Fixed Legend in Google Maps Mashup
Asked Answered
D

2

9

I have a page with a Google Maps mashup that has pushpins that are color-coded by day (Monday, Tuesday, etc.) The IFrame containing the map is dynamically sized, so it gets resized when the browser window is resized.

I'd like to put a legend in the corner of the map window that tells the user what each color means. The Google Maps API includes a GScreenOverlay class that has the behavior that I want, but it only lets you specify an image to use as an overlay, and I'd prefer to use a DIV with text in it. What's the easiest way to position a DIV over the map window in (for example) the lower left corner that'll automatically stay in the same place relative to the corner when the browser window is resized?

Devise answered 31/8, 2008 at 0:41 Comment(0)
M
10

You can add your own Custom Control and use it as a legend.

This code will add a box 150w x 100h (Gray Border/ with White Background) and the words "Hello World" inside of it. You swap out the text for any HTML you would like in the legend. This will stay Anchored to the Top Right (G_ANCHOR_TOP_RIGHT) 10px down and 50px over of the map.

function MyPane() {}
MyPane.prototype = new GControl;
MyPane.prototype.initialize = function(map) {
  var me = this;
  me.panel = document.createElement("div");
  me.panel.style.width = "150px";
  me.panel.style.height = "100px";
  me.panel.style.border = "1px solid gray";
  me.panel.style.background = "white";
  me.panel.innerHTML = "Hello World!";
  map.getContainer().appendChild(me.panel);
  return me.panel;
};

MyPane.prototype.getDefaultPosition = function() {
  return new GControlPosition(
      G_ANCHOR_TOP_RIGHT, new GSize(10, 50));
      //Should be _ and not _
};

MyPane.prototype.getPanel = function() {
  return me.panel;
}
map.addControl(new MyPane());
Milt answered 3/9, 2008 at 23:6 Comment(0)
L
3

I would use HTML like the following:

<div id="wrapper">
   <div id="map" style="width:400px;height:400px;"></div>
   <div id="legend"> ... marker descriptions in here ... </div>
</div>

You can then style this to keep the legend in the bottom right:

div#wrapper { position: relative; }
div#legend { position: absolute; bottom: 0px; right: 0px; }

position: relative will cause any contained elements to be positioned relative to the #wrapper container, and position: absolute will cause the #legend div to be "pulled" out of the flow and sit above the map, keeping it's bottom right edge at the bottom of the #wrapper and stretching as required to contain the marker descriptions.

Leifleifer answered 31/8, 2008 at 12:25 Comment(2)
This solution has been made obsolete with newer versions of the Google Maps API. As of version 3.8, this tutorial shows how to create a custom control and can be easily adapted to show a legend: developers.google.com/maps/documentation/javascript/…Schuss
Probably will need a z-index for the div legendCrellen

© 2022 - 2024 — McMap. All rights reserved.