How to select and deselect a marker in google maps in android?

孤街醉人 提交于 2019-12-18 09:13:22

问题


I have a list of places which are marked in google maps using Markers. I want to select a Marker so that it will highlight with a different color. I have set it using marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)). When I click on the same marker or any other marker I want remove the selection made in the first marker and set it back to the default color.

 map.setOnMarkerClickListener(new OnMarkerClickListener() {

    @Override
    public boolean onMarkerClick(Marker marker) {

        aa= marker.getPosition().latitude;
         bb=marker.getPosition().longitude;
        marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

        }

According to the code above when i click on other markers the selection made in the first marker is still there, and it stays colored HUE_BLUE. How can I remove the modified color and transfer the selection to currently clicked marker?


回答1:


I just tested this and it works, just add a Marker reference as an instance variable in order to keep a reference of the last clicked Marker, and each time a new Marker is clicked, set the previous one back to the default color.

You can also check !marker.equals(prevMarker) before setting the Marker to HUE_BLUE, this will allow a subsequent click on the Marker to set the color back to the default color.

Instance variable:

Marker prevMarker;

Click Listener:

mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {

            aa= marker.getPosition().latitude;
            bb=marker.getPosition().longitude;
            if (prevMarker != null) {
                //Set prevMarker back to default color
                prevMarker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
            }

            //leave Marker default color if re-click current Marker
            if (!marker.equals(prevMarker)) {
                marker.setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
                prevMarker = marker;
            }
            prevMarker = marker;
            return false;
        }

    }); 


来源:https://stackoverflow.com/questions/29740839/how-to-select-and-deselect-a-marker-in-google-maps-in-android

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