March 26, 2010

Change Z-Index of Google Map Markers

Google Maps API stacks the markers on the map upon its own discretion. However at times you may want to change the stacking order of specific markers; for example you may want to place a marker on top of all other markers so that it is always fully visible and emphasized.

A marker's stacking level is determined by its z-index which is automatically assigned. Since version 2.98 of the Google Maps API, you can change the z-index of a marker through a function. To do so, assign a function to the zIndexProcess option of the marker in its constructor:

var marker = new GMarker(latlng, { zIndexProcess: getZIndexOfMyChoice });

The following example demonstrates how you can force a marker to display on top of all other markers by assigning a function to the zIndexProcess option of the marker. The function returns a number large enough to ensure that the marker is displayed on top of all other markers (see details below). The green marker should appear on top of all other randomly generated markers. Zoom in and out of the map to verify this. View page source to inspect the code.


What z-index should you use to place the marker on the top of every other marker; and make sure it remains there? 1000? 10,000? 100,000? 1,000,000? I wasn't sure so I investigated a bit.

The following figure shows how Google Maps stacks up randomly generated markers:

Google maps markers stacking

Did you notice that the markers at the bottom of the map (towards the south pole) are stacked up higher than those above it; but the stacking order is not consistent sideways. The marker may appear above or below the markers towards their left or right depending on the order in which they were added.

Based on above observation, it is fairly safe to assume that the highest possible marker on the map will be the one placed at the very bottom of the map, its latitude being -90.00. You can use the Google Maps API function GOverlay.getZIndex(latitude) to determine what should be the z-index of markers placed at -90.00 latitude which, at the time of writing, turns out to be 288,000,000. Add 1 to this number to get an even higher z-index. This should be the z-index you should assign to your topmost marker.