0

i'm need to fitBounds few markers on my map and also need show infowindow on one of them. And all this stuff should be inside map viewport. I'm trying to use this code to get bounds of InfoWindow top left, top right corners and 2 markers:

function calculateWaypointsBounds(attraction, destination, client, infoBox, map){

  const bounds = new google.maps.LatLngBounds();
  bounds.extend(new google.maps.LatLng(attraction.lat, attraction.lon));
  bounds.extend(new google.maps.LatLng(client.lat, client.lon));
  bounds.extend(new google.maps.LatLng(destination.lat, destination.lon));

  const div = infoBox.content_;

  const projectionCoords = infoBox.getProjection().fromLatLngToContainerPixel(new google.maps.LatLng(attraction.lat, attraction.lon));
  const leftTop = new google.maps.Point(projectionCoords.x - div.offsetWidth / 2, projectionCoords.y - 400);
  const rightTop = new google.maps.Point(projectionCoords.x + div.offsetWidth / 2, projectionCoords.y - 400);
  const ltCoords = infoBox.getProjection().fromContainerPixelToLatLng(leftTop);
  const rtCoords = infoBox.getProjection().fromContainerPixelToLatLng(rightTop);

  bounds.extend(ltCoords);
  bounds.extend(rtCoords); //InfoWindow always shows above marker, so i'm need only top left and top right corners.



  return bounds;
}

But looks like my idea wrong. How can i do thats infoWindow and 2 of my markers are allways inside map viewport.

duncan
  • 31,401
  • 13
  • 78
  • 99

1 Answers1

2
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
    bounds.extend(markers[i].getPosition());
}

maintain a list of all your markers in a array(above :: markers). keep extending your bounds for all the markers in a loop and then apply it to the map object using the below code:

mapObject.fitBounds(bounds);

This will automatically make the map zoom out to fit all your markers and their infoWindows. Hope this helps you....

Abhishek
  • 2,485
  • 2
  • 18
  • 25
  • Thanks for the answer! Info window (i'm use google-maps-utility-v3 InfoBox) are drop out of screen, even when i take marker.getPosition() and put it to bounds. http://imgur.com/yFboXIA – Anton Konyushevskiy Jun 09 '16 at 09:48