如何从JavaScript的FeatureCollection数组中提取经纬度并保存为独立变量?
提取FeatureCollection中的经纬度并保存为独立变量
直接用下面的代码就能实现需求,同时做了空值判断避免报错:
autofillCollection.addEventListener('retrieve', (event) => { const featureCollection = event.detail; const inputEl = event.target; // 确保features数组存在且有数据 if (featureCollection.features && featureCollection.features.length > 0) { // 获取第一个地理要素 const targetFeature = featureCollection.features[0]; // 提取坐标(GeoJSON规范是[经度, 纬度]) const [longitude, latitude] = targetFeature.geometry?.coordinates || []; // 验证坐标有效性 if (typeof longitude === 'number' && typeof latitude === 'number') { console.log('经度:', longitude); console.log('纬度:', latitude); // 这里可以直接使用longitude和latitude变量做后续操作 } } });
关键步骤说明
- 空值校验:先判断
features数组是否存在且非空,防止无数据时出现报错 - 坐标提取:GeoJSON格式里
Point类型的坐标是[经度, 纬度]的顺序,直接通过解构赋值或索引获取 - 可选链保护:用
?.访问geometry,避免某些要素没有几何信息时抛出错误 - 有效性验证:确认提取到的是数值类型,保证后续使用的可靠性
如果你的场景中features数组有多个要素,可以用循环遍历处理每一个:
// 遍历所有要素提取经纬度 featureCollection.features.forEach(feature => { const [lon, lat] = feature.geometry?.coordinates || []; if (typeof lon === 'number' && typeof lat === 'number') { console.log(`要素ID ${feature.properties.id} 的经纬度:`, lon, lat); } });
内容的提问来源于stack exchange,提问作者Casey Davis
相关产品推荐
相关产品推荐

