UPDATE: Version 2 of the Google Maps API removed the overlays array. I have added a version 2 method that creates an array to track the markers. The basic idea for this came from a post to the Google Maps Group.
I recently needed a way to have a checkbox add and remove a GMarker from a Google Map. This JavaScript will create a GMarker when the checkbox is true and remove the Marker when it is false.
This example also:
For Version 1 of the Google Maps API
I recently needed a way to have a checkbox add and remove a GMarker from a Google Map. This JavaScript will create a GMarker when the checkbox is true and remove the Marker when it is false.
This example also:
- Adds an Info Window to the Marker
- Centers the map on the Marker at a Specified Zoom Level
var gmarkers=[];
function toggle_marker(lat, lon, infoWindowContent, theCheckBox){
if (theCheckBox.checked == true) {
var point = new GPoint(parseFloat(lon), parseFloat(lat));
var marker= new GMarker(point);
var html = infoWindowContent;
marker.id = theCheckBox.value;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
mymap.addOverlay(marker);
mymap.centerAndZoom(point, 8);
}
else {
for (i = 0; i < gmarkers.length; i++) {
if (gmarkers[i].id == theCheck.value) {
mymap.removeOverlay(gmarkers[i]);
}
}
}
}
For Version 1 of the Google Maps API
function toggle_marker(lat, lon, infoWindowContent, theCheckBox){
if (theCheckBox.checked == true) {
var point = new GPoint(parseFloat(lon), parseFloat(lat));
var marker= new GMarker(point);
var html = infoWindowContent;
marker.id = theCheckBox.value;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
mymap.addOverlay(marker);
mymap.centerAndZoom(point, 8);
}
else {
for (i = 0; i < mymap.overlays.length; i++) {
if (mymap.overlays[i].id) {
if (mymap.overlays[i].id == theCheckBox.value) {
mymap.removeOverlay(mymap.overlays[i]);
}
}
}
}
}