将ADSBExchange接口JSON转GeoJSON并在地图展示的技术咨询
ADSBExchange数据转GeoJSON在Leaflet显示的修正方案
原代码核心问题
- 错误将飞机点位数据构建为
LineString(线要素),飞机是单个点位,应使用Point类型 - 循环中引用未定义的
lat[i]/lon[i]变量,逻辑混乱 - 未采用GeoJSON标准的
FeatureCollection格式组织多个飞机要素
正确转换与加载代码
const settings = { "async": true, "crossDomain": true, "url": "https://adsbexchange-com1.p.rapidapi.com/v2/lat/47.22/lon/10.85/dist/250/", "method": "GET", "headers": { "X-RapidAPI-Key": "", "X-RapidAPI-Host": "adsbexchange-com1.p.rapidapi.com" } }; $.getJSON(settings, function(response) { // 构建标准GeoJSON FeatureCollection const geoJsonData = { type: "FeatureCollection", features: response.data.ac.map(plane => { // 过滤无有效经纬度的飞机数据 if (!plane.lat || !plane.lon) return null; return { type: "Feature", geometry: { type: "Point", // GeoJSON坐标顺序:[经度, 纬度],注意和常规lat/lon顺序相反 coordinates: [plane.lon, plane.lat] }, properties: { flight: plane.flight.trim(), altitude: plane.alt_baro, speed: plane.gs, aircraftType: plane.t, registration: plane.r } }; }).filter(feature => feature !== null) }; const geojsonMarkerOptions = { radius: 8, fillColor: "#ff7800", color: "#000", weight: 1, opacity: 1, fillOpacity: 0.8 }; // 将GeoJSON添加到地图,绑定弹窗显示飞机信息 L.geoJson(geoJsonData, { // 把Point要素转换为Leaflet圆形标记 pointToLayer: function(feature, latlng) { return L.circleMarker(latlng, geojsonMarkerOptions); }, // 为每个标记绑定弹窗 onEachFeature: function(feature, layer) { if (feature.properties) { const popupContent = ` <strong>航班号:</strong> ${feature.properties.flight}<br> <strong>机型:</strong> ${feature.properties.aircraftType}<br> <strong>注册号:</strong> ${feature.properties.registration}<br> <strong>高度:</strong> ${feature.properties.altitude} 英尺<br> <strong>地速:</strong> ${feature.properties.speed} 节 `; layer.bindPopup(popupContent); } } }).addTo(map); });
关键注意事项
- 坐标顺序:GeoJSON标准要求坐标为
[经度, 纬度],和日常习惯的[纬度, 经度]相反,这是加载失败的常见原因 - 数据过滤:部分飞机可能无有效定位数据,必须过滤避免渲染错误
- 要素类型匹配:飞机点位对应GeoJSON的
Point类型,多个点位需用FeatureCollection包裹,单个Feature仅适用于单个要素
内容的提问来源于stack exchange,提问作者Volker Schwarz
相关产品推荐
相关产品推荐

