2011-11-17 105 views
6

我遇到了一個問題,其中調用map.fitBounds似乎縮小。我正在嘗試使用backbone.js路由器來保存url中的地圖邊界。我希望能夠爲網址添加書籤,並且稍後讓地圖看起來完全一樣。谷歌地圖API 3縮小fitBounds

我注意到在調音臺中調用map.fitBounds(map.getBounds())會一直縮小。我希望它不會改變地圖。

這是正常的行爲嗎?我如何執行此操作,以便地圖從一步到另一步看起來都一樣?

謝謝

回答

9

這個Google Map API的問題曾經討論過幾次。請參閱:

功能map.fitBounds()將視包含的範圍。但map.getBounds()函數返回一些額外的邊距視圖邊界(請注意,這是正常的行爲,沒有錯誤)。放大的邊界不再適合先前的視口,因此地圖縮小。

解決您的問題的一個簡單方法是使用地圖中心和縮放級別。參見功能map.getCenter(),map.setCenter(),map.getZoom()map.setZoom()

+0

我花了我16個小時以上在這裏降落。即使這沒有錯誤,也應該爲那些試圖這樣做的人解決。 –

0

我也注意到這個問題。我的解決方案是將map.getBounds()與我設定的界限進行比較;如果它們相同,我將跳過map.fitBounds()呼叫。

1

固定在2017年

這個問題把它發送到map.fitBounds()之前略有縮水邊框。

這裏是一個功能縮小邊框:

// Values between 0.08 and 0.28 seem to work 
// Any lower and the map will zoom out too much 
// Any higher and it will zoom in too much 
var BOUNDS_SHRINK_PERCENTAGE = 0.08; // 8% 

/** 
* @param {google.maps.LatLngLiteral} southwest 
* @param {google.maps.LatLngLiteral} northeast 
* @return {Array[google.maps.LatLngLiteral]} 
*/ 
function slightlySmallerBounds(southwest, northeast) { 
    function adjustmentAmount(value1, value2) { 
    return Math.abs(value1 - value2) * BOUNDS_SHRINK_PERCENTAGE; 
    } 

    var latAdjustment = adjustmentAmount(northeast.lat, southwest.lat); 
    var lngAdjustment = adjustmentAmount(northeast.lng, southwest.lng); 

    return [ 
    {lat: southwest.lat + latAdjustment, lng: southwest.lng + lngAdjustment}, 
    {lat: northeast.lat - latAdjustment, lng: northeast.lng - lngAdjustment} 
    ] 
} 

使用方法如下:

// Ensure `southwest` and `northwest` are objects in google.maps.LatLngLiteral form: 
// southwest == {lat: 32.79712, lng: -117.13931} 
// northwest == {lat: 32.85020, lng: -117.09356} 

var shrunkBounds = slightlySmallerBounds(southwest, northeast); 
var newSouthwest = shrunkBounds[0]; 
var newNortheast = shrunkBounds[1]; 

// `map` is a `google.maps.Map` 
map.fitBounds(
    new google.maps.LatLngBounds(newSouthwest, newNortheast) 
); 

我有一個應用程序做同樣的事情爲codr:保存在當前地圖範圍URL,並在刷新時從URL邊界初始化映射。這個解決方案對此非常有效。

爲什麼這樣嗎?

谷歌地圖本質上是做這個的時候fitBounds()叫做:

  1. 中心在給定的邊界框的中心點在地圖。
  2. 放大到最高縮放級別,其中視口包含給定邊界內部的視口框。

如果給定的範圍將正是視匹配,谷歌地圖並不認爲是「含有」的範圍,所以它會縮小一個多水平。

0

對於2018年看到此問題的人,Google Maps API v3現在支持第二個padding參數,該參數指定要在您指定的邊界周圍包含的填充量。

爲避免縮小,只需撥打fitBounds並填充0即可。對於這個例子,它將是map.fitBounds(map.getBounds(), 0)