Removing google map markers using JQuery
I've searched hi and low for info regarding this but to no avail.
Basically I have a page that is loading a bunch of cateories as checkboxes, for example checkbox 1 is called 'Exhibitions' and when clicked on displays all the exhibitions on the map (I am passing the value of the checkbox to the JQuery function which then filters the XML). I have 6 checkboxes all relating to different categories. I have this part all working well but I now need to remove these markers when the checkbox is unticked. I also need it to only remove the markers associated with that category.
Code is below:
MYMAP.placeMarkersTest = function(filename, CatValue) {
$.get(filename, function(xml) {
$(xml).find("marker").each(function() {
var eventCat = $(this).find('Category').text();
if (eventCat == CatValue) {
var name = $(this).find('name').text();
var address = $(this).find('name').text();
var lat = $(this).find('lat').text();
var lng = $(this).find('lng').text();
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
MYMA开发者_开发知识库P.bounds.extend(point);
var icon = "/images/mapping/EventsIcon.png";
var marker = new google.maps.Marker({
position: point,
icon: icon,
map: MYMAP.map
});
var infoWindow = new google.maps.InfoWindow();
var html = '<strong>' + name + '</strong><br />';
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(MYMAP.map, marker);
});
MYMAP.map.fitBounds(MYMAP.bounds);
} else {
//alert("There are no matches");
}
});
});
}
Any ideas on how to remove the specific markers would be great, thanks.
When creating your markers you can add the category it belongs to as a property using marker.Set('MyProperty', 'MyCategory') then add the markers to a global array. When you are ready to remove the markers you can loop through the marker array and call marker.setMap(null) to remove it from the map.
var markers = new Array();
function setMarkers(map, locations, category) {
for(var i = 0; i < locations.length; i++) {
var area = locations[i];
var latlng = new google.maps.LatLng(area.Location[0], area.Location[1]);
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: markerShadow,
icon: markerImage,
shape: markerShape,
title: area.Name
});
marker.set('category', category);
markers.push(marker);
}
}
function clearMarkers(category) {
for(var i = 0; i < markers.length; i++) {
if (markers[i].get('category') == category) {
markers[i].setMap(null);
}
}
}
Have you tried adding each marker to a global array so its stored in context and using Map.removeOverlay(markerArray[indexvalue]) to remove it?
精彩评论