如何在Mapbox绘制多边形前验证坐标的GeoJSON有效性?
检查Mapbox多边形GeoJSON有效性的函数
要解决Input data is not a valid GeoJSON object错误,你可以编写一个严格遵循GeoJSON规范的验证函数,直接检查多边形的结构和坐标合法性:
import { Polygon } from 'mapbox-gl'; function isInvalidPolygon(polygon: Polygon): boolean { // 1. 检查基础类型结构 if (!polygon || polygon.type !== 'Polygon' || !Array.isArray(polygon.coordinates)) { return true; } const rings = polygon.coordinates; // 2. 检查至少有一个外环 if (rings.length === 0) { return true; } // 3. 遍历所有环(外环+内环)检查合法性 for (const ring of rings) { // 环必须是数组,且至少包含4个点(闭合需要首尾相同) if (!Array.isArray(ring) || ring.length < 4) { return true; } // 检查首尾坐标是否一致(闭合要求) const firstPoint = ring[0]; const lastPoint = ring[ring.length - 1]; if (firstPoint[0] !== lastPoint[0] || firstPoint[1] !== lastPoint[1]) { return true; } // 检查每个坐标点的数值范围 for (const [lng, lat] of ring) { // 经度范围:-180 到 180,纬度范围:-90 到 90 if (typeof lng !== 'number' || typeof lat !== 'number' || lng < -180 || lng > 180 || lat < -90 || lat > 90) { return true; } } } // 所有检查通过,多边形有效 return false; }
使用示例
在绘制多边形前调用该函数,提前拦截无效数据:
const userPolygon: Polygon = { type: 'Polygon', coordinates: [ [ [-122.4194, 37.7749], [-122.4074, 37.7749], [-122.4074, 37.7829], [-122.4194, 37.7829], [-122.4194, 37.7749] // 必须闭合 ] ] }; if (isInvalidPolygon(userPolygon)) { console.error('无效的多边形坐标,请检查GeoJSON格式'); } else { // 执行Mapbox绘制逻辑 map.addLayer({ id: 'user-polygon', type: 'fill', source: { type: 'geojson', data: userPolygon }, paint: { 'fill-color': '#888888', 'fill-opacity': 0.5 } }); }
额外说明
- 该函数严格遵循GeoJSON官方规范,覆盖了最常见的无效场景:结构错误、未闭合、坐标点数量不足、经纬度超出合理范围。
- 如果需要更复杂的验证(比如检查外环逆时针、内环顺时针的Mapbox推荐规则),可以在函数中添加对应的判断逻辑。
内容的提问来源于stack exchange,提问作者Avraham Wales
相关产品推荐
相关产品推荐

