如何移除GeoJSON重复要素,创建含唯一要素的FeatureCollection?
移除GeoJSON集合中的重复Feature
给定以下GeoJSON集合:
{ "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 13.55791, 52.54459 ] }, "properties": { "title": "Sommer 2022", "opening_hours": null } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 13.39519, 52.5203 ] }, "properties": { "title": "Winter", "opening_hours": "Sa,Su,PH 11:00-17:00" } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [ 13.39519, 52.5203 ] }, "properties": { "title": "Winter", "opening_hours": "Sa,Su,PH 11:00-17:00" } } ] }
如何移除重复的Feature,最终得到一个包含唯一Feature的GeoJSON集合?
解决方案
可以通过将Feature转换为唯一字符串标识,结合Set数据结构过滤重复项,具体实现如下:
代码示例
// 原始GeoJSON数据 const originalGeoJSON = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Point", "coordinates": [13.55791, 52.54459] }, "properties": { "title": "Sommer 2022", "opening_hours": null } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [13.39519, 52.5203] }, "properties": { "title": "Winter", "opening_hours": "Sa,Su,PH 11:00-17:00" } }, { "type": "Feature", "geometry": { "type": "Point", "coordinates": [13.39519, 52.5203] }, "properties": { "title": "Winter", "opening_hours": "Sa,Su,PH 11:00-17:00" } } ] }; // 定义去重函数 const removeDuplicateFeatures = (geoJSON) => { const seen = new Set(); // 过滤重复Feature const uniqueFeatures = geoJSON.features.filter(feature => { // 将Feature对象序列化为字符串,作为唯一标识 const featureKey = JSON.stringify(feature); if (!seen.has(featureKey)) { seen.add(featureKey); return true; } return false; }); // 返回包含唯一Feature的新GeoJSON集合 return { ...geoJSON, features: uniqueFeatures }; }; // 执行去重并输出结果 const uniqueGeoJSON = removeDuplicateFeatures(originalGeoJSON); console.log(JSON.stringify(uniqueGeoJSON, null, 2));
代码说明
- 唯一标识生成:使用
JSON.stringify()将每个Feature转换为字符串,完全相同的Feature会生成一致的字符串。 - 重复过滤:利用
Set的唯一性特性,记录已出现的Feature字符串标识,过滤掉重复项。 - 返回新集合:保留原GeoJSON的其他属性,仅替换为去重后的features数组。
内容的提问来源于stack exchange,提问作者JJD
相关产品推荐
相关产品推荐

