使用Turf进行点在面分析时遇ring undefined错误求助
问题排查:Turf.js booleanPointInPolygon抛出"ring is undefined"错误
错误信息
Uncaught TypeError: ring is undefined inRing index.js:82 booleanPointInPolygon index.js:54 CheckCoordinate CheckCoordinate.jsx:24 CheckCoordinate CheckCoordinate.jsx:23 React 8 commitHookEffectListMount commitPassiveMountOnFiber commitPassiveMountEffects_complete commitPassiveMountEffects_begin commitPassiveMountEffects flushPassiveEffectsImpl flushPassiveEffects commitRootImpl workLoop scheduler.development.js:266 flushWork scheduler.development.js:239 performWorkUntilDeadline scheduler.development.js:533
现有代码
import React, { useState, useEffect } from 'react'; import * as turf from '@turf/turf'; import yardZoneMap from './yard-zone-map.json'; // Adjust the path as necessary function CheckCoordinate(props) { const unparsedString = props.inputCoord || ''; const parsedValues = unparsedString.split(',').map(item => parseFloat(item)); const [pointLocation, setPointLocation] = useState(null); const [isInside, setIsInside] = useState(false); useEffect(() => { if (parsedValues.length === 2) { setPointLocation(parsedValues); } }, [unparsedString]); useEffect(() => { if (pointLocation) { const point = turf.point(pointLocation); // Correctly define the point here let insideAnyPolygon = false; yardZoneMap.features.forEach(feature => { if (turf.booleanPointInPolygon(point, feature)) { insideAnyPolygon = true; } }); setIsInside(insideAnyPolygon); } }, [pointLocation]); return ( <div> <p>Point is inside polygon: {isInside ? 'Yes' : 'No'}</p> </div> ); } export default CheckCoordinate;
排查方向
- 检查Feature几何类型:确保
yardZoneMap.features中的所有Feature都是Polygon或MultiPolygon类型。turf.booleanPointInPolygon仅支持这两类几何,其他类型(如Point、LineString)会导致内部处理失败。 - 验证坐标结构完整性:即使GeoJSON格式通过在线工具校验,也要手动检查每个Feature的
geometry.coordinates:- Polygon需符合
[[[lon, lat], ...]]层级 - MultiPolygon需符合
[[[[lon, lat], ...]], ...]层级
若存在空数组、层级缺失的情况,会导致turf找不到所需的ring(环)。
- Polygon需符合
- 添加数据过滤逻辑:遍历features时先过滤无效数据,避免传入非法参数:
yardZoneMap.features.forEach(feature => { // 跳过非多边形类Feature if (!['Polygon', 'MultiPolygon'].includes(feature.geometry.type)) return; // 跳过坐标为空的Feature if (!feature.geometry.coordinates || feature.geometry.coordinates.length === 0) return; if (turf.booleanPointInPolygon(point, feature)) { insideAnyPolygon = true; } }); - 确认坐标顺序:Turf.js默认采用**[经度, 纬度]**顺序,检查用户输入的坐标是否符合该规则,顺序错误可能引发异常或判断结果错误。
- 检查Turf.js版本:不同版本对GeoJSON的处理逻辑可能有差异,尝试切换到稳定版本(如@turf/turf@6.5.0)测试。
内容的提问来源于stack exchange,提问作者TheFloof
相关产品推荐
相关产品推荐

