Adding Google Maps to a RecyclerView

自古美人都是妖i 提交于 2020-07-02 10:50:34

问题


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 ?


回答1:


There are tow possibliy 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 bellow,

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;
            }

        }
    }



回答2:


there is something called lite mode in google map you can use in recycler view

check this litemode

and sample code example LiteListDemoActivity




回答3:


For example you can use Glide and load map preview, not map fragment Like this:

    GlideApp
        .with(context)
        .load("http://maps.google.com/maps/api/staticmap?center=" + 
               lat + 
               "," + 
               lng + 
               "&zoom=15&size=200x200&sensor=false" +
               "&markers=color:red%7Clabel:C%" + 
               markerLat + 
               "," + 
               markerLlng)
        .centerCrop()
        .into(myImageView);

Or using lib - static-maps-api



来源:https://stackoverflow.com/questions/51209686/adding-google-maps-to-a-recyclerview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!