【问题标题】:Google Maps v3 API Extend Bounds. Javascript How-To?Google Maps v3 API 扩展边界。 Javascript 操作方法?
【发布时间】:2020-03-06 10:01:37
【问题描述】:
function initialize(){
// Creating a map
var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 10,
  center: new google.maps.LatLng(53.0123601276819, -2.44519164333635),
  mapTypeId: google.maps.MapTypeId.ROADMAP
});

var m = [];

function addMarker(title, lat, lng) {
    m[m.length] = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map,
        title: title,  
        clickable: true,
        icon: 'http://domain.com/MVC/images/full.png' 
    });

} 

addMarker('Home', 53.0682143712504, -2.52150736731894);
addMarker('Away', 53.0123601276819, -2.44519164333635);
addMarker('Away', 59.0123601276819, -2.44519164333635);    

// Create a LatLngBounds object
var bounds = new google.maps.LatLngBounds(); 

for (var i = 0; i < m.length; i++) {
  // Insert code to add marker to map here

  // Extend the LatLngBound object
  bounds.extend(m[i]);

}
alert(m[0]);
map.fitBounds(bounds);
  document.write(getBounds());   

}

以上是我的代码。

我的目的是开发一张显示大量标记的地图并平移缩放以使所有标记都适合我的屏幕。

我是 JS 新手。

我的理解是

var m = [];

创建一个空数组。

然后每次我调用addMarker() 时,详细信息都会添加到这个数组中

在顶部我设置了默认缩放和中心点。

然后我添加各种标记。

然后我循环遍历 m 数组中的每个键,并使用其中的数据扩展边界。

我的理解是map.fitBounds(bounds); 应该重新定义缩放/中心以适合所有标记。

它没有。 我所有的标记都显示了,但是缩放/中心不是自动调整的,我不知道为什么。

任何建议将不胜感激。 谢谢

【问题讨论】:

    标签: javascript google-maps


    【解决方案1】:

    您需要将LatLng 对象传递给bounds.extend 函数。

    代码如下:

    ....
    bounds.extend(new google.maps.LatLng(lat, lng));
    ....
    

    【讨论】:

    • 这对我不起作用。 Uncaught TypeError: Object [object Array] has no method 'lat'
    【解决方案2】:

    这是对上述答案的澄清,它是正确的,只是缺少括号和简短的内容。

    //make an empty bounds variable
    var bounds = new google.maps.LatLngBounds();
    
    
    //do your map stuff here
    //special note: make sure your lat and lng are floats or googleMaps will error
    var lat = 38.103;
    var lng = -121.572;
    bounds.extend(new google.maps.LatLng(lat, lng));
    
    
    //adjust the viewport of the map
    //special note: this only needs to be done once, don't put it in a loop
    map.fitBounds(bounds);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 2013-03-01
      • 2011-03-18
      • 2015-04-14
      • 1970-01-01
      • 2011-08-23
      相关资源
      最近更新 更多