How to add a GoogleMap v2 MapView in your Android application

Today I wanted to convert my existing Android application to use the MapView View object rather than the fragment based object. This was partly to allow me to create some Espresso based matchers etc. but also I didn’t need the fragment approach for my application.

The first change was the the layout xml file. I needed to replace the fragment below.


<fragment
android:id="@+id/mapView"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

with the following mark up.


<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />

The next task is mentioned in the JavaDoc for com.google.android.gms.maps.MapView it states that you have to pass through your Activity or Fragment lifecycle events through to the View object.

To start off with it would be a good idea in your onCreate method you initialise your member variable for your MapView object using the code below and then immediately call the MapView’s onCreate method. You can then use this variable in the other lifecycle methods.


@Override
public void onCreate() {
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
}

Example of passing the activity lifecycle events through to the MapView.

@Override
public void onLowMemory() {
mapView.onLowMemory();
super.onLowMemory();
}

Initially I thought this was all that was needed however, on starting the application and then animating the position on the map using a CameraUpdateFactory I got the error java.lang.NullPointerException: CameraUpdateFactory is not initialized logcat exception a bit of googling found the stackoverflow article that said I needed to call MapsInitializer.initialize(this);

I added this to the onCreate method of my activity immediately after calling mapView.onCreate(savedInstance);


@Override
public void onCreate() {
mapView = (MapView)findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
MapsInitializer.initialize(this);
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s