我想將x個地理位置傳遞給Google Maps API,並使其圍繞這些位置居中並設置適當的縮放級別,以便所有位置都可見在地圖上。即顯示當前在地圖上的所有標記。讓Google以地圖爲中心並適當放大
這是可能與谷歌地圖API提供默認情況下,還是我需要解決,以建立自己的?
我想將x個地理位置傳遞給Google Maps API,並使其圍繞這些位置居中並設置適當的縮放級別,以便所有位置都可見在地圖上。即顯示當前在地圖上的所有標記。讓Google以地圖爲中心並適當放大
這是可能與谷歌地圖API提供默認情況下,還是我需要解決,以建立自己的?
有很多方法可以做到這一點,但如果您使用的是V2 API,這很容易。看到這個post for an example,this group post或this post。
對於V3有zoomToMarkers
我用fitBounds(API V3)對於每個點:
聲明變量。
var bounds = new google.maps.LatLngBounds();
與遍歷每個標記FOR循環
for (i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(markers[i].lat, markers[i].lng);
bounds.extend(latlng);
}
最後調用
map.fitBounds(bounds);
格雷的想法是偉大的,但不工作原樣。我已經制定出了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);
}
}
注意,第一個鏈接提到getBoundsZoomLevel()是未公開的 - 這不再是真實的。我實現了一個類似於我的項目的東西,它運行良好 - 除非我希望我知道GBounds.extend()然後! – 2008-11-27 04:28:57