如何使用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
相关产品推荐
相关产品推荐

