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"));
Manifest File:
<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" />
I am getting the following error:
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
Google map should now be loaded async, by adding a MapFragment to your view and then work on it. Something like that will work :
With this layout
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 thanmapView.getMap();
and implement this methodHave your activity implement OnMapReadyCallback and add the marker in OnMapReady() function.
Refer: https://developers.google.com/maps/documentation/android-api/start
It turns out that on google play services version
11.8.0
onCreatea()
andonResume()
are mandatory to see MapView: