Marker Management in Google Maps

March 12, 2011

Changing the icon when building a google map is easy -simply specify an icon in the marker.

This code populates the marker with a dynamic path - the JavaScript is in a Django template.

var lBand{{band.id}} = {
  section: '{{band.map_icon_name}}',
  region: '{{band.region.name|lower}}',
  marker: new google.maps.Marker({
    position: new google.maps.LatLng({{band.latitude}}, {{band.longitude}}),
    title: '{{band.name}}', 
    map : lMap,
  {% ifequal band.map_icon_name "extinct" %}
    visible: false,
  {% endifequal %}
    icon: '/site_media/map/{{band.map_icon_name}}.png'
  }),
};

If the icon is extinct.png, then the map marker is hidden by default. We can enable it later using JavaScript to call setVisible() on the marker:

function toggle_section_markers(pChecked, pSectionName) {
    for (var i=0; i<lBandDetails.length; i++){
        if (lBandDetails[i] && lBandDetails[i].section === pSectionName){
            var lMarker = lBandDetails[i].marker 
            lMarker.setVisible(pChecked);
        }
    }
}

References