Reputation: 345
I add the markers on the google map by clicking on the map. Now I wish to remove a marker on the google map by clicking on the marker but have no luck trying it.
var myMean = new google.maps.LatLng(22.321074,87.307710);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: myMean,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var icon = new google.maps.MarkerImage("http://maps.google.com/mapfiles/ms/micons/blue.png", new google.maps.Size(32, 32), new google.maps.Point(0, 0), new google.maps.Point(16, 32));
var points=[];
var markers=[];
function setAllMap(map)
{
for (var i = 0; i < markers.length; i++)
{
markers[i].setMap(map);
}
}
function addMarker(point)
{
var marker=new google.maps.Marker(
{
position: point,
icon: icon,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function()
{
var i;
for(i=0;i<points.length;i++)
{
if(points[i].equals(point))
{
points.splice(i,1);
markers.splice(i,1);
}
}
setAllMap(null);
setAllMap(map);
alert(points);
});
}
google.maps.event.addListener(map, 'click', function(event) {
points.push(event.latLng);
alert(points[points.length-1]);
addMarker(points[points.length-1]);
});
I am trying to maintain the list of markers and am removing the current marker from the list and setting other markers on the map but it is not working. Please tell what needs be modified in listener of marker in order to remove the marker by clicking on it.
Upvotes: 2
Views: 212
Reputation: 5795
You are setting all marker's map to null
in the wrong place. You should set all markers in the map before you remove the current clicked one.
So if you change your addMarker
logic like this, it should work:
function setAllMap(map) { for (var i = 0; i < markers.length; i++) { markers[i].setMap(map); } }
function addMarker(point) {
var marker = new google.maps.Marker({
position: point,
map: map
});
markers.push(marker);
google.maps.event.addListener(marker, "click", function () {
setAllMap(null);
var i;
for (i = 0; i < points.length; i++) {
if (points[i].equals(marker.getPosition())) {
points.splice(i, 1);
markers.splice(i, 1);
}
}
setAllMap(map);
//alert(points);
});
}
Working example here
Upvotes: 1