Andrew Ebling Andrew Ebling - 2 months ago 9
Android Question

Automate pressing the My Location button on a MapView

I have a

MapView
within a
Fragment
and I'm already displaying the users location via
setMyLocationEnabled()
. Everything is working as expected.

For the typical use-case I want to zoom to the user's location - the exact behaviour of pressing the "My Location" button on the stock maps UI.

I want to save the user from having to press the My Location button and automate this step, but I cannot see from the APIs how to do this. I can get the
UiSettings
from the
GoogleMap
but this only seems to allow me to query/set the state of the map UI (i.e. whether the My Location is enable and therefore available to be pressed).

Or do I really have to setup a
LocationClient
and calculate and animate to a
CameraUpdate
? This seems like a lot of legwork to do something quite common/simple. The logic of implementing this properly (i.e. as the user would expect it to behave) is more involved than it seems at first sight and I'm keen to avoid duplicating code which has clearly already been implemented within Google Maps.

Answer

To move the map camera position to user location you have to find the user location first and by using locationmangaer class object you can get that in onLocationChange method

LocationManager locationManager = (LocationManager) getActivity().getSystemService(
                Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER, 0, 0, this);

//... 

public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(location.getLatitude(), location
                        .getLongitude())) //
                .zoom(9).build();
        map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        locationManager.removeUpdates(this);
}
Comments