アプリからエクスポートされた生のkml/kmzファイルを操作する例。

このページでは、役立つと思われるkmz/kmlファイルの後処理の例を提供します。

準備:

  1. GPS Cameraからエクスポート: ポイントをKMZ/KMLとしてエクスポート
  2. KMLを抽出: 必要に応じてKMZを解凍

imageNotesからKMLプレースマーク名を更新する

このガイドでは、imageNotesフィールドから情報を抽出することにより、KMLファイルのプレースマーク名を自動的に更新する方法を示します。

概要

GPS Cameraからポイントをエクスポートすると、アプリは写真とポイントのタイトルに基づいてプレースマーク名を持つKMLファイルを作成します。ノートの内容(「Note 1」、「Note 2」など)は、タブ区切り値としてimageNotesフィールドに保存されます。このスクリプトを使用すると、そのノート情報を自動的に抽出し、必要に応じてプレースマーク名として使用できます。

写真を撮るときにノートをタイトルフィールドに入れるのが最善です。このスクリプトは、それをしていなかった場合や、kml後処理の例としても役立ちます。

使用例

前:

  • プレースマーク名はタイムスタンプを表示: 15Nov25 16:2512Nov25 17:24
  • 実際のノートはimageNotesフィールドに隠されている: Note 1Note 2

後:

  • プレースマーク名は意味のあるノートを表示: Note 1Note 2
  • マッピングアプリケーションで一目でポイントを簡単に識別

KMLファイル構造

エクスポートされたKMLファイルには、次の構造のプレースマークが含まれています:

<Placemark>
  <name>15Nov25 16:25</name>
  <ExtendedData>
    <SchemaData schemaUrl="#blcPointSchema">
      <SimpleData name="imageNotes"><![CDATA[15Nov25 16:25	Note 1		Ad-hoc	V Třešňovce 227/12...]]></SimpleData>
    </SchemaData>
  </ExtendedData>
  <Point>
    <coordinates>14.502834,50.095184,239.0</coordinates>
  </Point>
</Placemark>

imageNotesフィールドにはタブ区切り値が含まれています:

  • フィールド 0: タイムスタンプ (15Nov25 16:25)
  • フィールド 1: ノートテキスト (Note 1) ← これを抽出します
  • フィールド 2: 空
  • フィールド 3: タイプ (Ad-hoc)
  • フィールド 4: 住所

解決策: Pythonスクリプト

KMLファイルを自動的に処理し、imageNotesの内容に基づいてプレースマーク名を更新するPythonスクリプトを作成しました。

スクリプトの機能

  • 自動抽出: タブ区切りのimageNotesフィールドを解析
  • 位置ベース: 特定のフィールド位置からノートを抽出(デフォルト: 位置1)
  • 汎用: この構造に従う任意のKMLファイルで動作
  • 安全: ファイルを上書きする前にバックアップを作成
  • 柔軟: 新しいファイルに出力するか、その場で更新できます

仕組み

  1. KMLファイルを解析: XML構造を読み取ります
  2. プレースマークを検索: すべての<Placemark>要素を見つけます
  3. ノートを抽出: imageNotesをタブ文字で分割し、位置1のノートを取得します
  4. 名前を更新: <name>要素全体を抽出したノートに置き換えます
  5. 出力を保存: 更新されたKMLをファイルに書き込みます

インストールと使用

前提条件

  • Python 3 (macOSにプリインストール、Windowsの場合は python.org からダウンロード)
  • 追加のライブラリは不要(標準ライブラリのみ使用)

ステップバイステップガイド

1. スクリプトをダウンロード

update_kml_names.pyをダウンロードし、KMLファイルと同じフォルダに配置します。

2. スクリプトを実行

macOS / Linux:

# KMLファイルを含むフォルダに移動
cd ~/Downloads/Points_20251115_163211

# スクリプトを実行(バックアップを作成、元を更新)
python3 update_kml_names.py doc.kml

# または新しい出力ファイルを作成(元を保持)
python3 update_kml_names.py doc.kml updated_points.kml

Windows:

# KMLファイルを含むフォルダに移動
cd %USERPROFILE%\Downloads\Points_20251115_163211

# スクリプトを実行(バックアップを作成、元を更新)
python update_kml_names.py doc.kml

# または新しい出力ファイルを作成(元を保持)
python update_kml_names.py doc.kml updated_points.kml

3. 結果を表示

スクリプトは更新を表示します:

Updated: '15Nov25 16:25' -> 'Note 1'
Updated: '12Nov25 17:24' -> 'Note 2'

Completed! Updated 2 placemark(s).
Output saved to: doc.kml

高度な使用法

カスタムノート位置

imageNotesフィールドが異なる構造で、ノートが異なる位置にある場合は、指定できます:

# 位置2からノートを抽出(3番目のフィールド、0インデックス)
python3 update_kml_names.py doc.kml output.kml 2

バッチ処理

簡単なスクリプトを使用して複数のKMLファイルを処理できます:

macOS / Linux:

for file in *.kml; do
  python3 update_kml_names.py "$file"
done

Windows (PowerShell):

Get-ChildItem -Filter *.kml | ForEach-Object {
  python update_kml_names.py $_.Name
}

例: 前後

処理前

<Placemark>
  <name>15Nov25 16:25</name>
  <SimpleData name="imageNotes">15Nov25 16:25	Note 1		Ad-hoc	Address...</SimpleData>
</Placemark>

<Placemark>
  <name>12Nov25 17:24</name>
  <SimpleData name="imageNotes">12Nov25 17:24	Note 2		Ad-hoc	Address...</SimpleData>
</Placemark>

処理後

