stkent
stkent

Reputation: 20128

getMapAsync() - call once and save the result, or call every time I need the map?

Google Play Services 6.5 added the getMapAsync method, which allows us to asynchronously retrieve the GoogleMap object that backs a MapFragment (or MapView). The documentation states that

The GoogleMap object provided by the callback is non-null.

I don't have a great understanding of why asynchronous retrieval is required here (i.e., what circumstances could cause the deprecated getMap method to return null), which has led me to the following question:

When working with a MapFragment, should I call getMapAsync once in onCreate, store the (non-null) GoogleMap returned by the callback, and then reference this stored result everywhere else in my class? Or, should I call getMapAsync every time I need to interact with the GoogleMap object, and do all map-related work inside the corresponding callbacks?

The first option leads to more compact code, so I'd prefer to use it if possible. Is there any risk that the GoogleMap object I store could become 'stale' or null (in which case the second option would be safer)?

Upvotes: 3

Views: 1622

Answers (1)

SnyersK
SnyersK

Reputation: 1296

Google's map-related examples, located in the directory

<path-to-sdk>/extras/google/google_play_services/samples/maps

keep a reference, so I believe this should be fine.

The reason you have to use the async call is (I suppose), because the map probably does network requests while it's initializing (to download the tiles etc, see the docs for more info). If this is the case, the map needs to be (partially) initialized on a separate thread. Therefore you will have to wait until the initialization is finished before you can get the GoogleMap.

The getMap() function can return the GoogleMap correctly, but it's not guaranteed. If you call the getMap() function too soon, the map won't be initialized yet and it will return null.

Upvotes: 5

Related Questions