简体   繁体   中英

How to remove map markers

I want to implement a map system where the user can select a point of origin and destination as two different markers.

When the user long clicks on the map they could select a button to use this location as a start or end point.

    case (R.id.setStart):
        markerStart = mMap.addMarker(new MarkerOptions()
        .position(this.startPoint)
        .title("Start")
        .draggable(true)
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));       
        outputName = rGC.getStringFromCoordinates(this.startPoint.latitude, this.startPoint.longitude);
        autocompleterStart.setText(outputName); 
        break;
    case (R.id.setEnd):
        markerEnd = mMap.addMarker(new MarkerOptions()
        .position(this.endPoint)
        .title("End")
        .draggable(true)
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))); 

However, when the user repeats the same process (select a new location as start/end), I want to be able to remove the previous marker. So if they select the same START button, the previous marker for start is removed and a new one is created.

Is there a way to check if a particular marker exists on the map. I tried adding marker.remove(); but it gives me a nullpointerexception.

        case (R.id.setEnd):
        markerEnd.remove();
        markerEnd = mMap.addMarker(new MarkerOptions()
        .position(this.endPoint)
        .title("End")
        .draggable(true)
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));     

Any ideas? Thanks in advanced!

you can use method which i have implemented in my app and working fine...for me

LatLng  latpoint;

MAP.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {

            @Override
            public void onMapLongClick(LatLng point) {
                // TODO Auto-generated method stub

                // MAP.clear();
                if (marker != null) {
                    marker.remove();
                }
                latpoint = point;
                marker = MAP.addMarker(new MarkerOptions()
                        .position(
                                new LatLng(latpoint.latitude,
                                        latpoint.longitude))
                        .title(point.toString()).draggable(true)
                        .visible(true));

            }

        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM