This is how my data is saved inside LiveTracker there is 2,8 which are bus route id and inside it there is auto generated firebase id and inside that id there is latitude and longitude and i wanna access those latitude and longitude but i am stuck at here and dont know how to fetch that data need soo help
This is my data format which i get when i print data
{-NCQE5NU7ajW2L57gt1o: {latitude: -122.07730612330596, longitude: 37.41749912586621}, -NCQF6O3vx2NYVdZKD0X: {latitude: -122.083922, longitude: 37.4214938}, -NCQF6kWJPOyLuymJeXz: {latitude: -122.07730453282453, longitude: 37.417496832888055}, -NCQF5afZXRqg1Heb9Oq: {latitude: -122.07730562660478, longitude: 37.417495975114676}, -NCQDoU67-ZjN4kNEyPr: {latitude: -122.07730474508638, longitude: 37.41749751091001},
this is how i am trying to fetch that latitude and longitude but i am stuck and dont know how to get it
_dbReference?.child("LiveTracker").child(passedId.toString()).onValue.listen((event) {
var data = event.snapshot.value;
print("This is data $data");
/* _markers.add(Marker(
markerId: MarkerId(DateTime.now().toIso8601String()),
position: LatLng(double.parse(event.snapshot.value.toString()),
double.parse(event.snapshot.value.toString()))));*/
});
data appears to be a Map object when you print it. Assuming your app code is aware of the autogenerated IDs, you can fetch latitude and longitude like so:
var data = event.snapshot.value;
var latitude = data['-NCQE5NU7ajW2L57gt1o']['latitude'];
var longitude = data['-NCQE5NU7ajW2L57gt1o']['longitude'];
print("$latitude, $longitude");
If I misunderstood and your issue is not being aware of the auto generated IDs, then you need to either restructure your data or fetch the keys at runtime with: data.keys.toList()
Related
I have a dating app similar to Tinder but for specific niche, the app stores the latitude and longitude from the user in his document on Cloud Firestore database, I have a method that returns the distance from a user in meters, I am using GeoLocator for that and with this I know the distance between the current user and another user.
static String getDistanceBetween({
double sourceLat,
double sourceLong,
double currentLat,
double currentLong
}) {
double _distanceInMeters = Geolocator.distanceBetween(
sourceLat,
sourceLong,
currentLat,
currentLong,
);
print(_distanceInMeters);
if(_distanceInMeters == null){
return "?";
} else if(_distanceInMeters == 0.0){
return "0";
} else {
return _distanceInMeters.toString().substring(0, 5);
}
}
When the user log in, I wanted to retrieve the nearest users first, what is the easiest way to retrieve documents from nearest users from the current user logged in?
If I could do something like this I think it solves the problem but I don't think it's possible to do with Firestore:
FirebaseFirestore.instance.collection("users").orderBy(getDistanceBetween(), descending: true).get().then((querySnapshot){
...
/// Get documents from users that are nearest to the current user
})
There is no way to order by distance, as that requires the database to perform a calculation for each document, which would make it impossible to meet its performance guarantees.
What you can do is retrieve the documents within a certain range from the second user. This is described in the Firestore documentation on geoqueries, but you can also read some of these previous questions on the topic, many of which use add-on libraries to accomplish the same.
Once you've retrieved the documents within the range, you'll then need to order them by their distance in your application code.
I am building an app where users can upload a location to a Firebase realtime database using GeoFire. The locations need to be associated with the specific user who uploaded them, and accompany other information input by the user. Right now, the code looks like this:
let key = Auth.auth().currentUser!.uid
let subkey = Int.random(in: 1..<100000)
let object: [String: Any] = [
"Type": type.text!,
"Contact": contact.text!,
"Price": price.text!,
"Availability": availability.text!
]
geoFireRef.child("\(key)").child("\(subkey)").setValue(object)
let location = manager.location!
geoFire.setLocation(location, forKey: "\(subkey)")
All of the data gets uploaded, including the location. All of the data entered by the user goes together into a new child of the user ID. However, the location data goes into a separate child outside of the user ID. The name of the new child is the same random number that is used to name the child containing the other data. However, again, the location data is stored outside of the user ID. Is there a method I can use to get the location data into the same child within the user ID? I've tried things like geoFireRef.child("\(key)").child("\(subkey)").setLocation(location) but such a method does not seem to exist. Is there a method I can use?
example of the database
Basically, what I've decided to do is, instead of using the setLocation method, I will just I declared let latitude = location.latitude and let longitude = location.longitude and uploaded those as values for keys called "latitude" and "longitude" to the database with the other dictionary entries. This works for my purposes.
l am trying to get objects keys from JSON API url , content on latitude and longitude from server . The data json api content on Object keys and those keys are change all time . l want to get only the coordinates inside of those Object keys and add it to leaflet map marker as array then show on map .
protected points: { lng: number, lat: number }[] = [];
Data : any
data(){
this.http.get("xxxxxxxxxxxx",{},{}).
then((data) => {
this.Data = JSON.parse(data.data);
this.points = Object.keys(this.Data)
.map(key => this.Data[key])
.map((position) => ({
lat: position[0],
lon: position[1]
}));
this.points.forEach((point) => {
new L.Marker([point]
Live code
new L.Marker([point]
Should have been:
new L.Marker(point (no need for square brackets)
Your point variable is already a LatLngExpression (in your case: an object with lat and lon properties)
How's it going?
I have the following data structure in Firebase:
reports
.XbCacF7tHosOZxxO(child generated by auto-id)
..userId: "XvSjDkLsaA8Se"
..message: "Text goes here"
..latitude: "30.123131"
..longitude: "50.3313131"
.Yoa7HsgTuWm97oP(child generated by auto-id)
..userId: "XvSjDkLsaA8Se"
..message: "Text goes here 2"
..latitude: "30.99999"
..longitude: "50.99999"
users
.XvSjDkLsaA8Se
..name: "John"
..email: "john#email.com"
The idea of the app is that users can make multiple "reports".
In future if I have hundreds of "reports" I don't want it to overload my query. So I'm trying to find a way using Geofire query.
My question is: Is there any way of getting only the "reports" near me using the radius feature from Geofire and the latitude and longitude from "reports"?
Thanks!
I've just found a way of doing that.
I had to save my Geofire node "reports_locations" with the same id generated by Auto Id at the moment of the creation of the report.
The func that my app saves the data on Firebase:
//Save data to Firebase Database
let key = report.childByAutoId().key
report.child(key).setValue(dataToSaveInFirebase)
//Save data to Geofire node
let userLocal = database.child("reports_locations")
let geoRef = GeoFire(firebaseRef: userLocal)
let location = CLLocation(latitude: self.localUser.latitude, longitude: self.localUser.longitude)
geoRef?.setLocation(location, forKey: key)
I hope it can help other people.
I have saved latitudes and longitudes for my points as Geography typed. I created custom api and I am able to retrieve points from closest by this code:
exports.get = function(request, response) {
var lat = request.query.latitude.replace(",",".");
var lng = request.query.longitude.replace(",",".");
var limit = +request.query.limit;
if (!limit) limit = 20;
console.log('Filtr: lat - %s, lng - %s, limit - %s', lat, lng, limit);
var mssql = request.service.mssql;
var queryString = "SELECT TOP (?) id, title, description, category, city, street, price, startdate, enddate, location.Lat latitude, location.Long longitude, location.STDistance(geography::Point(?, ?, 4326)) AS distance FROM Action ORDER BY distance"
mssql.query(queryString, [limit, lat, lng], {
success: function(results) {
request.respond(statusCodes.OK, results);
}
});
};
But I want to retrieve all points and I can't figure out how to do it. Now when I have just in script operation read:
function read(query, user, request) {
request.execute();
}
I get this in my object:
"location":{
"0":230,
"1":16,
"2":0,
"3":0,
"4":1,
"5":12,
"6":67,
"7":203,
"8":186,
"9":127,
"10":44,
"11":190,
"12":72,
"13":64,
"14":70,
"15":64,
"16":133,
"17":35,
"18":72,
"19":169,
"20":48,
"21":64,
"length":22
},
I was trying to modified sql script from custom api to apply to read operation but I don't know how to change query in read operation script. I was trying to work with success after executing request but It's too late. Anyone can help me with this?
I found solution to my problem:
function read(query, user, request) {
var queryString = "SELECT id, title, description, category, city, street, price, startdate, enddate, location.Lat latitude, location.Long longitude FROM Action";
mssql.query(queryString, {
success: function(results) {
request.respond(statusCodes.OK, results);
}
});
}
I tried this as first option before I asked the question but I tried it with this line:
var mssql = request.service.mssql;
But then I found example without this line and still with mssql object and it's working.