首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在将fitBounds()与Google Maps API V3一起使用之后使用setZoom()

在将fitBounds()与Google Maps API V3一起使用之后使用setZoom()
EN

Stack Overflow用户
提问于 2010-12-24 06:47:27
回答 5查看 97K关注 0票数 81

我正在使用fitBounds()在我的地图上设置缩放级别,包括当前显示的所有标记。但是,当我只有一个标记可见时,缩放级别是100% (...我想是哪个变焦级别20 )。但是,我不希望它被放大那么远,这样用户就可以调整标记的位置,而不必缩小。

我有以下代码:

代码语言:javascript
运行
复制
var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter());
this.map.map.fitBounds(this.map.bounds);
if (this.markerNumber === 1) {
  this.map.map.setZoom(16);
}
this.markerNumber++;

其中,this.map.bounds以前定义为:

代码语言:javascript
运行
复制
this.map.bounds = new google.maps.LatLngBounds();

然而,我遇到的问题是,如果我使用this.map.map.fitBounds(this.map.bounds);this.map.map.setZoom(16);行就不能工作,但是,我知道这行代码是正确的,因为当我注释掉fitBound()行时,setZoom()就神奇地开始工作了。

你知道我该怎么解决这个问题吗?如果我不能让它工作,我正在考虑设置一个maxZoom级别作为替代。

EN

回答 5

Stack Overflow用户

发布于 2012-08-16 04:15:20

代码语言:javascript
运行
复制
google.maps.event.addListenerOnce(yourMap, 'bounds_changed', function(event) {
  if (this.getZoom() > 15) {
    this.setZoom(15);
  }
});

这个解决方案工作得更好,…而不是等待超时来移除监听器。在使用fitBounds之前直接调用它(我相信之后调用也可以)。

票数 107
EN

Stack Overflow用户

发布于 2013-10-04 00:22:22

我发现额外的变焦有点刺耳。如果您在调用fitBounds之前设置了maxZoom选项(然后在回调中取消设置),则可以避免这种情况:

代码语言:javascript
运行
复制
map.setOptions({
    maxZoom: 10
});

map.setCenter(new google.maps.LatLng(-89, -179)); // make sure it changes so the idle listener gets called back

map.fitBounds(bounds);

var listener = google.maps.event.addListenerOnce(map, "idle", function()
{
    map.setOptions({
        maxZoom: 999
    });
});
票数 16
EN

Stack Overflow用户

发布于 2010-12-24 23:08:34

我有一个简单而肮脏的解决方案。

使用If else ...

代码语言:javascript
运行
复制
var marker = this.map.createMarker(view.latlng, this.markerNumber);
this.map.bounds.extend(view.latlng);
this.map.map.setCenter(this.map.bounds.getCenter()); 
if (this.markerNumber === 1) {
  this.map.map.setZoom(16);
} else {
   this.map.map.fitBounds(this.map.bounds);
}       
this.markerNumber++;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4523023

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档