Javascript - Can't Remove Google Map Markers
I'm having some trouble with google map markers. I have an array that contains 7 locations. When the page loads, a 'for' loop runs through the array and places the first four locat
Solution 1:
In case anyone else is having the same problem and finds this question, as ray stated, I needed to create an array to push the markers into and then apply the setMap(null) to the markers array, as opposed to applying it to the original array (pins[]) that contained my location info.
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(40, -95),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// create the mapvar map = new google.maps.Map(mapCanvas, mapOptions);
// array of locationsvar pins = [
['Cleveland',41.499321,-81.694359],
['Florence',34.195435,-79.762566],
['Knoxville',35.960638,-83.920739],
['Memphis',35.149532,-90.048981],
['Nashville',36.162664,-86.781602],
['Phoenix',33.448376,-112.074036],
['Toronto',43.653225,-79.383186]
];
// this array will hold the markersvar markers = [];
// Loop through the array of locations & place each one on the map for( i = 0; i < 4; i++ ) {
var position = new google.maps.LatLng(pins[i][1], pins[i][2]);
var marker = new google.maps.Marker({
position: position,
map: map,
icon: 'http://i.imgur.com/FPiUErC.png',
title: pins[i]['0']
});
//each marker is added to the markers array
markers.push(marker);
} // end of the for loopfunctionaddmarker2() {
// remove the first four markersfor( i = 0; i < 4; i++ ) {
// the loop removes the first four results from the markers array
markers[i].setMap(null);
}
// add the last three markersfor( i = 4; i < 7; i++ ) {
var myPosition = new google.maps.LatLng(pins[i][1], pins[i][2]);
var marker = new google.maps.Marker({
position: myPosition,
map: map,
icon: 'http://i.imgur.com/FPiUErC.png',
title: pins[i][0]
});
} // end of for loop
} // end of addmarker2 function
$("#mysubmit").click(addmarker2);
Solution 2:
I've already live debugging by typing on developer console, and i've found a way to remove all markers. (which saved using array.push()
method)
Here is the code -- just call neutralize()
:
function neutralize() {
for (var i = 0; i < markers.length; i++) {
try{
markers[i].f.setMap(null);
}
catch{
markers[i].setMap(null);
}
}
markers = [];
}
Post a Comment for "Javascript - Can't Remove Google Map Markers"