问题描述
我正在寻找一种方法来检查点是否存在于 Google Maps v3 (JavaScript) 中的多边形内.我到处搜索,到目前为止我找到的唯一解决方案是获取多边形的边界,但显示的代码似乎只是创建了一个矩形并不断扩大其表面积以包括所有相关点.
I am looking to find a way of checking if a point exists inside a polygon in Google Maps v3 (JavaScript). I've searched everywhere and the only solutions I have found so far have been to do with getting the bounds of the polygon, but the code shown seems to just create a rectangle and keeps expanding its surface area to include all relevant points.
顺便说一句,我不能只使用一个大正方形,即获得多边形边界的原因是我在地图上有边界多边形,它们不能扩展到彼此的领土.
By the way, the reason I can't just use a big square i.e. getting a polygons bounds, is that I have bordering polygons on the map and they can not expand into each other's territory.
编辑根据下面的回复,我尝试使用我现有的多边形之一实现示例代码,但只是说它没有定义,我不知道为什么.
EDITFollowing on from the reply below, I have tried implementing the example code using one of my existing polygons but it is just saying that it is not defined and I can't figure out why.
这是我的声明:
myCoordinates = [
new google.maps.LatLng(0.457301,-0.597382),
new google.maps.LatLng(0.475153,-0.569916),
new google.maps.LatLng(0.494379,-0.563049),
new google.maps.LatLng(0.506738,-0.553436),
new google.maps.LatLng(0.520470,-0.541077),
new google.maps.LatLng(0.531456,-0.536957),
new google.maps.LatLng(0.556174,-0.552063),
new google.maps.LatLng(0.536949,-0.596008),
new google.maps.LatLng(0.503991,-0.612488),
new google.maps.LatLng(0.473780,-0.612488) ];
polyOptions = {
path: myCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.6 };
var rightShoulderFront = new google.maps.Polygon(polyOptions);
rightShoulderFront.setMap(map);
这里是我检查要点的地方:
and here is where I am checking for the point:
var coordinate = selectedmarker.getPosition();
var isWithinPolygon = rightShoulderFront.containsLatLng(coordinate);
console.log(isWithinPolygon);
但它不断出现错误:Uncaught ReferenceError: rightShoulderFront is not defined
But it keeps coming up with the error: Uncaught ReferenceError: rightShoulderFront is not defined
推荐答案
一种解决此问题的算法是光线投射.在此处查看说明.
One algorithm to solve this is ray-casting. See an explanation here.
您可以在此处找到为 Google Maps JS API V3 实现此功能的代码.
And you can find code implementing this for the Google Maps JS API V3 here.
HTH.
这篇关于Google Maps v3:检查多边形中是否存在点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!