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
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
}
}
Google map should now be loaded async, by adding a MapFragment to your view and then work on it. Something like that will work :
public class MainActivity extends Activity implements OnMapReadyCallback {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_activity);
MapView mapView = new MapView(this);
((LinearLayout) findViewById(R.id.mapWrapper)).addView(mapView);
mapView.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap map) {
map.addMarker(new MarkerOptions()
.position(new LatLng(0, 0))
.title("Marker"));
}
}
With this layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mapWrapper"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Have 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()
and onResume()
are mandatory to see MapView:
@Override public void setupMap(LatLng latLng) {
if (mapView == null) {
mapView = new MapView(getActivity());
rootLayout.addView(mapView);
mapView.onCreate(Bundle.EMPTY);
}
mapView.getMapAsync(map -> {
map.clear();
map.addCircle(MapUtil.makeDefaultGreenCircle(getActivity(), latLng));
});
}
@Override public void onResume() {
super.onResume();
mapView.onResume();
}