0

我无法从 map 获取我的位置,它会引发空指针异常。

        if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        try {
            mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.mapFrag)).getMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
            mMap.getUiSettings().setZoomControlsEnabled(true);
            putMarkerOnMap(mMap.getMyLocation().getLatitude(),mMap.getMyLocation().getLongitude());
        }

它在行抛出错误..我调用函数 putMarkerOnMap(lat,lng) 这是那个函数

    public void putMarkerOnMap(double la , double lo){
    LatLng position = new LatLng(la,lo);
    mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)).title("Your Location"));
    CameraPosition campos = new CameraPosition.Builder().target(position).zoom(15)
            .bearing(90)
            .tilt(40)
            .build();
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(campos));
}
4

2 回答 2

1

我认为NPE是在这一行引起的

mMap.getMyLocation().getLatitude()

此外,如果您想获取当前位置,您应该使用不同的方法,例如使用 Google Play Services 或 Android 内置库

谷歌播放服务:http: //developer.android.com/training/location/retrieve-current.html

Android 内置库:http: //developer.android.com/guide/topics/location/strategies.html

于 2016-03-27T07:52:56.573 回答
1

该方法getMyLocation()已弃用。所以不要使用它。而是使用 Google Play 服务提供的 FusedLocation API 来获取当前位置。

检查这个

于 2016-03-27T08:04:07.107 回答