<Placemark>
  <name>Note 1</name>
  <SimpleData name="imageNotes">15Nov25 16:25	Note 1		Ad-hoc	Address...</SimpleData>
</Placemark>

<Placemark>
  <name>Note 2</name>
  <SimpleData name="imageNotes">12Nov25 17:24	Note 2		Ad-hoc	Address...</SimpleData>
</Placemark>

技術的詳細

スクリプトの実装

スクリプトはPythonの組み込みXMLパーサー(xml.etree.ElementTree)を使用します:

  • 適切な名前空間処理でKMLファイルを解析
  • XML構造をナビゲートしてプレースマーク要素を見つける
  • タブ区切り値を抽出して処理
  • ファイル構造を保持しながら要素を更新

互換性

  • KMLバージョン: 2.2(標準形式)
  • Pythonバージョン: 3.6+
  • オペレーティングシステム: macOS、Windows、Linux
  • アプリ: Google Earth、QGIS、ArcGIS、およびその他のKML対応アプリケーションと互換性があります

トラブルシューティング

問題: スクリプトが見つかりません

原因: Pythonがインストールされていないか、システムPATHにありません

解決策:

  • macOS: Python 3がプリインストールされているはずです
  • Windows: python.org からダウンロードし、インストール時に「Add to PATH」がチェックされていることを確認してください

問題: 更新後に名前が空

原因: ノートフィールドが空であるか、間違った位置にあります

解決策: スクリプトは警告を表示します。imageNotesフォーマットを確認し、位置パラメータを調整してください。

ワークフローとの統合

このスクリプトは自動化されたワークフローに統合できます:

  1. GPS Cameraからエクスポート: ポイントをKMZ/KMLとしてエクスポート
  2. KMLを抽出: 必要に応じてKMZを解凍
  3. スクリプトを実行: 名前を更新するためにKMLを処理
  4. GISにインポート: Google Earth、QGIS、またはその他のツールで使用

ソースコード

#!/usr/bin/env python3
"""
Script to update KML placemark names with Note from imageNotes field.
Extracts the note from the tab-separated imageNotes field (position 2) and replaces the placemark name.
"""

import xml.etree.ElementTree as ET
import sys
import os

def update_kml_with_notes(input_file, output_file=None, note_position=1):
    """
    Update KML placemark names by extracting Note from tab-separated imageNotes field.

    Args:
        input_file: Path to input KML file
        output_file: Path to output KML file (if None, overwrites input)
        note_position: Position of the note in tab-separated imageNotes (0-indexed, default 1)
    """
    # Parse the KML file
    tree = ET.parse(input_file)
    root = tree.getroot()

    # Define namespace
    ns = {'kml': 'http://www.opengis.net/kml/2.2'}

    # Find all Placemark elements
    placemarks = root.findall('.//kml:Placemark', ns)

    updated_count = 0

    for placemark in placemarks:
        # Get the current name
        name_elem = placemark.find('kml:name', ns)
        if name_elem is None:
            continue

        current_name = name_elem.text

        # Find the imageNotes field
        image_notes_elem = placemark.find('.//kml:SimpleData[@name="imageNotes"]', ns)

        if image_notes_elem is not None and image_notes_elem.text:
            image_notes = image_notes_elem.text

            # Split by tab to get the note (tab-separated format)
            parts = image_notes.split('\t')

            if len(parts) > note_position and parts[note_position].strip():
                note_text = parts[note_position].strip()

                # Update the name - replace entirely with the note
                name_elem.text = note_text

                print(f"Updated: '{current_name}' -> '{note_text}'")
                updated_count += 1
            else:
                print(f"Warning: No note found at position {note_position} in imageNotes for placemark '{current_name}'")
                print(f"  imageNotes content: {image_notes}")
        else:
            print(f"Warning: No imageNotes found for placemark '{current_name}'")

    # Determine output file
    if output_file is None:
        output_file = input_file

    # Write the updated KML
    tree.write(output_file, encoding='utf-8', xml_declaration=True)

    print(f"\nCompleted! Updated {updated_count} placemark(s).")
    print(f"Output saved to: {output_file}")

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python3 update_kml_names.py <input_kml_file> [output_kml_file] [note_position]")
        print("\nArguments:")
        print("  input_kml_file:  Path to the KML file to process")
        print("  output_kml_file: (Optional) Output file path. If not provided, input will be overwritten.")
        print("  note_position:   (Optional) 0-indexed position of note in tab-separated imageNotes (default: 1)")
        print("\nExample:")
        print("  python3 update_kml_names.py doc.kml")
        print("  python3 update_kml_names.py doc.kml doc_updated.kml")
        print("  python3 update_kml_names.py doc.kml doc_updated.kml 1")
        sys.exit(1)

    input_file = sys.argv[1]
    output_file = sys.argv[2] if len(sys.argv) > 2 else None
    note_position = int(sys.argv[3]) if len(sys.argv) > 3 else 1

    if not os.path.exists(input_file):
        print(f"Error: Input file '{input_file}' not found.")
        sys.exit(1)

    # Create backup if overwriting
    if output_file is None:
        backup_file = input_file + '.backup'
        import shutil
        shutil.copy2(input_file, backup_file)
        print(f"Backup created: {backup_file}\n")

    update_kml_with_notes(input_file, output_file, note_position)

サポート

質問や問題について:

  • Python 3が正しくインストールされていることを確認してください
  • imageNotesにタブ区切り値が含まれていることを確認してください

ライセンス

このスクリプトは、アプリのエクスポートで使用するために現状のまま提供されています。特定のニーズに合わせて自由に変更および適応してください。


関連ドキュメント

エクスポートとインポート

Google Earthでの作業

関連ワークフロー


最終更新: 2025年11月