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

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


我使用:

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

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


请尝尝这个。

// 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);
}

如果这对你有帮助的话。

愿一切都好!


在这个函数中,您只需要动态添加元数据来存储几何类型,因为该函数接受任何几何。

“fitGeometries”是一个扩展映射对象的JSON函数。

"geometries"是一个通用的javascript数组,而不是MVCArray()。

geometry.metadata = { type: "point" };
var geometries = [geometry];

fitGeometries: function (geometries) {
    // go and determine the latLngBounds...
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0; i < geometries.length; i++) {
        var geometry = geometries[i];
        switch (geometry.metadata.type)
        {
            case "point":
                var point = geometry.getPosition();
                bounds.extend(point);
                break;
            case "polyline":
            case "polygon": // Will only get first path
                var path = geometry.getPath();
                for (var j = 0; j < path.getLength(); j++) {
                    var point = path.getAt(j);
                    bounds.extend(point);
                }
                break;
        }
    }
    this.getMap().fitBounds(bounds);
},

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

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

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

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

我不喜欢这样建议,但如果你一定要尝试,请先打电话

gmap.fitBounds(范围);

然后创建一个新的Thread/AsyncTask,让它休眠20-50ms左右,然后调用

gmap。setZoom (Math。max(6, gmap.getZoom()));

从UI线程(使用处理程序或AsyncTask的onPostExecute方法)。

我不知道是否有用,只是一个建议。除此之外,你必须自己计算缩放级别,检查是否太低,纠正它,然后调用gmap.setZoom(correctedZoom)


计算完边界后,你可以检查左上角和右下角之间的距离;然后你可以通过测试距离来了解缩放级别(如果距离太远,缩放级别会很低),然后你可以选择是否使用setbound方法或setZoom..


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

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

如果我没记错的话,我假设你想让你的所有点在地图上以最高的缩放级别可见。我通过将地图的缩放级别初始化为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);

结果: 成功!


我所做的就是:

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

它适用于V3 API。


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

得到它!试试这个:

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

根据您的需要进行修改。


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

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

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

希望这能帮助到一些人!


我有同样的问题,我能够解决它使用下面的代码。这个监听器(google.maps.addListenerOnce())事件只会在map.fitBounds()执行之后被触发一次。所以,没有必要

跟踪并手动删除侦听器,或者 等待地图空闲。

它最初设置适当的缩放级别,并允许用户放大和缩小超过初始缩放级别,因为事件侦听器已经过期。例如,如果只调用google.maps.addListener(),那么用户将永远无法放大超过指定的缩放级别(在本例中为4)。由于我们实现了google.maps.addListenerOnce(),用户将能够放大到他/她选择的任何级别。

map.fitBounds(bounds);

var zoom_level_for_one_marker = 4;

google.maps.event.addListenerOnce(map, 'bounds_changed', function(event){
   if (this.getZoom() >= zoom_level_for_one_marker){  
       this.setZoom(zoom_level_for_one_marker) 
   }
});

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

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


这项工作为我的API v3,但设置固定缩放:

var bounds = new google.maps.LatLngBounds();
// extend bounds with each point

gmap.setCenter(bounds.getCenter()); 
gmap.setZoom( 6 );

我已经找到了一个解决方案,在调用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);
});

我只是通过提前设置maxZoom来修复这个问题,然后在之后删除它。例如:

map.setOptions({ maxZoom: 15 });
map.fitBounds(bounds);
map.setOptions({ maxZoom: null });

像我一样,如果你不愿意和听众一起玩,这是我想出的一个简单的解决方案: 在地图上添加一个方法,严格按照你的要求工作,像这样:

    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)来覆盖缩放范围..


请试试这个:

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'没有正确地触发(有时谷歌似乎不完全接受坐标),那么考虑使用'center_changed'代替。

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

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

参见谷歌maps 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文档。


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

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