在Google Maps Android API v2中使用新的OnMyLocationChangeListener

时间:2013-02-27 04:08:50

标签: android google-maps-android-api-2

Google最终在Android API v2中添加了位置更改回调!但是,我无法直观地将其用于工作,Google也没有太多文档。有没有人让它上班?我还需要什么?

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

1 个答案:

答案 0 :(得分:7)

当我们获得第一个位置更新时,这就是我导航到地图中心的方式。

我的班级标题:

public class FragActivity extends SherlockFragmentActivity implements  OnMyLocationChangeListener

private GoogleMap mMap;

我的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-方法:

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

和我的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);
}

像魅力一样工作