Javascript – google map map.fitBounds() and bounds.extend() are not working as expected.

boundsfitboundsgoogle-mapsgoogle-maps-api-3javascript

I have a piece of code below which is using bounds.extend() and map.fitBounds() to resize the map to accommodate all markers. I would expect the map could focus to start_point as a center and zoom out to a appropriate level so every markers would be seen.

However, it ends up a maximum zoom in to start_point. And I tried to (commen)not call bounds.extend() every time in geocoder.geocode callback function but add the marker into an array and call bounds.extend() in a separate loop which is not working either.

I double checked the markers are created successfully and I can see them if I zoom out manually.

mark_pins() is invoked as a ajax success callback function which I didn't include here.

Do I miss anything?

   var map;
   var start_point = new google.maps.LatLng(37.519002, -122.131);
   var bounds = new google.maps.LatLngBounds();


   function initialize() {
    var map_canvas = document.getElementById('map_canvas');

    var map_options = {
      center: start_point,
      zoom: 10,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(map_canvas, map_options);

  }

  google.maps.event.addDomListener(window, 'load', initialize);


  function mark_pins(trucks){
    var geocoder = new google.maps.Geocoder();
    var markersArray = [];


    for (i = 0; i < trucks.length; i++) {
      // iterate each truck address
      geocoder.geocode( { 'address' : trucks[i]['address']}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var marker = new google.maps.Marker({
                  map: map,
                  position: results[0].geometry.location
              });
              marker.setMap(map);
              bounds.extend(results[0].geometry.location);
              //markersArray.push(marker);

          } else {
              alert('Internal error: ' + status + address);
          }
      });
    }
    var bounds = new google.maps.LatLngBounds();


    for (i = 0; i< markersArray.length; i++) {
      //code
      //bounds.extend(new google.maps.LatLng(markersArray[i][1], markersArray[i][2]));
    }
    bounds.extend(start_point);
    map.setCenter(start_point);

    map.fitBounds(bounds);


  }

Best Solution

The geocoder is asynchronous. Your code calls map.fitBounds(bounds) before the results have come back. The posted code also never calls the mark_pins function.

function mark_pins(trucks) {
    var geocoder = new google.maps.Geocoder();
    var markersArray = [];


    for (i = 0; i < trucks.length; i++) {
        // iterate each truck address
        geocoder.geocode({
            'address': trucks[i]['address']
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                marker.setMap(map);
                bounds.extend(results[0].geometry.location);
                map.fitBounds(bounds);
            } else {
                alert('Internal error: ' + status + address);
            }
        });
    }
}

working fiddle

screenshot of resulting map

code snippet:

var map;
var start_point = new google.maps.LatLng(37.519002, -122.131);
var bounds = new google.maps.LatLngBounds();
var trucks = [{
    address: "Sunnyvale, CA"
}, {
    address: "Palo Alto, CA"
}, {
    address: "Reno, NV"
}, {
    address: "Portland, OR"
}];

function initialize() {
    var map_canvas = document.getElementById('map_canvas');

    var map_options = {
        center: start_point,
        zoom: 10,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(map_canvas, map_options);
    mark_pins(trucks);
}

google.maps.event.addDomListener(window, 'load', initialize);


function mark_pins(trucks) {
    var geocoder = new google.maps.Geocoder();
    var markersArray = [];


    for (i = 0; i < trucks.length; i++) {
        // iterate each truck address
        geocoder.geocode({
            'address': trucks[i]['address']
        }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location
                });
                marker.setMap(map);
                bounds.extend(results[0].geometry.location);
                //markersArray.push(marker);
                map.fitBounds(bounds);
            } else {
                alert('Internal error: ' + status + address);
            }
        });
    }
}
html, body, #map_canvas {
    height: 100%;
    width: 100%;
    padding: 0px;
    margin: 0px;
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

Related Question