判断一个点是否在多边形里面

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/whgyxy/article/details/86585198

判断一个点是否在多边形里面

判断一个点是否在一个多边形里面,会在很多地方用到。尤其是,给你一个多边形,不管是凹的,凸的,任意形状,然后再来一个点的位置,任凭你这个点的位置在哪,都能快速判断这个点是不是属于这个多边形,不管点在哪,快到碗里来

开始以为判断一个点是否属于多边形的算法非常复杂,我都准备好闭关修炼苦攻算法,没想到原理是这么简单,so easy~

这个算法用途非常广泛,可以用在地理位置计算上,看我画的地盘你有没有来过,我可以任意画形状。这里给出scala实现,这里经度对应坐标系中的x,纬度对应y


  case class Location(longitude: Double, latitude: Double)


/**
    * 判断一点是否在多边形里面
    *
    * @param list 组成多边形的点集合,有顺序
    * @param test 待检测点
    * @return 待检测点是否在多边形里面
    */
  def isInPloy(list: Array[Location], test: Location, percision: Double = 0.00001): Boolean = {
    var flag = false
    var i = 0
    var j = list.length - 1
    for (i <- list.indices) {
      val pointI = list(i)
      val pointJ = list(j)
      if ((compDouble(test.longitude, pointI.longitude, percision) && compDouble(test.latitude, pointI.latitude, percision)) ||
        (compDouble(test.longitude, pointJ.longitude, percision) && compDouble(test.latitude, pointJ.latitude, percision)))
        return true
      if ((test.latitude <= pointI.latitude && test.latitude > pointJ.latitude) || (test.latitude <= pointJ.latitude && test.latitude > pointI.latitude)) {
        val x = pointI.longitude + (test.latitude - pointI.latitude) * (pointJ.longitude - pointI.longitude) / (pointJ.latitude - pointI.latitude)
        if (compDouble(x, test.longitude, percision))
          return true
        if (x > test.longitude)
          flag = !flag
      }
      j = i
    }
    flag
  }

  /**
    * Doulbe类型数字判断是否相等
    *
    * @param percision 判断精度
    * @return 是否相等
    */
  def compDouble(x: Double, y: Double, percision: Double): Boolean = {
    if ((x - y).abs < percision) true else false
  }

参考资料

1 算法参考
2 实现参考

猜你喜欢

转载自blog.csdn.net/whgyxy/article/details/86585198