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

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


当前回答

为了配合另一个解决方案-我发现“监听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);
    });
  }
});

其他回答

我所做的就是:

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

它适用于V3 API。

请尝尝这个。

// Find out what the map's zoom level is
zoom = map.getZoom();
if (zoom == 1) {
  // If the zoom level is that low, means it's looking around the
world.
  // Swap the sw and ne coords
  viewportBounds = new
google.maps.LatLngBounds(results[0].geometry.location, initialLatLng);
  map.fitBounds(viewportBounds);
}

如果这对你有帮助的话。

愿一切都好!

如果'bounds_changed'没有正确地触发(有时谷歌似乎不完全接受坐标),那么考虑使用'center_changed'代替。

每次调用fitBounds()时都会触发'center_changed'事件,尽管它会立即运行,而不一定是在地图移动之后。

在正常情况下,'idle'仍然是最好的事件侦听器,但这可能会帮助一些人在调用fitBounds()时遇到奇怪的问题。

参见谷歌maps fitBounds回调

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

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

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

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

有同样的问题,需要适应地图上的许多标记。 这解决了我的问题:

申报范围 koderoid提供的使用方案(用于每个标记集bounds.extend(objLatLng)) 执行fitbounds后映射完成: google.maps.event。addListenerOnce(map, 'idle', function() { 地图。fitBounds(边界); });