前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >GIS算法—判断点在面内

GIS算法—判断点在面内

作者头像
lzugis
发布2023-05-27 14:33:08
4070
发布2023-05-27 14:33:08
举报

概述

今天分享一个简单的空间关系的判断:点是否在面内。

分析

image.png
image.png

如上图:

  • 红色为多边形,其坐标为[[0,0],[3,2],[3,3],[2,3],[0,0]];
  • A为多边形四至外的点,其坐标为[-1, -1],计算结果为false;
  • B点位多边形内的点,坐标为[2,2],,计算结果为true
  • C点位多边形边界上的点,其坐标为[3, 2.5],计算结果为true;
  • D为多边形四至内的点,但在多边形外,其坐标为[1, 2],计算结果为false

实现

代码语言:javascript
复制
function isPointInPolygon (point, polygon) {
    if(!point || point.length < 0) throw new Error('not a point')
    if(!polygon || polygon.length < 4 || polygon[0].join('') !== polygon[polygon.length - 1].join('')) throw new Error('not a polygon')

    const [x, y] = point
    const xs = polygon.map(([x, y]) => x)
    const ys = polygon.map(([x, y]) => y)
    const xsSort = xs.sort((a, b) => a - b)
    const ysSort = ys.sort((a, b) => a - b)
    // 在四至内
    const inBBOX = () => {
        const [xmin, ymin, xmax, ymax] = [
            xsSort[0],
            ysSort[0],
            xsSort[xsSort.length - 1],
            ysSort[ysSort.length - 1]
        ]
        return x >= xmin && x <= xmax && y >= ymin && y <= ymax
    }
    // 点在线上
    const onBorder = () => {
        let res = false
        for (let i = 0; i < polygon.length - 2; i++) {
            const [xi, yi] = polygon[i]
            const [xj, yj] = polygon[i+1]
            const k1 = (yj - yi)/(xj - xi)
            const k2 = (yj - y)/(xj - x)
            if(k1 === k2) {
                res = true
                break
            }
        }
        return res
    }
    // 点在多边形内部
    const inPolygon = () => {
        let odd = false;
        for (let i = 0, j = polygon.length - 1; i < polygon.length; i++) {
            if (((polygon[i][1] > y) !== (polygon[j][1] > y))
                && (x < ((polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0]))) {
                odd = !odd;
            }
            j = i;
        }
        return odd;
    }

    if(!inBBOX()) return false
    if(onBorder()) return true
    return inPolygon()
}

ABCD四点的测试及结果如下:

image.png
image.png
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 概述
  • 分析
  • 实现
相关产品与服务
腾讯云服务器利旧
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档