Reputation: 43
I want to remove all old marker from google map and add new one but setMap(null) does not work and it add new marker without remove old one . Please look into my code
var markers = data['map'];
if (marker != null) {
marker.setMap(null);
}
marker.setMap(null);
for (var i = 0; i < markers.length; i++) {
alert(1);
var data = markers[i];
var infoWindow = new google.maps.InfoWindow();
var img1 = data.imageUrl != '' ? '<img src= <?php echo $baseUrl; ?>/uploads/property/thumb/' + data.imageUrl + '>' : "";
var bed1 = data.beds != '' ? data.beds + ' beds' : "";
var bath1 = data.bath != '' ? data.bath + ' bath' : "";
var squarefeet1 = data.areaSqaureFeet != '' ? data.areaSqaureFeet + ' squarefeet' : "";
var contentString = '<div id="content">';
contentString += img1+ '<p>' + data.propertyAddress + ' </p><p> ' + bed1 + ' </p><p>' + bath1 + ' </p><p>' + squarefeet1 + ' </p>';
contentString += '</div>';
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.title);
infowindow.open(map, this);
});
}
}
Upvotes: 1
Views: 4976
Reputation: 993
I don´t see where you defined you "marker" variable. However, in general you should create a Marker -> push it into a global defined array (or just an array that you can access) so you have a reference to it. You can then just run over the marker array and set it null. So you could do it this way:
var markers = []; //Global Marker array to keep references
var marker = new google.maps.Marker({
position: {lat: lat, lng: lng},
icon: icon,
map: map
});
markers.push(marker);
This will keep your markers accessible. If you want to set them null you could write a function like this one:
removeMarker: function () {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
},
Hope that helped.
Upvotes: 1