【问题标题】:I am receiving null pointer exception , when i try to get mylocation from map当我尝试从地图中获取 mylocation 时,我收到空指针异常
【发布时间】:2016-07-14 16:34:21
【问题描述】:

我无法从 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));
}

【问题讨论】:

    标签: android google-maps android-fragments google-latitude


    【解决方案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

    【讨论】:

      【解决方案2】:

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

      查看this

      【讨论】:

      • 实际上我需要片段中的位置....我可以在片段中使用 FusedLocation API
      • 是的,它与片段一起工作..有一个问题..它给了我旧位置而不是我现在所在的更新位置!而我正在调用内置函数的最后一个已知位置......是否有任何函数可以给我当前位置......这里是代码`@Override public void onConnected(Bundle bundle){ mLastLocation = LocationServices.FusedLocationApi.getLastLocation( mGoogleApiClient); if (mLastLocation != null) { putMarkerOnMap(mLastLocation.getLatitude(),mLastLocation.getLongitude()); } }`
      • 它应该返回可用的最新位置。阅读this了解更多详情并选择最适合您的方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      相关资源
      最近更新 更多