KaiteN
KaiteN

Reputation: 53

Android wait for GoogleMap.OnMyLocationChangeListener

Im using GoogleMap.OnMyLocationChangeListener to get the current location (below)

private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        start = new LatLng(location.getLatitude(), location.getLongitude());
        map.addMarker(new MarkerOptions().position(start));
    }
};

However, I need a way to wait for the listener to complete. Reason being that, Start var will obviously be null if I continue to execute other code without location data. I thought that AsyncTask might be useful here, but have no idea what to call inside doInBackground/onPostExecute.

map.setOnMyLocationChangeListener(myLocationChangeListener); // set the listener
// perform wait and initiate start variable
String url = getDirectionsUrl(start, destination);
// a sync task here using the url

Any hints or code snippets would be much appreciated~!

Upvotes: 0

Views: 1700

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007349

I need the location information after setting the listener

That is not possible. There may not be any "location information after setting the listener". It may take some time to get a location fix. Given your existing code, your first opportunity to have location data will be in onMyLocationChange(), and you cannot use the location data before that point.

Also note that setOnMyLocationChangeListener() has been deprecated for about a year. Quoting the documentation:

This method is deprecated. use FusedLocationProviderApi instead. FusedLocationProviderApi provides improved location finding and power usage and is used by the "My Location" blue dot. See the MyLocationDemoActivity in the sample applications folder for example example code, or the Location Developer Guide.

Upvotes: 2

Related Questions