2

我正在使用适用于 Android v2 的 Google 地图。我想显示当前用户位置并放大它。这是 中的代码FragmentActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.map_activity);

    mMap = ((SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.mapFragment_mapActivity)).getMap();
    if (mMap == null) {
        Toast.makeText(this, R.string.mapCreationProblem, Toast.LENGTH_LONG)
                .show();
        finish();
        return;
    }
    mMap.setMyLocationEnabled(true);
    Location currentLocation = mMap.getMyLocation();
    if(currentLocation!=null){
       LatLng currentCoordinates = new LatLng(
                            currentLocation.getLatitude(),
                            currentLocation.getLongitude());
       mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentCoordinates, 10));
    }
}

地图工作正常,当前位置上的蓝点也工作正常。但它似乎currentLocation总是为空。所以我无法放大当前位置。

请问哪位大神知道为什么?

4

2 回答 2

8

这是一个 getMyLocation() 的实现,增加了查找人员位置的保护。我只是在管理地图片段的活动中拥有它。

private Location getMyLocation() {
    // Get location from GPS if it's available
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    // Location wasn't found, check the next most accurate place for the current location
    if (myLocation == null) {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_COARSE);
        // Finds a provider that matches the criteria
        String provider = lm.getBestProvider(criteria, true);
        // Use the provider to get the last known location
        myLocation = lm.getLastKnownLocation(provider);
    }

    return myLocation;
}

谢谢, 曼

于 2013-01-24T21:21:39.740 回答
1

尝试使用 LocationManager:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
于 2013-01-24T13:19:30.250 回答