免费获取FlightTrader的数据并导入GoogleEarth
免费获取FlightTrader的数据并导入GoogleEarth
获取
注意:网站需要魔法才能访问,免费和未登录用户只能看到最近7天的数据。
- 打开 FlightTrader24网站 ;
- 搜索航班号,找到历史数据,按 打开控制台,选择选项卡;
- 点击 按钮,在控制台里找含
flight-playback.json字样的链接,下载下来; - 运行下面的脚本
import sys
import json
from datetime import datetime, timezone
def generate_flight_kml(json_file_path, kml_file_path):
"""
从指定的 JSON 文件路径读取航班数据,并创建一个功能完整、视觉优化的 KML 文件。
Args:
json_file_path (str): 输入的 JSON 文件路径。
kml_file_path (str): 输出的 KML 文件路径。
"""
print(f"读取输入文件: {json_file_path}")
try:
with open(json_file_path, 'r', encoding='utf-8') as f:
data = json.load(f)
# --- 1. 提取所有需要的航班信息 ---
flight_data = data.get('result', {}).get('response', {}).get('data', {}).get('flight', {})
# 用于摘要的信息
flight_id = flight_data.get('identification', {}).get('number', {}).get('default', 'N/A')
# 机场信息
airport_info = flight_data.get('airport', {})
origin = airport_info.get('origin', {})
destination = airport_info.get('destination', {})
origin_name = origin.get('name', 'N/A')
origin_iata = origin.get('code', {}).get('iata', '')
dest_name = destination.get('name', 'N/A')
dest_iata = destination.get('code', {}).get('iata', '')
# 轨迹数据
track = flight_data.get('track', [])
if not track:
print(f"错误: 文件 {json_file_path} 中未找到有效的轨迹数据。")
return
# --- 2. 处理轨迹和数据点 (与之前相同) ---
track_when_tags, track_coord_tags, datapoint_placemarks = [], [], []
for point in track:
timestamp = point.get('timestamp')
lon, lat = point.get('longitude'), point.get('latitude')
alt_m = point.get('altitude', {}).get('meters', 0)
if all([timestamp, lon is not None, lat is not None]):
dt_object = datetime.fromtimestamp(timestamp, tz=timezone.utc)
time_str = dt_object.strftime('%Y-%m-%dT%H:%M:%SZ')
track_when_tags.append(f" <when>{time_str}</when>")
track_coord_tags.append(f" <gx:coord>{lon} {lat} {alt_m}</gx:coord>")
desc_html = f"<![CDATA[<div style='font-family: Arial, sans-serif;'><h3>{flight_id} - 数据点</h3><p><b>时间:</b> {dt_object.strftime('%Y-%m-%d %H:%M:%S UTC')}<br><b>速度:</b> {point.get('speed', {}).get('kmh', 0)} km/h<br><b>高度:</b> {alt_m} 米 (海拔)<br><b>航向:</b> {point.get('heading', 0)}°</p></div>]]>"
datapoint_placemarks.append(f"""
<Placemark>
<TimeStamp><when>{time_str}</when></TimeStamp>
<styleUrl>#datapointStyle</styleUrl>
<Point><coordinates>{lon},{lat},{alt_m}</coordinates></Point>
<name>数据</name>
<description>{desc_html}</description>
</Placemark>""")
track_when_block = "\n".join(track_when_tags)
track_coord_block = "\n".join(track_coord_tags)
datapoint_block = "\n".join(datapoint_placemarks)
# --- 新增:创建航班摘要信息 ---
flight_info_html = f"""
<![CDATA[
<b>航班号:</b> {flight_id}<br>
<b>航空公司:</b> {flight_data.get('airline', {}).get('name', 'N/A')}<br>
<b>机型:</b> {flight_data.get('aircraft', {}).get('model', {}).get('text', 'N/A')} ({flight_data.get('aircraft', {}).get('identification', {}).get('registration', 'N/A')})<br>
<b>从:</b> {origin_name} ({origin_iata})<br>
<b>到:</b> {dest_name} ({dest_iata})
]]>
"""
# --- 3. 构建最终 KML 字符串 ---
kml_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">
<Document>
<name>航班 {flight_id}</name>
<description>{flight_info_html.strip()}</description>
<Style id="flightTrackStyle"><IconStyle><scale>1.5</scale><color>ff00ffff</color><Icon><href>http://maps.google.com/mapfiles/kml/shapes/airports.png</href></Icon></IconStyle><LineStyle><color>ff0000ff</color><width>4.5</width></LineStyle></Style>
<Style id="airportStyle"><IconStyle><scale>1.3</scale><color>ffff7f00</color><Icon><href>http://maps.google.com/mapfiles/kml/paddle/A.png</href></Icon></IconStyle></Style>
<Style id="datapointStyle"><IconStyle><scale>0.5</scale><color>80ffffff</color><Icon><href>http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png</href></Icon></IconStyle><LabelStyle><scale>0</scale></LabelStyle></Style>
<Placemark><name>起点: {origin_name} ({origin_iata})</name><styleUrl>#airportStyle</styleUrl><Point><coordinates>{origin.get('position', {}).get('longitude')},{origin.get('position', {}).get('latitude')},0</coordinates></Point></Placemark>
<Placemark><name>终点: {dest_name} ({dest_iata})</name><styleUrl>#airportStyle</styleUrl><Point><coordinates>{destination.get('position', {}).get('longitude')},{destination.get('position', {}).get('latitude')},0</coordinates></Point></Placemark>
<Folder>
<name>飞行轨迹与数据点</name>
<Placemark><name>飞行轨迹动画</name><styleUrl>#flightTrackStyle</styleUrl><gx:Track><altitudeMode>absolute</altitudeMode>
{track_when_block}
{track_coord_block}
</gx:Track></Placemark>
<Folder><name>详细数据点 (点击飞机图标查看)</name>
{datapoint_block}
</Folder>
</Folder>
</Document>
</kml>
"""
with open(kml_file_path, 'w', encoding='utf-8') as f:
f.write(kml_content)
print(f"✅ KML 文件已成功生成: {kml_file_path}")
except FileNotFoundError:
print(f"错误: 找不到输入文件 {json_file_path}")
except json.JSONDecodeError:
print(f"错误: {json_file_path} 不是一个有效的 JSON 文件。")
except Exception as e:
print(f"发生未知错误: {e}")
# --- 主程序入口:处理命令行参数 ---
if __name__ == "__main__":
# 检查命令行参数数量是否正确
if len(sys.argv) != 3:
print("用法: python make_kml.py <输入文件名.json> <输出文件名>")
print("示例: python make_kml.py flight-playback.json my_flight_output")
sys.exit(1) # 退出脚本
# 从命令行获取参数,并调用主函数执行转换
generate_flight_kml(sys.argv[1], sys.argv[2] + ".kml")python main.py flight-playback.json output输出的数据就可以导入GoogleEarth了。
