问题描述
我正在地图上绘制一系列标记(使用地图 API 的 v3).
I'm drawing a series of markers on a map (using v3 of the maps api).
在 v2 中,我有以下代码:
In v2, I had the following code:
bounds = new GLatLngBounds();
... loop thru and put markers on map ...
bounds.extend(point);
... end looping
map.setCenter(bounds.getCenter());
var level = map.getBoundsZoomLevel(bounds);
if ( level == 1 )
level = 5;
map.setZoom(level > 6 ? 6 : level);
这可以很好地确保地图上始终显示适当的细节级别.
And that work fine to ensure that there was always an appropriate level of detail displayed on the map.
我正在尝试在 v3 中复制此功能,但 setZoom 和 fitBounds 似乎没有合作:
I'm trying to duplicate this functionality in v3, but the setZoom and fitBounds don't seem to be cooperating:
... loop thru and put markers on the map
var ll = new google.maps.LatLng(p.lat,p.lng);
bounds.extend(ll);
... end loop
var zoom = map.getZoom();
map.setZoom(zoom > 6 ? 6 : zoom);
map.fitBounds(bounds);
我尝试了不同的排列(例如,在 setZoom 之前移动 fitBounds)但我对 setZoom 所做的一切似乎都不会影响地图.我错过了什么吗?有没有办法做到这一点?
I've tried different permutation (moving the fitBounds before the setZoom, for example) but nothing I do with setZoom seems to affect the map. Am I missing something? Is there a way to do this?
推荐答案
在 关于 Google Groups 的讨论 我发现基本上当您执行 fitBounds 时,缩放是异步发生的,因此您需要捕获缩放和边界更改事件.最后一篇文章中的代码对我做了一个小的修改......就目前而言,它完全阻止了你放大超过 15 倍,所以使用了第四篇文章中的想法来设置一个标志,只在第一次这样做.
At this discussion on Google Groups I discovered that basically when you do a fitBounds, the zoom happens asynchronously so you need to capture the zoom and bounds change event. The code in the final post worked for me with a small modification... as it stands it stops you zooming greater than 15 completely, so used the idea from the fourth post to have a flag set to only do it the first time.
// Do other stuff to set up map
var map = new google.maps.Map(mapElement, myOptions);
// This is needed to set the zoom after fitbounds,
google.maps.event.addListener(map, 'zoom_changed', function() {
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom() > 15 && this.initialZoom == true) {
// Change max/min zoom here
this.setZoom(15);
this.initialZoom = false;
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
});
map.initialZoom = true;
map.fitBounds(bounds);
希望有所帮助,
安东尼.
这篇关于谷歌地图 v3:强制执行分钟.使用 fitBounds 时的缩放级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!