我有一组点,我想在嵌入式谷歌地图(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之后直接调用,则不会改变地图的缩放级别。
有没有一种方法来获得缩放级别的边界而不应用到地图?还有其他解决方法吗?
我看到许多不正确或太复杂的解决方案,所以决定张贴一个工作,优雅的解决方案。
setZoom()没有像你期望的那样工作的原因是fitBounds()是异步的,所以它不能保证它会立即更新缩放,但是你对setZoom()的调用依赖于这一点。
你可能会考虑在调用fitBounds()之前设置minZoom map选项,然后在调用完成后清除它(这样用户仍然可以手动缩小):
var bounds = new google.maps.LatLngBounds();
// ... (extend bounds with all points you want to fit)
// Ensure the map does not get too zoomed out when fitting the bounds.
gmap.setOptions({minZoom: 6});
// Clear the minZoom only after the map fits the bounds (note that
// fitBounds() is asynchronous). The 'idle' event fires when the map
// becomes idle after panning or zooming.
google.maps.event.addListenerOnce(gmap, 'idle', function() {
gmap.setOptions({minZoom: null});
});
gmap.fitBounds(bounds);
此外,如果你也想限制最大缩放,你可以对maxZoom属性应用同样的技巧。
请参阅MapOptions文档。
如果我没记错的话,我假设你想让你的所有点在地图上以最高的缩放级别可见。我通过将地图的缩放级别初始化为16来实现这一点(不确定它是否是V3上可能的最高缩放级别)。
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 16,
center: marker_point,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
然后我做了边界的事情:
var bounds = new google.maps.LatLngBounds();
// You can have a loop here of all you marker points
// Begin loop
bounds.extend(marker_point);
// End loop
map.fitBounds(bounds);
结果:
成功!