在 2017 年解决这个问题
在发送到map.fitBounds()之前稍微缩小边界框。
这是一个缩小边界框的函数:
// Values between 0.08 and 0.28 seem to work
// Any lower and the map will zoom out too much
// Any higher and it will zoom in too much
var BOUNDS_SHRINK_PERCENTAGE = 0.08; // 8%
/**
* @param {google.maps.LatLngLiteral} southwest
* @param {google.maps.LatLngLiteral} northeast
* @return {Array[google.maps.LatLngLiteral]}
*/
function slightlySmallerBounds(southwest, northeast) {
function adjustmentAmount(value1, value2) {
return Math.abs(value1 - value2) * BOUNDS_SHRINK_PERCENTAGE;
}
var latAdjustment = adjustmentAmount(northeast.lat, southwest.lat);
var lngAdjustment = adjustmentAmount(northeast.lng, southwest.lng);
return [
{lat: southwest.lat + latAdjustment, lng: southwest.lng + lngAdjustment},
{lat: northeast.lat - latAdjustment, lng: northeast.lng - lngAdjustment}
]
}
像这样使用它:
// Ensure `southwest` and `northwest` are objects in google.maps.LatLngLiteral form:
// southwest == {lat: 32.79712, lng: -117.13931}
// northwest == {lat: 32.85020, lng: -117.09356}
var shrunkBounds = slightlySmallerBounds(southwest, northeast);
var newSouthwest = shrunkBounds[0];
var newNortheast = shrunkBounds[1];
// `map` is a `google.maps.Map`
map.fitBounds(
new google.maps.LatLngBounds(newSouthwest, newNortheast)
);
我有一个应用程序与codr 做同样的事情:将当前地图边界保存在 URL 中,并在刷新时从 URL 边界初始化地图。这个解决方案非常适合。
为什么会这样?
当调用fitBounds() 时,Google 地图基本上会执行此操作:
- 以给定边界框的中心点居中地图。
- 放大到视口将包含给定边界inside视口框的最高缩放级别。
如果给定的边界完全与视口匹配,Google 地图不会将其视为“包含”边界,因此会再缩小一层。