Steven
Steven

Reputation: 915

Is there a way to get notified when the GoogleMap is ready in a MapView object in the new Google Maps Android API v2?

I implementing the new Google Maps Android API right now within my app, and there are a few things that I want to do when the map has loaded such as moving the map to the current location and displaying a marker there and enabling certain overlays like the satellite view. However, I am running into NPEs when I try to access the Mapview's getMap() because the GoogleMap object isn't ready.

Is there a way to detect when a MapView's GoogleMap is ready? I found CommonsWare's suggestion for dealing with the SupportMapFragment and detecting when getMap() will not get null, but what would the equivalent event by for a MapView?

CommonsWare's suggestion for SupportMapFragment: How do I know the map is ready to get used when using the SupportMapFragment?

This seems kind of broken that there is not a way to determine when the GoogleMap object is ready so that we can do all these setup things.

Upvotes: 0

Views: 1316

Answers (1)

Ryan
Ryan

Reputation: 2260

To use the MapView directly you need to make sure you forwarding the Activity lifecycle methods through to the MapView.

E.g. to set it up, you'd do this in your onCreate()

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.raw_mapview_demo);

    mMapView = (MapView) findViewById(R.id.map);
    mMapView.onCreate(savedInstanceState);

    setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
    if (mMap == null) {
        mMap = ((MapView) findViewById(R.id.map)).getMap();
        if (mMap != null) {
            setUpMap();
        }
    }
}

The code is taken from Google's sample code that is included with the Play Services lib. You also need to route onDestroy(), onResume(), and onPause().

FYI you need to check for a null pointer for both the MapView and MapFragment as the user may not have Google Play Services installed. If it isn't installed the user should get a prompt to install the APK and then you can return to this Activity.

Hope that helps.

Ryan

Upvotes: 2

Related Questions