You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Turf.js为每个GIS坐标点绑定对应ID属性?

为Turf.js生成的Point绑定对应ID属性

问题场景

现有一组地理坐标数据:

let geo_points = [  
   { "lnglat":[100,50], "id": 1 },
   { "lnglat":[100,50], "id": 2 },
   ....
];

使用Turf.js的turf.pointsWithinPolygon判断点是否在预定义GeoJSON范围时,输出结果丢失了ID属性。尝试直接传入ID数组给turf.points,导致每个Point的properties被设为包含所有ID的数组,不符合需求。需要实现每个Point的properties对应自身的ID,期望格式:

{ 
   type: 'FeatureCollection', features:
       [ {type: 'Feature', properties: {id: 1}, geometry: {…}},
         {type: 'Feature', properties: {id: 2}, geometry: {…}}
       ]
}

解决方案

方法1:逐个创建带属性的Point再组合

遍历原始数据,为每个坐标点创建带对应ID属性的Point,再组合成FeatureCollection:

// 遍历生成单个带属性的Feature
const features = geo_points.map(item => {
  return turf.point(item.lnglat, { id: item.id });
});
// 组合为FeatureCollection
const points = turf.featureCollection(features);

// 执行范围判断
const ptsWithin = turf.pointsWithinPolygon(points, predefined);

方法2:正确使用turf.points的属性参数

turf.points的第二个参数需传入每个点对应的属性对象数组,而非单一的ID数组。调整传参方式:

// 生成与坐标一一对应的属性对象数组
const propertiesList = geo_points.map(item => ({ id: item.id }));
// 提取所有坐标
const lnglats = geo_points.map(item => item.lnglat);
// 创建带对应属性的Points集合
const points = turf.points(lnglats, propertiesList);

// 执行范围判断
const ptsWithin = turf.pointsWithinPolygon(points, predefined);

两种方法均可让ptsWithin返回的结果中保留每个点的ID属性,满足需求。

内容的提问来源于stack exchange,提问作者user824624

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:12:41