문제

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.

도움이 되었습니까?

해결책

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);
}

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top