我无法从地图获取我的位置,它会抛出空指针异常。
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));
}
答案 0 :(得分:1)
我认为NPE是在这一行引起的
mMap.getMyLocation().getLatitude()
此外,如果您想获取当前位置,则应使用不同的方法,例如使用Google Play服务或Android内置库
Google Play服务: http://developer.android.com/training/location/retrieve-current.html
Android内置库: http://developer.android.com/guide/topics/location/strategies.html
答案 1 :(得分:1)
不推荐使用方法getMyLocation()
。所以不要使用它。而是使用Google Play服务提供的FusedLocation API来获取当前位置。
检查this