Mika
Mika

Reputation: 5845

MapView fix not compling

I get the following error with my MapView: "CameraUpdateFactory is not initialized"

Many posts out there suggest adding: MapsInitializer.initialize(this); but now IDE is telling me: "GooglePlayServicesNotAvailableException is never thrown"

My code is below:

XML:

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

And code to run it:

    mapView = (MapView) header.findViewById(R.id.mapview);
    map = mapView.getMap();

    try {
        MapsInitializer.initialize(this);
    } catch (GooglePlayServicesNotAvailableException e) {
        e.printStackTrace();
    }

    // Updates the location and zoom of the MapView
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
    map.animateCamera(cameraUpdate);

Upvotes: 0

Views: 111

Answers (1)

Dan Harms
Dan Harms

Reputation: 4840

First off, you are getting a compiler warning because MapsInitializer.initialize(this); does not throw a GooglePlayServicesNotAvailableException. So by surrounding it with a try/catch, you are introducing unreachable code in the catch.

Now the reason that you need to call onCreate and onResume is that there are lifecycle events logic that Google needs to perform in order for the MapView to function properly. If you were using a MapFragment this is taken care of for you in the background. Ideally, you put these method calls in their respective Activity/Fragment methods. So call mapView.onCreate() in your onCreate method, mapView.onResume() in onResume, etc. You should also add calls to onPause and onDestroy as well.

Hope that clears things up for you. Feel free to follow up with any questions about this.

Upvotes: 1

Related Questions