Google Map Geojson to OsmAnd map gpx

Apr 3, 2025 at 11:53:54

紀錄今天使用的轉換程式
把Google Map的儲存地點匯出後,就可以轉換成gpx並用在其他OSM相關的app上
以前Maps.me可以匯入這些檔案,現在沒找到匯入的地方
先轉用OsmAnd map,之後再研究看看

import json
import xml.etree.ElementTree as ET
from datetime import datetime

def geojson_to_gpx(geojson_file, gpx_file):
    try:
        # 載入 GeoJSON 檔案
        with open(geojson_file, 'r', encoding='utf-8') as f:
            geojson_data = json.load(f)

        # 創建 GPX 根元素,並添加命名空間
        gpx = ET.Element('gpx', {
            'version': '1.1',
            'creator': 'Google Maps to GPX Converter',
            'xmlns': 'http://www.topografix.com/GPX/1/1',
            'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
            'xsi:schemaLocation': 'http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd'
        })

        # 遍歷 GeoJSON 中的特徵
        for feature in geojson_data.get('features', []):
            # 獲取幾何資訊
            if feature['geometry']['type'] == 'Point':
                lon, lat = feature['geometry']['coordinates']

                # 驗證坐標是否有效
                if not (isinstance(lon, (int, float)) and isinstance(lat, (int, float))):
                    print(f"警告:無效的坐標 {lon}, {lat},跳過此點。")
                    continue

                # 獲取名稱,從 properties.location.name 中提取
                name = feature['properties'].get('location', {}).get('name', '未命名地點')

                # 創建 GPX 的 Waypoint 元素
                wpt = ET.SubElement(gpx, 'wpt')
                wpt.set('lat', str(lat))
                wpt.set('lon', str(lon))

                # 添加名稱
                name_elem = ET.SubElement(wpt, 'name')
                name_elem.text = name

                # 可選:添加描述(如地址)
                address = feature['properties'].get('location', {}).get('address', '')
                if address:
                    desc_elem = ET.SubElement(wpt, 'desc')
                    desc_elem.text = address

                # 添加時間(使用 GeoJSON 中的日期或當前時間)
                date = feature['properties'].get('date', datetime.now().isoformat() + 'Z')
                time_elem = ET.SubElement(wpt, 'time')
                time_elem.text = date

        # 保存 GPX 檔案,格式化輸出以便閱讀
        tree = ET.ElementTree(gpx)
        with open(gpx_file, 'wb') as f:
            f.write(b'<?xml version="1.0" encoding="UTF-8"?>\n')
            tree.write(f, encoding='utf-8', xml_declaration=False)

        print(f"GPX 檔案已成功保存至 {gpx_file}")

    except FileNotFoundError:
        print(f"錯誤:找不到檔案 {geojson_file}")
    except json.JSONDecodeError:
        print(f"錯誤:{geojson_file} 不是有效的 JSON 檔案")
    except Exception as e:
        print(f"發生錯誤:{str(e)}")

# 使用示例
if __name__ == "__main__":
    geojson_file = 'GoogleMap.json'
    gpx_file = 'OsmAnd.gpx'
    geojson_to_gpx(geojson_file, gpx_file)
Tags: