Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
Andrew Ebling Avatar asked May 01 '14 10:05

Andrew Ebling


2 Answers

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);
}
like image 195
Asheesh Avatar answered Sep 28 '22 07:09

Asheesh


Hierarchy Viewer says the id of the "my location button" is 0x2. So, with that information you can use SupportMapFragment.getView to call View.findViewById and then View.performClick.

Here's an example:

final SupportMapFragment smf = (SupportMapFragment) getSupportFragmentManager()
        .findFragmentById(R.id.map);
smf.getView().findViewById(0x2).performClick();

I ran this in the "My Location Demo" provided in the Google Play Services samples and it worked.

The demo is located in: <android-sdk>/extras/google-play-services/samples/maps

like image 28
adneal Avatar answered Sep 28 '22 07:09

adneal