android - 放大显示的当前用户位置

标签 android android-maps android-maps-v2

我使用的是 Android 版 Google map 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));
    }
}

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

谁知道为什么,请问?

最佳答案

这里是 getMyLocation() 的一个实现,增加了查找人员位置的保护。我只是在管理 map fragment 的 Activity 中有这个。

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

谢谢, 德曼

关于android - 放大显示的当前用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14502102/

相关文章:

android - 与 Fragment (GMap) 一起使用时 SlidingMenu 上的空白屏幕

java - 带有标记的 Google Maps Android API 问题

android - 替换默认的 Android Maps API v2 更改 MyLocation 图标

java - 多线程访问数组

android - Android 中的 Google map 标记集群

google-maps - 嵌入式 Google map 无法在 WebView 中获取当前位置

android - requestLocationUpdates 与位置监听器

android - 如何覆盖相机 Activity 的 onBackPressed ?即 android.provider.MediaStore.ACTION_IMAGE_CAPTURE

java - Android 应用程序 - 带有相机应用程序的弹出菜单

Android - 在调用 stopService 时销毁服务