Remove previous Marker and add new Marker in Google Map v2

前端 未结 8 780
不思量自难忘°
不思量自难忘° 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:04

    Just creat a new marker object and before adding a new marker, remove the previous one

    Marker marker;
    
    MAP.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
    
                    @Override
                    public void onMapLongClick(LatLng arg0) {
                        if (marker != null) {
                            marker.remove();
                        }
                        marker = MAP.addMarker(new MarkerOptions()
                                .position(
                                        new LatLng(arg0.latitude,
                                                arg0.longitude))
                                .draggable(true).visible(true));
                    }
                });
    

    EDIT

    Do the same for OnMapClick

    MAP.setOnMapClickListener(new OnMapClickListener() {
            @Override
            public void onMapClick(LatLng point) {
                // TODO Auto-generated method stub
    
                    if (marker != null) {
                        marker.remove();
                    }
                marker = MAP.addMarker(new MarkerOptions()
                        .position(currentPosition)
                        .snippet(
                                "Lat:" + location.getLatitude() + "Lng:"
                                        + location.getLongitude())
                        .icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
                        .title("ME"));
                Log.e("lat", "" + point);
    
            }
        });
    

提交回复
热议问题