Search code examples
androidgoogle-mapsgoogle-maps-markerssupportmapfragment

Add Marker to Google Map once data is available?


I'm trying to add a marker to my google maps using the Long/Lat that i am retrieving from my database. However, i can't seem to get it to add a marker outside of the onMapReady.

My map fragment inside my activities layout

<fragment android:name="com.google.android.gms.maps.SupportMapFragment"
                        android:id="@+id/map"
                        android:layout_width="match_parent"
                        android:layout_height="400dp"/>

OnCreate

mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

OnMapReady

@Override
    public void onMapReady(GoogleMap map) {
        map.addMarker(new MarkerOptions()
                .position(new LatLng(1, 1))
                .title("jjj"));
    }

I basically need to get a reference to the map that allows me to add a marker away from that OnMapReady method.


Solution

  • This is the right way of doing it, loading the map asynchronously. If you really want to set a marker outside of the onMapReady method consider a new attribute inside this class that will keep a reference to the GoogleMap object you get in onMapReady method. But pay attention when you call this attribute as it might not be set yet (NullPointerException)! Also you may want to unset the attribute when you don't need it any more, so you don't have a memory leak.

    ...
    
    private GoogleMap mMyGoogleMap;
    
    ...
    
    @Override
    public void onMapReady(GoogleMap map) {
        mMyGoogleMap = map;
    }