Each time I click on the map a new marker is placed on the map. The problem is that I need only one marker and if I click several times, each time a new marker is added.
How do I change the code so only one marker is placed and when the map is clicked again it changes its location?
Here is my开发者_高级运维 code so far:
function clicked(overlay, latlng) {
var icon3 = new GIcon();
icon3.image = "marker.png";
icon3.iconAnchor = new GPoint(15, 40);
var marker2 = new GMarker(latlng, { icon: icon3, draggable: true, title: 'Drag me' });
map.addOverlay(marker2);
}
I would recommend keeping an instance of marker2
outside of the clicked
function, then if marker2 is null, make and add a new one like you are now, otherwise call marker2.setLatLong(latlng);
to update it's location.
Untested example code:
var marker2;
function clicked(overlay, latlng) {
if (marker2 == null) {
var icon3 = new GIcon();
icon3.image = "marker.png";
icon3.iconAnchor = new GPoint(15, 40);
marker2 = new GMarker(latlng, { icon: icon3, draggable: true, title: 'Drag me' });
map.addOverlay(marker2);
}
else {
marker2.setLatLong(latlng);
}
}
You will need to implement some sort of check to see if the marker has already been placed. One option would be to keep a list of markers already added and check that list for a marker at a specific point before calling the functions to add the marker to the map. If you need a code sample, let me know.
Well, dont bother, I figured it out myself. I just used map.clearOverlays(); before the marker is pplaced and that solved the problem.
精彩评论