2008-11-27 54 views
8

我想將x個地理位置傳遞給Google Maps API,並使其圍繞這些位置居中並設置適當的縮放級別,以便所有位置都可見在地圖上。即顯示當前在地圖上的所有標記。讓Google以地圖爲中心並適當放大

這是可能與谷歌地圖API提供默認情況下,還是我需要解決,以建立自己的?

回答

3

有很多方法可以做到這一點,但如果您使用的是V2 API,這很容易。看到這個post for an example,this group postthis post

+0

注意,第一個鏈接提到getBoundsZoomLevel()是未公開的 - 這不再是真實的。我實現了一個類似於我的項目的東西,它運行良好 - 除非我希望我知道GBounds.extend()然後! – 2008-11-27 04:28:57

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); 
    
+0

這個例子不是很清楚 – Francesco 2010-11-30 16:48:47

+2

@camelCase:取決於你的技能,+1正是我在找的東西 – Moak 2011-03-15 04:05:21

1

格雷的想法是偉大的,但不工作原樣。我已經制定出了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); 
    } 

}