Javascript Google Maps v3 - 为什么 LatLngBounds.contains 返回 false
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5405539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Maps v3 - Why is LatLngBounds.contains returning false
提问by Mario Menger
I have the following code in which I would expect the contains method to return true, but it returns false:
我有以下代码,我希望 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
On the same page, where map is a reference to the Map object, the following code returns true as expected:
在同一页面上,其中 map 是对 Map 对象的引用,以下代码按预期返回 true:
map.getBounds().contains(map.getBounds().getCenter())
Why might my call to bounds.contains
be returning false?
为什么我的电话bounds.contains
返回错误?
回答by Mario Menger
Ah, brilliant. The google.maps.LatLngBounds
constructor expects SouthWest and NorthEast LatLng
parameters. I have somehow bungled up my coordinates and passed in NorthWest and SouthEast instead!
啊,厉害。该google.maps.LatLngBounds
构造预计西南和东北LatLng
参数。我不知何故弄错了我的坐标,而是从西北和东南通过了!
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
Lesson learned: getCenter
doesn't care if you created the LatLngBounds
with NorthWest and SouthEast instead, but if you want contains
to return a useful answer you better pass in the suggested SouthWest and NorthEast!
经验教训:getCenter
并不关心您是否LatLngBounds
使用 NorthWest 和 SouthEast创建了,但是如果您想contains
返回一个有用的答案,您最好传入建议的 SouthWest 和 NorthEast!
回答by axs
I guess its easier to try this. It works for me without having to worry about NE orSW
我想尝试这个更容易。它对我有用而不必担心 NE 或 SW
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
I know this post is old, but I came searching for answers here, so thought of updating from what I have learnt.
我知道这篇文章很旧,但我是来这里寻找答案的,所以想从我学到的东西中更新。
回答by paulalexandru
This is the way that it worked for me:
这是它对我有用的方式:
var bounds = new google.maps.LatLngBounds();
bounds.extend(54.69726685890506,-2.7379201682812226);
bounds.extend(55.38942944437183, -1.2456105979687226);
map.fitBounds(bounds);