Resize google map to show all points

I needed to get a google map to center and scale based on the added points.

I found a tutorial here: http://econym.googlepages.com/basic14.htm

This gave me exactly what I needed.

In short, given a GMap2 object called map and a map of locations (name -> object with lat and lng properties):


map.setCenter(new GLatLng(0,0),0);

var bounds = new GLatLngBounds();

for (name in locs) {
    var loc = locs[name];
    var latlng = new GLatLng(loc.lat, loc.lng);
    var marker = new GMarker(latlng);

    bounds.extend(latlng);

    map.addOverlay(marker);
}

map.setZoom(map.getBoundsZoomLevel(bounds));

map.setCenter(bounds.getCenter());

Reply

  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <p> <pre> <hr>
  • Lines and paragraphs break automatically.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Insert Flickr images: [flickr-photo:id=230452326,size=s] or [flickr-photoset:id=72157594262419167,size=m].
  • Replace [debbug:xxxxx] with a link to the relevant debian bug.
  • Images can be added to this post.
  • You may link to Gallery2 items on this site using a special syntax.
  • Insert Google Map macro.
  • Textual smileys will be replaced with graphical ones.

More information about formatting options