文章目录
需求:判断经纬度数据是否在某个平面内,将在面上的数据筛选出来。
例如:给出一组平面的经纬度数据,再给出一组点的经纬度数据,筛选出在面范围内的点的数据。
判断方法(直接复制可用):
// 判断点位是否在区域内
static isPointInPolygon(point, pts) {
// point数据格式 ---{longitude: 114.28988366986654, latitude: 23.042948244464927}
// pts数据格式 ---[{latitude:xxx,longitude:xxx}
var N = pts.length //pts [{latitude:xxx,longitude:xxx},{latitude:xxx,longitude:xxx}]
var boundOrVertex = true //如果点位于多边形的顶点或边上,也算做点在多边形内,直接返回true
var intersectCount = 0 // x的交叉点计数
var precision = 2e-10 // 浮点类型计算时候与0比较时候的容差
var p1, p2 // 相邻边界顶点
var p = point // point {latitude:xxx,longitude:xxx}
p1 = pts[0]
for (var i = 1; i <= N; ++i) {
if (p.latitude == p1.latitude && p.longitude == p1.longitude) {
return boundOrVertex
}
p2 = pts[i % N] //右顶点
if (
p.latitude < Math.min(p1.latitude, p2.latitude) ||
p.latitude > Math.max(p1.latitude, p2.latitude)
) {
p1 = p2
continue //下一条射线左点
}
if (
p.latitude > Math.min(p1.latitude, p2.latitude) &&
p.latitude < Math.max(p1.latitude, p2.latitude)
) {
if (p.longitude <= Math.max(p1.longitude, p2.longitude)) {
if (
p1.latitude == p2.latitude &&
p.longitude >= Math.min(p1.longitude, p2.longitude)
) {
return boundOrVertex
}
if (p1.longitude == p2.longitude) {
if (p1.longitude == p.longitude) {
return boundOrVertex
} else {
++intersectCount
}
} else {
var xinters =
((p.latitude - p1.latitude) * (p2.longitude - p1.longitude)) /
(p2.latitude - p1.latitude) +
p1.longitude // 经度交点
if (Math.abs(p.longitude - xinters) < precision) {
return boundOrVertex
}
if (p.longitude < xinters) {
++intersectCount
}
}
}
} else {
if (p.latitude == p2.latitude && p.longitude <= p2.longitude) {
var p3 = pts[(i + 1) % N] //next vertex
if (
p.latitude >= Math.min(p1.latitude, p3.latitude) &&
p.latitude <= Math.max(p1.latitude, p3.latitude)
) {
++intersectCount
} else {
intersectCount += 2
}
}
}
p1 = p2
}
if (intersectCount % 2 == 0) {
//偶数在多边形外
return false
} else {
//奇数在多边形内
return true
}
}
使用:
let includeData = [] // 存放筛选过后的点位数据
pointData.forEach(item => {//pointData 点的数据
let isInclude = GisDataConverter.isPointInPolygon(
{
longitude: item.lon,
latitude: item.lat
},fanwei)//fanwei 面的数据
if (isInclude) {
includeData.push(item)
}
})
今天开心,大吃一斤^ o ^