androidandroid-mapviewandroid-maps-v2

Adding Google Maps to a RecyclerView


I have added the map view inside the RecyclerView alongside other types of list items but now ... how and where do I initialize the map, where do I listen for onMapReady so that I can place a marker afterwards, and how do I handle the recycling of the item ?

Any ideas what the best practice is in this situation ?


Solution

  • There are two possible ways, to do this thing,
    one is Google Static Maps API using, which will give you the snapshot of the map.

    Another is, you can use com.google.android.gms.maps.MapView inside of recycler item and initialize in your viewholder like below,

    public class AdapterWithMap extends RecyclerView.Adapter<AdapterWithMap.CustomeHolder> {
    
            @Override
            public void onBindViewHolder(CustomeHolder holder, int position)
            {
                GoogleMap thisMap = holder.mapCurrent;
                if(thisMap != null)
                    thisMap.moveCamera();//initialize your position with lat long  or move camera
            }
            @Override
            public void onViewRecycled(CustomeHolder holder)
            {
                // Cleanup MapView here?
                if (holder.mapCurrent != null)
                {
                    holder.mapCurrent.clear();
                    holder.mapCurrent.setMapType(GoogleMap.MAP_TYPE_NONE);
                }
            }
            public class CustomeHolder extends RecyclerView.ViewHolder implements OnMapReadyCallback {
                GoogleMap mapCurrent;
                MapView map;
    
                public CustomeHolder(View view) {
                    super(view);
                    map = (MapView) view.findViewById(R.id.mapImageView);
                    if (map != null)
                    {
                        map.onCreate(null);
                        map.onResume();
                        map.getMapAsync(this);
                    }
    
                }
    
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    MapsInitializer.initialize(getApplicationContext());
                    mapCurrent = googleMap;
                }
    
            }
        }