v2.77: GMarker show, hide, and isHidden = Quick & Easy Marker Toggling!

Wednesday, April 04, 2007 at 7:31:00 AM



The day has come - the API now has officially documented methods for showing and hiding markers, and querying their ("hidden-ness") state. Using a combination of GMarker.show(), GMarker.hide(), and GMarker.isHidden(), you can painlessly toggle the visibility of markers. Here's what the code looks like to toggle one marker:

if (marker.isHidden()) {
  marker.show();
 } else {
  marker.hide();
}

It's pretty easy to extend that code to create a map that has groups of markers that are toggled by checking boxes in a sidebar. Shown below is a map that loads in an XML file of my favorite restaurants and bars in Seattle, and creates 2 different "toggle-able" marker groups:

How's it done? There are a couple ways you could keep track of marker groups, but I chose to use an associative array that keys each marker type with an array of markers. The array declaration looks like:

var markerGroups = { "restaurant": [], "bar": []};

Then when parsing the XML, I use an attribute value of each marker node that's either "restaurant" or "bar" to push the marker into the appropriate array, like so:

var type = markers[i].getAttribute("type");
//...
markerGroups[type].push(marker);

The onclick event for the checkboxes trigger either toggleGroup('restaurant') or toggleGroup('bar'). In toggleGroup, I just iterate through the markers in that group's array, using the same code shown at the beginning of the post, like so:

    function toggleGroup(type) {
      for (var i = 0; i < markerGroups[type].length; i++) {
        var marker = markerGroups[type][i];
        if (marker.isHidden()) {
          marker.show();
        } else {
          marker.hide();
        }
      } 
    }

Now go forth and toggle! Remember that you'll need to specify v=2.x in your script tag to use the new functions for the next few weeks, since they're new features.

API v2 Latest (v=2.x): 2.77
API v2 Default (v=2): 2.76