首页 > 解决方案 > 如何将谷歌地图 GeoJSON 转换为 GPX,保留位置名称

问题描述

我已经通过外卖工具导出了我的 google-maps Point Of Interests(保存的地点/位置)。如何将其转换为 GPX,以便将其导入 OSMANd?

我尝试使用 gpsbabel:

gpsbabel -i geojson -f my-saved-locations.json -o gpx -F my-saved-locations_converted.gpx

但这并没有保留每个兴趣点的标题/名称 - 而只是使用 WPT001、WPT002 等名称。

标签: pythongoogle-mapsgpsgeojsongpx

解决方案


最后,我通过创建一个小的 python 脚本在格式之间进行转换来解决这个问题。这可以很容易地适应特定需求:

#!/usr/bin/env python3

import argparse
import json
import xml.etree.ElementTree as ET
from xml.dom import minidom


def ingestJson(geoJsonFilepath):
    poiList = []
    with open(geoJsonFilepath) as fileObj:
        data = json.load(fileObj)
        for f in data["features"]:
            poiList.append({'title': f["properties"]["Title"],
                            'lon': f["geometry"]["coordinates"][0],
                            'lat': f["geometry"]["coordinates"][1],
                            'link': f["properties"].get("Google Maps URL", ''),
                            'address': f["properties"]["Location"].get("Address", '')})
    return poiList


def dumpGpx(gpxFilePath, poiList):
    gpx = ET.Element("gpx", version="1.1", creator="", xmlns="http://www.topografix.com/GPX/1/1")
    for poi in poiList:
        wpt = ET.SubElement(gpx, "wpt", lat=str(poi["lat"]), lon=str(poi["lon"]))
        ET.SubElement(wpt, "name").text = poi["title"]
        ET.SubElement(wpt, "desc").text = poi["address"]
        ET.SubElement(wpt, "link").text = poi["link"]
    xmlstr = minidom.parseString(ET.tostring(gpx)).toprettyxml(encoding="utf-8", indent="  ")
    with open(gpxFilePath, "wb") as f:
        f.write(xmlstr)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--inputGeoJsonFilepath', required=True)
    parser.add_argument('--outputGpxFilepath', required=True)
    args = parser.parse_args()

    poiList = ingestJson(args.inputGeoJsonFilepath)
    dumpGpx(args.outputGpxFilepath, poiList=poiList)


if __name__ == "__main__":
    main()

...

它可以这样调用:

./convert-googlemaps-geojson-to-gpx.py \
  --inputGeoJsonFilepath my-saved-locations.json \
  --outputGpxFilepath my-saved-locations_converted.gpx

推荐阅读