Remove previous Marker and add new Marker in Google Map v2

前端 未结 8 772
不思量自难忘°
不思量自难忘° 2021-02-05 07:40

I want to remove a current marker after long click on map anywhere and recreate a new marker at that point. I have cleared google map on long click on map and new marker is crea

8条回答
  •  不知归路
    2021-02-05 08:12

    For the people who have tried the first solution in this question and you get the error of Marker has not been intialized.

    Because, we are comparing the marker and null. When we have not even intialized the marker in the first place.

    Solution:

    Int mMarkerCount = 0; //Global Variable
    Marker mMarker; //Global Variable
    
    if(mMarkerCount > 0){
        if(mMarker != null){
            mMarker.remove();              
        }
    }
    
    mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
    mMarkerCount++;
    

    The Solution for the question:

    Int mMarkerCount = 0; //Global Variable
    Marker mMarker;
    
    mMap.setOnMapClickListener(new OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latlng) {
            if(mMarkerCount > 0){
                if(mMarker != null){
                    mMarker.remove();              
                }
            }
    
            mMarker = mMap.addMarker(new MarkerOptions().position(latLng));
            mMarkerCount++;  
        }
    });
    

    In the beginning, the count is going to be zero. So, the marker remove method will not be called. Once, the marker is intialized and the count is incremented. We can remove the previous marker by the help of the remove method and create a new marker as shown in the code.

提交回复
热议问题