我有一组点,我想在嵌入式谷歌地图(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之后直接调用,则不会改变地图的缩放级别。

有没有一种方法来获得缩放级别的边界而不应用到地图?还有其他解决方法吗?


当前回答

我已经多次访问这个页面来获得答案,虽然所有现有的答案都非常有用,但它们并不能完全解决我的问题。

google.maps.event.addListenerOnce(googleMap, 'zoom_changed', function() {
    var oldZoom = googleMap.getZoom();
    googleMap.setZoom(oldZoom - 1); //Or whatever
});

基本上,我发现“zoom_changed”事件阻止了UI的地图从“跳过”,这发生在我等待“空闲”事件。

希望这能帮助到一些人!

其他回答

我在我的一个应用程序中解决了类似的问题。你对问题的描述让我有点困惑,但我认为你的目标和我一样……

在我的应用程序中,我想绘制一个或多个标记,并确保地图显示它们。问题是,如果我只依赖fitBounds方法,那么缩放级别将在只有一个点时达到最大值——这是不好的。

解决方案是当有很多点时使用fitBounds,当只有一个点时使用setCenter+setZoom。

if (pointCount > 1) {
  map.fitBounds(mapBounds);
}
else if (pointCount == 1) {
  map.setCenter(mapBounds.getCenter());
  map.setZoom(14);
}

我已经找到了一个解决方案,在调用fitBounds之前进行检查,这样你就不会放大,然后突然缩小

var bounds = new google.maps.LatLngBounds();

// extend bounds with each point

var minLatSpan = 0.001;
if (bounds.toSpan().lat() > minLatSpan) {
    gmap.fitBounds(bounds); 
} else {
    gmap.setCenter(bounds.getCenter());
    gmap.setZoom(16);
}

您必须对minLatSpan变量进行一些操作,以使其达到您想要的位置。它将根据缩放级别和地图画布的尺寸而变化。

你也可以用经度来代替纬度

我看到许多不正确或太复杂的解决方案,所以决定张贴一个工作,优雅的解决方案。

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文档。

对我来说,最简单的解决方法是:

map.fitBounds(bounds);

function set_zoom() {
    if(map.getZoom()) {map.setZoom(map.getZoom() - 1);}
    else {setTimeout(set_zoom, 5);}
}
setTimeout(set_zoom, 5);

我用这个来确保缩放级别不超过设置的级别,这样我就知道卫星图像是可用的。

向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);