2011-03-23 20 views
20

我有下面的代碼中,我會期望contains方法返回true,但它返回false:谷歌地圖V3 - 爲什麼LatLngBounds.contains返回false

var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(55.38942944437183, -2.7379201682812226), 
    new google.maps.LatLng(54.69726685890506, -1.2456105979687226) 
); 

var center = bounds.getCenter(); // (55.04334815163844, -1.9917653831249726) 

var x = bounds.contains(center); // returns false 

在同一頁上,在地圖是Map對象的引用,下面的代碼返回true預期:

map.getBounds().contains(map.getBounds().getCenter()) 

爲什麼我的到bounds.contains調用返回false?

回答

42

啊,輝煌。 google.maps.LatLngBounds構造函數期望使用SouthWest和NorthEast LatLng參數。我不知怎的搞砸了我的座標,而是通過了NorthWest和SouthEast!

var bounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(54.69726685890506,-2.7379201682812226), 
    new google.maps.LatLng(55.38942944437183, -1.2456105979687226) 
); 

var center = bounds.getCenter(); // still returns (55.04334815163844, -1.9917653831249726) 

var x = bounds.contains(center); // now returns true 

教訓:getCenter不關心,如果您創建的LatLngBounds與西北和東南代替,但如果你想contains返回一個有用的答案你更好的建議西南和東北繞道!

+0

+1。 – kjy112 2011-03-23 16:17:17

12

我想它更容易嘗試這個。這對我的作品,而不必擔心NE orSW

var bounds = new google.maps.LatLngBounds(); 
bounds.extend(54.69726685890506,-2.7379201682812226); 
bounds.extend(55.38942944437183, -1.2456105979687226); 
var center = bounds.getCenter(); // still returns (55.04334815163844, -1.9917653831249726) 
var x = bounds.contains(center); // now returns true 

我知道這個帖子是老了,但我來尋找答案在這裏,所以想從我學到更新的。

+0

是的,這是一個更有效率和更少混淆的解決方案。 – 2013-08-06 15:12:08

+5

'bounds.extend'需要一個LatLng對象,而不僅僅是數字。 – Sharky 2014-08-18 09:45:15

0

這是方式,它爲我工作:我無法弄清楚,但現在我知道爲什麼

var bounds = new google.maps.LatLngBounds(); 
bounds.extend(54.69726685890506,-2.7379201682812226); 
bounds.extend(55.38942944437183, -1.2456105979687226); 
map.fitBounds(bounds);  
+0

這對我很有用,但是就像Sharky所說的,座標必須是一個LatLng對象,而不僅僅是數字。即: 'myLatLang = new google.maps.LatLng(54.69726685890506,-2.7379201682812226); bounds.extend(myLatLang); ' – JBS 2015-08-31 13:45:39