检测标记是否在谷歌地图上的圆形覆盖范围内(Javascript API V3)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8766218/
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
Detect if marker is within circle overlay on Google Maps (Javascript API V3)
提问by Joey Emery
I have markers dotted around a map, and a radius (circle overlay) on a marker marking your location (which changes every time you move). Is there any way I can check to see if the other markers come inside the circle?
我在地图周围点缀了标记,在标记您的位置的标记上有一个半径(圆圈叠加)(每次移动都会改变)。有什么办法可以检查其他标记是否在圆圈内?
UPDATE
更新
I got around this by looping through each other marker, and using the geometry library calculating the distance between your marker and the other marker and then a simple if statement to see if it's less than 100 meters.
我通过遍历彼此的标记来解决这个问题,并使用几何库计算您的标记和另一个标记之间的距离,然后使用一个简单的 if 语句来查看它是否小于 100 米。
function checkAllChests() {
var Current = 0;
$.each(treasureArray, function() {
//var thisLocation = treasureArray[Current].getPosition();
var distanceBetween = Math.ceil(google.maps.geometry.spherical.computeDistanceBetween(treasureArray[Current].getPosition(), marker_me.getPosition()));
if(distanceBetween < 100) {
alert('CAN OPEN THIS CHEST');
}
Current++;
});
}
I'd like to note that the above code uses jQuery, so if you aren't using jQuery it won't work.
我想指出的是,上面的代码使用了 jQuery,所以如果您不使用 jQuery,它将无法工作。
回答by Mark
Here's a way to add a contains
method to the google.maps.Circle
class. It first uses the bounding box to exclude a point if it's not even in the bounding box. If it is in the bounding box, then it compares the distance from the point to the center with the radius, and returns true only if the distance is shorter than the radius.
这是一种向类添加contains
方法的方法google.maps.Circle
。它首先使用边界框排除一个点,如果它甚至不在边界框中。如果在边界框内,则将点到中心的距离与半径进行比较,只有当距离小于半径时才返回true。
Once you add the javascript below, you can call the contains() method on your circle object.
添加下面的 javascript 后,您可以在圆对象上调用 contains() 方法。
google.maps.Circle.prototype.contains = function(latLng) {
return this.getBounds().contains(latLng) && google.maps.geometry.spherical.computeDistanceBetween(this.getCenter(), latLng) <= this.getRadius();
}
回答by user4741877
google.maps.Circle.prototype.contains = function(latLng) {
return this.getBounds().contains(latLng) && google.maps.geometry.spherical.computeDistanceBetween(this.getCenter(), latLng) <= this.getRadius();
}