Automatically center Google Map between two markers

Asked

Viewed 1,170 times

0

I’m having trouble 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 point of the beginning and the point of the end of the route.

1 answer

4

There’s an easy way to do it, 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);
});

This way, you can add several points.

Demodisplaying jsFiddle here: http://jsfiddle.net/x5R63/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.