Search code examples
javaandroidgradlemaps

Google Maps .getMap() deprecated


I am using Google Maps on my Android App. Before a gradle the new version of Google Play Services it works with the following code to get the Fragment:

GoogleMap googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

Since I updated to version 9.2.1, the .getMap() is red (deprecated). Is there a new practise to declare the fragment?

Thank you for every response?


Solution

  • You should replace getMap() with getMapAsync().

    As per the official doc, get map async requires a callback and this is where yo do main google maps stuff. Have a look on the below snippet.

     public class MapPane extends Activity implements OnMapReadyCallback {
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map_activity);
    
        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }
    
    @Override
    public void onMapReady(GoogleMap map) {
    //DO WHATEVER YOU WANT WITH GOOGLEMAP
     map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            map.setMyLocationEnabled(true);
            map.setTrafficEnabled(true);
            map.setIndoorEnabled(true);
            map.setBuildingsEnabled(true);
            map.getUiSettings().setZoomControlsEnabled(true);
        }
    }
    

    Hope this helps you.