Dynamically updating geopoint values in a firestore database - firebase

I am building a react-native app with firebase that monitors the user's location and stores it in a Firestore database via a geopoint. I have retrieved the user's longitude and latitude position and now I basically want to store it.
This is my database function:
//setting the geolocation of the logged in user
export const updateLocation =(uid, data)=>{
const userRef = doc(db, "users", uid);
return setDoc(userRef, data); // overwrite the location value if already set
}
Once I've fetched the longitude and latitude I try to call the function like so:
updateLocation(auth.uid,{location:{latitude : location.coords.latitude , longitude : location.coords.longitude}});
I can't quite figure out is there a problem with my syntax or if I need to rethink this functionality using something like geohashing. I can't quite see in the firebase documentation how to update geopoint values

Related

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});

Fetching data from sqflite and sending it to firebase

I made a local database using sqflite to save data locally and i need to send it to a firebase in need
so far the function i used to get the data is:
Future<List> getNameAndPrice() async{
Database db = await instance.database;
var result = await db.rawQuery('SELECT $columnName , $columnAmount FROM $table');
return result.toList();
}
the other function i use in the other page of flutter to get the data is:
Future sendtofirebase() async {
var orders = await dbHelper.getNameAndPrice();
print(orders);
}
so far the print is just to check the data i get and i get the data in this format:
I/flutter (21542): [{name: Regular burger, amount: 2}, {name: Cheese
burger, amount: 1}]
i just want to find a way to like fetch this data from the variable and then send it to the firebase database i've made firestore collectionreference and everything i just don't know how can i get the name alone and send it then send the amount of the item etc.. for each order (how to get each item individually and send it to the firebase db).
really looking forward for answers cause i've spent time looking and i am stuck there..
ps. i am still a beginner and i even don't know if i should use both sqflite and firebase
other than just saving everything in the firebase itself.. thank you for reading.

Firestore Collection (with Subcollection) to Sqflite Item in Flutter

My application is using firestore database. I design categories and its subcategories of the content by using subcollection.
To make offline mode feature;
I want to save this firestore data to sqflite database.
I learned that I convert firebase data map to text for sqlite
But I counl't find a way to locate the subcollections.
var catagorySnapshots =
await _firestore.collection("categories").getDocuments();
List _list = [];
catagorySnapshots.documents.forEach((_snapshot) {
CategoryInformation categoryInformation = CategoryInformation();
CategoryItem curCategory =
CategoryItem.fromCollection(_snapshot.documentID, _snapshot.data);
categoryInformation.categoryList.add(curCategory);
print(curCategory.title);
//
// sub collections
//
});
I know its too late to answer, this might help someone else.
You have to try getting the information from snapshot.data['field'] like so and covert it to text as well.
Let me know of that works.

How to retrieve data from firebase and then update the data using Swift5

After the current user watches the video ad, it will retrieve their point (which is stored in the firebase) and add 1 to their point. Then, it will update the document and also display the number of points the user has. It seems like everything is okay, except, I can't do scoreText.text = point
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
let dBRef = Database.database().reference()
dBRef.child("Users").child(Auth.auth().currentUser!.uid).queryOrderedByKey().observeSingleEvent(of: .value, with: { snapshot in
guard let dict = snapshot.value as? [String:Any] else {
print("Error")
return
}
var point = dict["point"] as? Int
point!+=1
dBRef.child("users").child(Auth.auth().currentUser!.uid).setValue(["point": point])
scoreText.text = point
})
How would I display the user's points?
[UPDATED CODE]
Changed code to access Cloud Firestore, not Realtime Database
func rewardBasedVideoAd(_ rewardBasedVideoAd: GADRewardBasedVideoAd, didRewardUserWith reward: GADAdReward) {
//[START update_document-increment
let docRef = db.collection("users").document(UserID!)
// Atomically increment the population of the city by 1.
docRef.updateData([
"points": FieldValue.increment(Int64(1))
])
//[END update_document-increment]
//insert point value here
scoreText.text =
The code you're showing accesses the Realtime Database, while he screenshot shows Cloud Firestore. While both databases are part of Firebase, they're completely separate, and the API for one doesn't apply to the other.
To fix the problem, you will have to either use the Cloud Firestore API, or enter the data into the Realtime Database.

How to add Geopoint, timestamp and reference to a document in Firestore trough Flutter

It is fairly straightforward hot to set basic types inside Firestore.
But I cannot find how to construct Geopoint, Timestamp and another document reference with flutter Firestore plugin.
What do you assing inside data that you set to the coollection Map<String,dynamic> for each object?
Any help or examples?
I created manually an object on the server and got it inside my flutter app.
For TimeStamp you can pass DateTime object directly from dart.
For Geopoint there is GeoPoint object inside Firestore plugin.
new GeoPoint(longitude: 3.4, latitude: 4.5) })
For another document reference, you would pass DocumentReference that you retrieved as a value to the data object.
To create or update geopoint in firebase you can use the object GeoPoint(Latitude, Longitude) directly, this example from official documentation
CollectionReference users = FirebaseFirestore.instance.collection('users');
Future<void> updateUser() {
return users
.doc('ABC123')
.update({'info.address.location': GeoPoint(53.483959, -2.244644)})
.then((value) => print("User Updated"))
.catchError((error) => print("Failed to update user: $error"));
}
In the latest version of flutter a GeoPoint is created without named parameters.
GeoPoint(0, 0);
first argument => latitude
second argument => longitude

Resources