8hvfvg
Last Updated: February 25, 2016
·
2.245K
· tilsammans
Avatar joost

Auto-zooming Google map based on its markers

Show a Google map, zoomed exactly so that all its markers are visible. This example uses jQuery, but it's not required.

HTML

<script src='//maps.googleapis.com/maps/api/js?sensor=false'></script>
<div id="map-canvas" data-lat-lng="40.689060,-74.044636"></div>
<span class="marker" data-lat-lng="41.689060,-73.044636">Marker 1</span>
<span class="marker" data-lat-lng="42.689060,-72.044636">Marker 2</span>

Coffeescript

$ ->

 # Convert the #map-canvas div into a map.
 # By Joost Baaij www.spacebabies.nl
 $('#map-canvas').each (index, element) ->
  # split the data-lat-lng attribute into lat and lng variables
   [lat, lng]    = $(element).data('lat-lng').split(",")
  # initial zoom and center
   options =
     center:     new google.maps.LatLng(lat, lng)
     mapTypeId:  google.maps.MapTypeId.ROADMAP
     zoom:       $(element).data('zoom') || 16

   map = new google.maps.Map(element, options)
   bounds = new google.maps.LatLngBounds()

   # Go through all markers, if any, and place those on the map.
   $('.marker').each (index, element) ->
     [lat, lng]    = $(element).data('lat-lng').split(",")
     return unless lat && lng

     marker        = new google.maps.Marker
       position:   new google.maps.LatLng(lat, lng)
       title:      $(element).text()
       map:        map

     bounds.extend(marker.position)

   # resize the map to show all markers, if there are more than one.
   map.fitBounds(bounds) if $('.marker').length > 1

generated javascript

(function() {
  $(function() {
    return $('#map-canvas').each(function(index, element) {
      var bounds, lat, lng, map, options, _ref;

      _ref = $(element).data('lat-lng').split(","), lat = _ref[0], lng = _ref[1];
      options = {
        center: new google.maps.LatLng(lat, lng),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: $(element).data('zoom') || 16
      };
      map = new google.maps.Map(element, options);
      bounds = new google.maps.LatLngBounds();
      $('.marker').each(function(index, element) {
        var marker, _ref1;

        _ref1 = $(element).data('lat-lng').split(","), lat = _ref1[0], lng = _ref1[1];
        if (!(lat && lng)) {
          return;
        }
        marker = new google.maps.Marker({
          position: new google.maps.LatLng(lat, lng),
          title: $(element).text(),
          map: map
        });
        bounds.extend(marker.position);
      });
      if ($('.marker').length > 1) {
        return map.fitBounds(bounds);
      }
    });
  });

}).call(this);
Say Thanks
Respond