Google Maps v3 - 为什么LatLngBounds.contains返回false

时间:2011-03-23 12:54:46

标签: javascript google-maps google-maps-api-3

我有以下代码,我希望contains方法返回true,但它返回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是对Map对象的引用,以下代码按预期返回true:

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

为什么我对bounds.contains的调用可能会返回false?

3 个答案:

答案 0 :(得分:45)

啊,太棒了。 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并不关心您是否使用NorthWest和SouthEast创建了LatLngBounds,但如果您希望contains返回有用的答案,则最好通过建议SouthWest和NorthEast!

答案 1 :(得分:13)

我想这更容易尝试。它对我有用而不必担心NE或者

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

我知道这篇文章很老,但我来这里寻找答案,所以想到从我学到的东西中更新。

答案 2 :(得分:1)

这就是它对我有用的方式:

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