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

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


当前回答

我已经找到了一个解决方案,在调用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变量进行一些操作,以使其达到您想要的位置。它将根据缩放级别和地图画布的尺寸而变化。

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

其他回答

google.maps.event.addListener(marker, 'dblclick', function () {
    var oldZoom = map.getZoom(); 
    map.setCenter(this.getPosition());
    map.setZoom(parseInt(oldZoom) + 1);
});

编辑:请看下面马特·戴蒙德的评论。

得到它!试试这个:

map.fitBounds(bounds);
var listener = google.maps.event.addListener(map, "idle", function() { 
  if (map.getZoom() > 16) map.setZoom(16); 
  google.maps.event.removeListener(listener); 
});

根据您的需要进行修改。

我使用:

gmap.setZoom(24); //this looks a high enough zoom value
gmap.fitBounds(bounds); //now the fitBounds should make the zoom value only less

这将使用较小的24和必要的缩放级别根据你的代码,但它可能会改变缩放无论如何,并不关心你有多少缩小。

请试试这个:

map.fitBounds(bounds);

// CHANGE ZOOM LEVEL AFTER FITBOUNDS
zoomChangeBoundsListener = google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
  if (this.getZoom()){
    this.setZoom(15);
  }
});
setTimeout(function(){
  google.maps.event.removeListener(zoomChangeBoundsListener)
}, 2000);

为了配合另一个解决方案-我发现“监听bounds_changed事件,然后设置新的缩放”方法对我来说并不可靠。我认为我有时在地图已经完全初始化之前调用fitBounds,初始化导致一个bounds_changed事件,将使用侦听器,在fitBounds改变边界和缩放级别之前。我最终得到了这段代码,到目前为止似乎还可以工作:

// If there's only one marker, or if the markers are all super close together,
// `fitBounds` can zoom in too far. We want to limit the maximum zoom it can
// use.
//
// `fitBounds` is asynchronous, so we need to wait until the bounds have
// changed before we know what the new zoom is, using an event handler.
//
// Sometimes this handler gets triggered by a different event, before
// `fitBounds` takes effect; that particularly seems to happen if the map
// hasn't been fully initialized yet. So we don't immediately remove the
// listener; instead, we wait until the 'idle' event, and remove it then.
//
// But 'idle' might happen before 'bounds_changed', so we can't set up the
// removal handler immediately. Set it up in the first event handler.

var removeListener = null;
var listener = google.maps.event.addListener(map, 'bounds_changed', () => {
  console.log(map.getZoom());
  if (map.getZoom() > 15) {
    map.setZoom(15);
  }

  if (!removeListener) {
    removeListener = google.maps.event.addListenerOnce(map, 'idle', () => {
      console.log('remove');
      google.maps.event.removeListener(listener);
    });
  }
});