jamcoupe
jamcoupe

Reputation: 1452

how to clear previous google map markers so only one is on the map at a time

I am trying to make this map only allow one marker on the page at any time but when I click a new marker is placed along with old ones.

Does anyone know how you would make this happen?

google.maps.event.addListener(map, 'click', function(event) {
                //set up variables
                var clickLat = event.latLng.lat();
                var clickLng = event.latLng.lng();

                //show lat and long
                var loc = document.getElementById("location");
                var info = "Latitude: "+clickLat+" "+", longitude: "+clickLng;
                loc.innerHTML = info;

                //place marker
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(clickLat, clickLng),
                    map: map,
                    animation: google.maps.Animation.DROP
                });

            });

Upvotes: 2

Views: 5046

Answers (3)

Lucas
Lucas

Reputation: 949

declare a Marker field:

private Marker marker;

then, for the setOnMapClickListener method of your GoogleMap object, do the following:

@Override
public void onMapClick(LatLng point) {
 if(marker!=null)  marker.remove();
 markerSelectedPlace = new MarkerOptions().position(point).title(
                            "dfsdfsdfs dfsdfsdf"); 
 marker = mMap.addMarker(markerSelectedPlace);
 mMap.addMarker(markerSelectedPlace);
 marker.showInfoWindow();

}

Upvotes: 0

Kathryn Hurley
Kathryn Hurley

Reputation: 1094

Another option would be to have a single marker variable and update the position of the marker when someone clicks on the map.

Upvotes: 2

ninty9notout
ninty9notout

Reputation: 1116

I believe your answer is in the Google Mapa API. You just have to set the map of your old marker to null.

Read this: http://code.google.com/apis/maps/documentation/javascript/overlays.html#RemovingOverlays

Upvotes: 4

Related Questions