I want to enable location in Google Maps Android API v2. What I want is:
- load the map centered on a fix latitude/longitude,.
- Start listening to location changes, and once a provider (network/GPS) gets the location, center the map on this location and animate it (animation shall only run once). Meanwhile, location listener updates user's location after specified amount of time,
- Store this location data and use it to fetch nearby places of interest via my API.
I'm kind of confused with how to get periodic updates, the amount of time interval to choose. Right now, I have set up the project to show a map and used
googleMap.setMyLocationEnabled(true);
googleMap.setOnMyLocationChangeListener(myLocationChangeListener);
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location location) {
LatLng loc = new LatLng(location.getLatitude(), location.getLongitude());
if(googleMap != null){
if(!firstTime){
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(loc).zoom(zoom).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
firstTime = true;
}
lat = location.getLatitude();
lng = location.getLongitude();
Toast.makeText(context, "Location is: " + String.valueOf(lat) + ", "
+ String.valueOf(lng), Toast.LENGTH_LONG).show();
}
}
};
to set lat/lng in variables. My questions are:
- Is this a correct approach? Or can it be made better?
- The location change listener updates itself quite often. I'm seeing toasts being made in a few seconds interval. How to regulate that?
- How to stop the listener from fetching location when the activity's gone (paused/stopped)? Thank you!