brainmurphy1
brainmurphy1

Reputation: 1112

Using new OnMyLocationChangeListener in Google Maps Android API v2

Google finally added a callback for location changes in the Android API v2! However, I cannot intuitively get it to work, and Google does not have much documentation for it. Has anyone gotten it to work? What more do I need?

    public class ... extends SupportMapFragment implements GoogleMap.OnMyLocationChangeListener {
GoogleMap map;
LocationManager locationManager;
String provider;

        @Override
        public void onActivityCreated(android.os.Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            map = getMap();
                    if (map != null) {
                       Criteria criteria = new Criteria();
                       criteria.setAccuracy(Criteria.ACCURACY_FINE);
                           locationManager =(LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
                provider = locationManager.getBestProvider(criteria, false);
            }
        }

        @Override
        public void onResume() {
            super.onResume();
            while(map == null) {
                map = getMap();
                map.setMyLocationEnabled(true);
                map.setOnMyLocationChangeListener(this);
            }
        }
        @Override
        public void onMyLocationChange(Location loc) {
            //implementation
        }
}

Upvotes: 2

Views: 9543

Answers (1)

ullstrm
ullstrm

Reputation: 10170

This is how I do to navigate to the center of the map when we get the first location-update.

my class header:

public class FragActivity extends SherlockFragmentActivity implements  OnMyLocationChangeListener

private GoogleMap mMap;

my mMap-setup:

    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = customMapFragment.getMap();

        // Check if we were successful in obtaining the map.
        if (mMap != null)
            setUpMap();
    }

setUpMap-method:

private void setUpMap() {
    mMap.setMyLocationEnabled(true);
    mMap.setOnMyLocationChangeListener(this);
}

and my onlocationchange:

@Override
public void onMyLocationChange(Location lastKnownLocation) {
    CameraUpdate myLoc = CameraUpdateFactory.newCameraPosition(
            new CameraPosition.Builder().target(new LatLng(lastKnownLocation.getLatitude(),
                    lastKnownLocation.getLongitude())).zoom(6).build());
    mMap.moveCamera(myLoc);
    mMap.setOnMyLocationChangeListener(null);
}

Works like a charm

Upvotes: 7

Related Questions