我需要在地图上使用几个标记,并且还需要在其中一个上显示infowindow。所有这些东西应该在地图视口内。我正在尝试使用此代码来获取InfoWindow左上角,右上角和2个标记的边界:
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;
}
但看起来我的想法是错的。我怎么能这样做infoWindow和我的2个标记总是在地图视口内。
答案 0 :(得分:2)
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].getPosition());
}
维护数组中所有标记的列表(上面是:: markers)。继续扩展循环中所有标记的边界,然后使用以下代码将其应用于地图对象:
mapObject.fitBounds(bounds);
这会自动缩小地图以适合所有标记及其infoWindows。希望这可以帮助你......