I currently add markers to the map using the code below. I'd like to be able to remove any one at any time by pushing a javascript command. Is this possible?
ex. place 5 markers.. removed the 3rd one while keeping the other 4.
$('#map').show();
var geocoder = new google.maps.Geocoder();
var address = document.getElementById("address").value +", " + document.getElementById("city").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat = results[0].geometry.location.lat();
var lng = results[0].geometry.location.lng();
locationsall[counter] = new Array();
locationsall[counter][0] = address;
locationsall[counter][1] = lat;
locationsall[counter][2] = lng;
var mapOptions = {
zoom: 13,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker, i;
for (i = 0; i < locationsall.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locationsall[i][1], locationsall[i][2]),
map: map,
title: 'You are here!'
});
}
counter++;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
}); }
Edit 1:
}).text("Remove").click(function() {
var index2 = $tr2.index();
$("#locationDeals input[type='hidden']").each(function() {
this.name = this.name.replace(/\[(\d+)\]/, function(str2, number2) {
return "[" + (+number2 > index2 - 1 ? number2 - 1 : number2) + "]";
});
});
//locationsall[locations.indexOf(location)].setMap(null);
$tr2.remove();
locations.splice(locations.indexOf(location), 1);
return false;
}).appendTo($tdRemoveRow2);
Outside of your
for loop
define anArray
that will hold all added markers. E.g.allMarkers = []
Inside of your
for loop
after creating the marker, push it in said Array. E.g.allMarkers.push(marker)
When you want to remove the first marker:
allMarkers[0].setMap(null)
, or the third marker:allMarkers[2].setMap(null)
Yes, this is possible. The Google Maps documentation covers this fully, including code examples, etc. Essentially markers are overlays rather than the map itself. You can put these overlays into an array and then use
setMap()
to null to hide.Fully documentation here.