testLat,testLon,polygonPoints分别是要判断的点的纬度坐标、点的经度坐标、多边形的顶点数组
注:openlayers获取多边形的顶点坐标数组时,最后一个点的坐标与起始点坐标相同,记得将最后一个点的坐标排除出去
function IsPointInPolygon(testLat,testLon,polygonPoints){
if (polygonPoints.length < 3) return false;
let iSum = 0,iCount = polygonPoints.length;
let dLon1, dLon2, dLat1, dLat2, dLon;//点1,点2的经度纬度;需要判断的点与多边形边的交点经度
let bool = false;
/**判断是否是顶点,如果是顶点则直接返回**/
for (let i = 0; i < iCount; i++) {
dLon1 = polygonPoints[i][0];
dLat1 = polygonPoints[i][1];
if (testLon == dLon1 && testLat == dLat1) {
bool = true;
}
}
/**判断顶点结束**/
if(bool){
return bool
}else{
for (let i = 0; i < iCount; i++) {
if (i == iCount - 1) {
dLon1 = polygonPoints[i][0];
dLat1 = polygonPoints[i][1];
dLon2 = polygonPoints[0][0];
dLat2 = polygonPoints[0][1];
} else {
dLon1 = polygonPoints[i][0];
dLat1 = polygonPoints[i][1];
dLon2 = polygonPoints[i + 1][0];
dLat2 = polygonPoints[i + 1][1];
}
//以下语句判断A点是否在边的两端点的水平平行线之间,在则可能有交点,开始判断交点是否在左射线上
if (((testLat >= dLat1) && (testLat < dLat2)) || ((testLat >= dLat2) && (testLat < dLat1))) {
if (Math.abs(dLat1 - dLat2) > 0) {
//得到 A点向左射线与边的交点的x坐标:
dLon = dLon1 - ((dLon1 - dLon2) * (dLat1 - testLat)) / (dLat1 - dLat2);
if (dLon < testLon) iSum++;
}
}
}
if (iSum % 2 != 0){
bool = true;
}
return bool;
}
}