July 11, 2012

Bring Google Map v3 Markers to Front by Changing Z-Index

As mentioned in my earlier article on the same subject, the Google Maps API stacks the markers on a map based on their latitude — the markers appear in front of those that are vertically above them. This means that a marker that needs to be prominent might be buried below nearby markers, especially at lower zoom levels.

Google Maps API v3 allows you to change the stacking order of a marker using the zIndex property. The API automatically assigns z-index to markers; manually assigning a value higher than google.maps.Marker.MAX_ZINDEX will ensure that the marker stays in front of all markers with auto-assigned z-index.

Partial Example

You can specify zIndex while creating the marker:

var marker = new google.maps.Marker({
  position: position,
  map: map,
  zIndex: google.maps.Marker.MAX_ZINDEX + 1

Or you can change it using setZIndex() method:

marker.setZIndex(google.maps.Marker.MAX_ZINDEX + 1);

Example 1: One Special Marker

The following example shows how to create a marker that displays in front of other markers regardless of its position or the order in which it was added to the map. The green marker should appear on top of red markers. View page source to inspect the code.

Example 2: Bring Markers to Front by Clicking

The following example shows how to change the z-index of an existing marker on-demand. The example demonstrates the click event, however you are free to improvise. View page source to inspect the code.

Google Maps API documentation can be viewed here.