显示在当前用户位置放大(Zoom on current user location displaye

2019-07-18 16:13发布

我使用谷歌地图Android版V2。 我想显示当前用户位置和放大它。 下面是在代码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总是空。 因此,我不能放大的当前位置。

谁知道为什么吗?

Answer 1:

这里是)与寻找的人的位置额外保护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;
}

谢谢,DMAN



Answer 2:

尝试使用的LocationManager:

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location currentLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);


文章来源: Zoom on current user location displayed