欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

判断经纬度是否在某个区域内

程序员文章站 2024-02-14 22:59:10
...

通过经纬度信息,判断某点是否在某个区域内

代码

/**
 * 处理区域轮廓点数据
 * path : [ [ lon,lat ] ]
 */
export function preceedPointInArea(lng, lat, points) {
  const polygon = [];
  for (const point of points) {
    if (point.length == 2) {
      point["lng"] = parseFloat(point[0]);
      point["lat"] = parseFloat(point[1]);
      polygon.push(point);
    }
  }
  return isPointInPolygon(polygon, lng, lat);
}

/**
 * 判断点是否在某个区域
 */
export function isPointInPolygon(polygon, lng, lat) {
  const numberOfPoints = polygon.length;
  const polygonLats = [];
  const polygonLngs = [];
  for (let i = 0; i < numberOfPoints; i++) {
    polygonLats.push(polygon[i]["lat"]);
    polygonLngs.push(polygon[i]["lng"]);
  }
  let polygonContainsPoint = false;
  for (
    let node = 0, altNode = numberOfPoints - 1;
    node < numberOfPoints;
    altNode = node++
  ) {
    if (
      polygonLngs[node] > lng != polygonLngs[altNode] > lng &&
      lat <
        ((polygonLats[altNode] - polygonLats[node]) *
          (lng - polygonLngs[node])) /
          (polygonLngs[altNode] - polygonLngs[node]) +
          polygonLats[node]
    ) {
      polygonContainsPoint = !polygonContainsPoint;
    }
  }
  return polygonContainsPoint;
}

使用

 import { preceedPointInArea } from "./utli.js";
 const path = [
 	[ 120,25 ],
 	[ 130,25 ],
 	[ 130,20 ],
 	[ 120,20 ]
 ];
 console.log(preceedPointInArea(121.5654, 24.033, path)); // true
相关标签: javascript