node.js - 在 NodeJS 中查找 GeoJSON 点所在的多边形
问题描述
给定一个已定义的(lat, lon)
地理点,我试图找到该点所在的多边形。我认为迭代所有多边形效率不高。是否有任何适用于 NodeJS 的函数或库来执行此操作?
const polygon = getPolygonFromPoint(FeatureCollection, x, y);
没有重叠的多边形,实际上我正在使用它来检测定义的 GPS 坐标点位于某个国家的哪个地区。
解决方案
对于多边形测试中的一个简单点,您可以检查turf
哪个具有booleanPointInPolygon
. Turf 在节点中工作,但您应该检查 v5 和 v6+ 之间关于如何相应地使用 npm 的差异。点应该是长/纬度(不是纬度/长),并且可以轻松地将多边形从要素集合的要素几何中拉出。
对于一个更复杂的用例,您有许多点和许多多边形来定位它们,您应该考虑使用rbush
.
请注意,rbush 库是根据多边形的边界框而不是多边形本身构造一个 r-tree,因此使用 r-tree 只是一种大大减少需要测试的多边形数量的方法booleanPointInPolygon
。
示例代码rbush
:
const RBush = require("rbush");
const turfBbox = require("@turf/bbox").default;
const geo = {} // your feature collection...
const maxEntriesPerNode = 50; // check the doco
const tree = new RBush(maxEntriesPerNode);
const bbox2Object = (keys, bbox) => ["minX", "minY", "maxX", "maxY"].reduce((o, k, i) => ({...o, [k]: bbox[i]}), {})
// create rtree from feature collection
geo.features.forEach(feature => {
const leaf = bbox2Object(bboxKeys, turfBbox(feature)); // use bbox of feature
leaf["id"] = feature.properties.SOME_ID; // add some custom properties
tree.insert(leaf);
});
// test a random point from your data
const [x, y] = [123, 456]; // should be long, lat
const test = tree.search({minX: x, minY: y, maxX: x, maxY: y});
// test should have an array of leaves per the tree.insert above
然后,您可以booleanPointInPolygon
对这组减少的多边形执行测试。
推荐阅读
- c# - 如何上下移动虚拟listView项目?
- mongodb - 如何获取文档数组属性的串联列表?
- c# - 在 C# 接口中容纳来自 VB.Net 的参数化方法
- netsuite - NetSuite Suitescript 2.0 如何访问自定义项目选项记录?
- android - Kotlin Firebase onFailureListener 空异常
- reactjs - 如何更改 ag-grid 行数?
- angular - Angular中带有mat复选框的总和
- c# - Swagger 未加载 - 无法加载 API 定义:获取错误未定义
- javascript - JavaScript:创建将嵌套数组中的数据转换为具有多个对象的数组的函数
- angular - 在 mat-table 中加载初始值时不选中复选框