我有一组点,我想在嵌入式谷歌地图(API v3)上绘制。我希望边界容纳所有的点,除非缩放级别太低(即,缩小太多)。我的方法是这样的:
var bounds = new google.maps.LatLngBounds();
// extend bounds with each point
gmap.fitBounds(bounds);
gmap.setZoom( Math.max(6, gmap.getZoom()) );
这行不通。最后一行“gmap.setZoom()”如果在fitBounds之后直接调用,则不会改变地图的缩放级别。
有没有一种方法来获得缩放级别的边界而不应用到地图?还有其他解决方法吗?
我用这个来确保缩放级别不超过设置的级别,这样我就知道卫星图像是可用的。
向zoom_changed事件添加一个监听器。
这还可以在UI上控制缩放控制。
只在需要时执行setZoom,因此if语句比Math语句更可取。max或Math.min
google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() > 19 ) {
map.setZoom(19);
}
});
bounds = new google.maps.LatLngBounds( ... your bounds ... )
map.fitBounds(bounds);
为了防止缩小得太远:
google.maps.event.addListener(map, 'zoom_changed', function() {
if ( map.getZoom() < 6 ) {
map.setZoom(6);
}
});
bounds = new google.maps.LatLngBounds( ... your bounds ... )
map.fitBounds(bounds);
像我一样,如果你不愿意和听众一起玩,这是我想出的一个简单的解决方案:
在地图上添加一个方法,严格按照你的要求工作,像这样:
map.fitLmtdBounds = function(bounds, min, max){
if(bounds.isEmpty()) return;
if(typeof min == "undefined") min = 5;
if(typeof max == "undefined") max = 15;
var tMin = this.minZoom, tMax = this.maxZoom;
this.setOptions({minZoom:min, maxZoom:max});
this.fitBounds(bounds);
this.setOptions({minZoom:tMin, maxZoom:tMax});
}
那么你可以调用map.fitLmtdBounds(bounds)而不是map.fitBounds(bounds)来设置定义的缩放范围下的边界…或者map.fitLmtdBounds(bounds,3,5)来覆盖缩放范围..