在Google地图API v2中,我们国家的地图可以通过以下方式完美适配到700x400像素的地图中:
map.getBoundsZoomLevel(<bounds of our country>)
但在API v3中,map.fitBounds()
方法不会将其适合于700x400的缩放级别 - 它会缩小一个级别。
这意味着map.fitBounds()
考虑到一些“优雅边距”或其他因素。
我该如何影响此边距的大小?
在Google地图API v2中,我们国家的地图可以通过以下方式完美适配到700x400像素的地图中:
map.getBoundsZoomLevel(<bounds of our country>)
但在API v3中,map.fitBounds()
方法不会将其适合于700x400的缩放级别 - 它会缩小一个级别。
这意味着map.fitBounds()
考虑到一些“优雅边距”或其他因素。
我该如何影响此边距的大小?
helper.getProjection()
的调用总是返回未定义,因此我稍微改编了上面的答案,并得出了这个可行的代码。map.fitBounds(bounds)
的调用替换为myFitBounds(map, bounds)
:function myFitBounds(myMap, bounds) {
myMap.fitBounds(bounds);
var overlayHelper = new google.maps.OverlayView();
overlayHelper.draw = function () {
if (!this.ready) {
var projection = this.getProjection(),
zoom = getExtraZoom(projection, bounds, myMap.getBounds());
if (zoom > 0) {
myMap.setZoom(myMap.getZoom() + zoom);
}
this.ready = true;
google.maps.event.trigger(this, 'ready');
}
};
overlayHelper.setMap(myMap);
}
// LatLngBounds b1, b2 -> zoom increment
function getExtraZoom(projection, expectedBounds, actualBounds) {
var expectedSize = getSizeInPixels(projection, expectedBounds),
actualSize = getSizeInPixels(projection, actualBounds);
if (Math.floor(expectedSize.x) == 0 || Math.floor(expectedSize.y) == 0) {
return 0;
}
var qx = actualSize.x / expectedSize.x;
var qy = actualSize.y / expectedSize.y;
var min = Math.min(qx, qy);
if (min < 1) {
return 0;
}
return Math.floor(Math.log(min) / Math.log(2) /* = log2(min) */);
}
// LatLngBounds bnds -> height and width as a Point
function getSizeInPixels(projection, bounds) {
var sw = projection.fromLatLngToContainerPixel(bounds.getSouthWest());
var ne = projection.fromLatLngToContainerPixel(bounds.getNorthEast());
return new google.maps.Point(Math.abs(sw.y - ne.y), Math.abs(sw.x - ne.x));
}
expectedSize
恰好是actualSize
的两倍时,我必须修改一行以处理浮点舍入误差。将getSizeInPixels
的返回语句更改为: `return new google.maps.Point(
Math.round(10000 * Math.abs(sw.y - ne.y)) / 10000,
Math.round(10000 * Math.abs(sw.x - ne.x)) / 10000
);`
- Eric Freese现在,fitBounds方法有第二个参数,表示填充大小。对于那些想要删除它的人,只需要传递0即可。
Map.map.fitBounds(bounds, 0);
New method signature: fitBounds(bounds:LatLngBounds|LatLngBoundsLiteral, padding?:number)