I have declared the Location source and destination as global variable. But though I am not getting the right value in dist. What should I do pass the values of location outside of geoFire.getLocation() mehtod? Or how may I get distance between two geolocation by geofire?
I have tried by making the source and the destination static. But it didn't work.
public double get_distance(String from, String to)
{
source = new Location("to");
destination = new Location("form");
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
GeoFire geoFire = new GeoFire(databaseReference);
geoFire.getLocation(from, new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
source.setLatitude(location.latitude);
source.setLongitude(location.longitude);
Log.e("source latlong b4 ",source.getLatitude()+" .. "+source.getLongitude()); // the right value is passed
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("source latlong ",source.getLatitude()+" .. "+source.getLongitude()); //value hase turned into 0.0
geoFire.getLocation(to, new LocationCallback() {
@Override
public void onLocationResult(String key, GeoLocation location) {
destination.setLatitude(location.latitude);
destination.setLongitude(location.longitude);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
Log.e("destination latlong", destination.getLatitude()+" .. "+destination.getLongitude());
dist= source.distanceTo(destination);
return dist;
}
Firebase APIs are asynchronous, meaning that onLocationResult()
method returns immediately after it's invoked, and the callback from the Task it returns, will be called some time later. There are no guarantees about how long it will take, it may take from a few hundred milliseconds to a few seconds before that data is available.
Because that method returns immediately, the value of your dist
variable you're trying to return as a result of a method, will not have been populated from the callback yet.
Basically, you're trying to return a value synchronously from an API that's asynchronous. That's not a good idea. You should handle the APIs asynchronously as intended.
A quick solve for this problem would be to use the value of your dist
variable only inside the onLocationResult()
method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.