Andrew Ebling Andrew Ebling - 1 year ago 80
Android Question

Automate pressing the My Location button on a MapView

I have a

within a
and I'm already displaying the users location via
. 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
from the
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
and calculate and animate to a
? 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 Source

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(
                        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())) //

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download