本文介绍了以编程方式创建MapView和添加标记会导致片段中出现空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试以编程方式创建MapView并添加MarkerPosition,如下所示:
I am trying to create a MapView programmatically and add a MarkerPosition as shown below:
MapView mapView = new MapView(getActivity());
((ViewGroup) rootView).addView(mapView);
GoogleMap googleMap = mapView.getMap();
googleMap.addMarker(new MarkerOptions()
.position(new LatLng(
Double.parseDouble(
mEvent.getEventInfo().mEventData.mLat),
Double.parseDouble(
mEvent.getEventInfo().mEventData.mLng)))
.title("Marker"));
清单文件:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<permission
android:name="com.example.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.example.permission.MAPS_RECEIVE" />
我遇到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference
推荐答案
,因为您的googleMap尚未加载,但表示null,并且您要在其上添加标记,从而导致崩溃.最好使用mapView.getMapAsync(context);
而不是mapView.getMap();
并实现此方法
because your googleMap is not loaded yet means null and you are adding marker on it which is causing a crash. better to use mapView.getMapAsync(context);
rather than mapView.getMap();
and implement this method
@Override
public void onMapReady(final GoogleMap map) {
if(map != null){
// you are ready to add marker here
}
}
这篇关于以编程方式创建MapView和添加标记会导致片段中出现空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!