让Google地图围绕地理位置居中并适当放大

时间:2008-11-27 03:51:47

标签: api google-maps

我想将一定数量的地理位置传递到Google Maps API,并将其置于这些位置的中心位置,并设置相应的缩放级别,以便所有位置在地图上都可见。即显示当前在地图上的所有标记。

默认情况下Google Maps API提供的内容是否可行,或者我自己需要解决此问题?

4 个答案:

答案 0 :(得分:9)

我为每个点使用了fitBounds(API V3):

  1. 声明变量。

    var bounds = new google.maps.LatLngBounds();
    
  2. 使用FOR循环

    浏览每个标记
    for (i = 0; i < markers.length; i++) {
        var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
        bounds.extend(latlng);
    }
    
  3. 最后致电

    map.fitBounds(bounds);
    

答案 1 :(得分:3)

有很多方法可以做到这一点,但如果您使用V2 API则非常容易。请参阅此post for an examplethis group postthis post

答案 2 :(得分:2)

对于V3,zoomToMarkers

答案 3 :(得分:1)

Gray的想法很棒,但不能正常工作。我不得不为 zoomToMarkers API V3制作一个黑客:

function zoomToMarkers(map, markers)
{
    if(markers[0]) // make sure at least one marker is there
    {
        // Get LatLng of the first marker
        var tempmark =markers[0].getPosition();

        // LatLngBounds needs two LatLng objects to be constructed
        var bounds = new google.maps.LatLngBounds(tempmark,tempmark);

        // loop thru all markers and extend the LatLngBounds object
        for (var i = 0; i < markers.length; i++) 
        {
            bounds.extend(markers[i].getPosition());
        }

        // Set the map viewport 
        map.fitBounds(bounds);
    }

}