Automatically center Google Map between two bookmarks

0

I'm having difficulty trying to center the map between two markers. I need to do this when I change the DirectionsRenderer from one map to another. If the route has no changes that can be dragged then the map will automatically center. But if changes occur, the map will keep the same center and zoom.

  

In short: What I want is to center the map between the start point and the end point of the route.

    
asked by anonymous 22.06.2016 / 17:37

1 answer

3

It has an easy way to do this, using LatLngBounds

Add to your code

//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();    

for (i = 0; i < locations.length; i++) {  
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
  });

  //extend the bounds to include each marker's position
  bounds.extend(marker.position);

  google.maps.event.addListener(marker, 'click', (function(marker, i) {
    return function() {
      infowindow.setContent(locations[i][0]);
      infowindow.open(map, marker);
    }
  })(marker, i));
}

//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);

//(optional) restore the zoom level after the map is done scaling
var listener = google.maps.event.addListener(map, "idle", function () {
    map.setZoom(3);
    google.maps.event.removeListener(listener);
});

In this way, you can add several points.

Demonstration jsFiddle here: link

    
22.06.2016 / 23:11