qgisからKML出力すると、ラベル、場所の属性が表示されない問題の対処法

Google EarthでQGISから出力したKMLやKMZを表示すると、ポイントの「名前」や「属性(ラベル)」が表示されないことがあります。
これは、KML出力時にラベル設定やスタイル情報が適切に埋め込まれていないためです。

✅ Step1:QGISでラベルにするフィールド名を name に変更

QGISで出力する前に、属性テーブルの中でラベルに使いたいフィールド名を Name にしておきます。
(大文字・小文字は区別されます)

✅ Step2:Pythonスクリプトでラベルスタイルを自動付与

以下のPythonスクリプトを実行すると、指定フォルダ内のすべてのKML/KMZファイルにラベルとスタイル情報を追加し、_styled フォルダに保存します。

#!/usr/bin/env python3
"""
KML/KMZフォルダ内一括処理スクリプト
-----------------------------------
- 指定フォルダ内の .kml / .kmz ファイルを対象
- 各 Placemark に name タグから styleUrl を追加し、Google Earthでラベルを常時表示
- KMZは一時的に展開して処理、再度KMZ化
- 出力は "_styled" フォルダに保存されます

依存:
    pip install lxml
"""

import os
import zipfile
import shutil
from pathlib import Path
from lxml import etree
from tkinter import Tk, filedialog

# ラベルとアイコンを設定するKMLスタイル
STYLE_BLOCK = """
<Style id="labelStyle">
  <LabelStyle>
    <scale>1.4</scale>
    <color>ff0000ff</color> <!-- 赤色ラベル(BGR + alpha) -->
  </LabelStyle>
  <IconStyle>
    <Icon>
      <href>http://maps.google.com/mapfiles/kml/paddle/red-circle.png</href>
    </Icon>
  </IconStyle>
</Style>
"""

def add_style_to_kml(kml_path, output_path):
    parser = etree.XMLParser(remove_blank_text=True)
    tree = etree.parse(str(kml_path), parser)
    root = tree.getroot()
    nsmap = root.nsmap
    if None in nsmap:
        nsmap['kml'] = nsmap.pop(None)
    doc = root.find('.//kml:Document', namespaces=nsmap)
    if doc is None:
        print(f"[!] <Document> タグが見つかりません: {kml_path}")
        return
    try:
        style_elem = etree.fromstring(STYLE_BLOCK)
        doc.insert(0, style_elem)
    except Exception as e:
        print(f"[!] スタイル追加失敗: {e}")
        return
    for placemark in doc.findall('.//kml:Placemark', namespaces=nsmap):
        style = placemark.find('kml:styleUrl', namespaces=nsmap)
        if style is None:
            new_style = etree.Element('{http://www.opengis.net/kml/2.2}styleUrl')
            new_style.text = '#labelStyle'
            placemark.insert(1, new_style)
    tree.write(str(output_path), pretty_print=True, xml_declaration=True, encoding='utf-8')

def process_folder(folder_path):
    folder = Path(folder_path)
    out_folder = folder / "_styled"
    out_folder.mkdir(exist_ok=True)
    for file in folder.glob("*"):
        if file.suffix.lower() == '.kml':
            out_file = out_folder / file.name
            add_style_to_kml(file, out_file)
            print(f"[KML] 処理完了: {file.name}")
        elif file.suffix.lower() == '.kmz':
            with zipfile.ZipFile(file, 'r') as zip_ref:
                temp_dir = folder / "_temp_kmz"
                temp_dir.mkdir(exist_ok=True)
                zip_ref.extractall(temp_dir)
            kml_files = list(temp_dir.glob("*.kml"))
            if kml_files:
                out_kml = temp_dir / kml_files[0].name
                add_style_to_kml(kml_files[0], out_kml)
                kmz_out = out_folder / file.name
                with zipfile.ZipFile(kmz_out, 'w', zipfile.ZIP_DEFLATED) as zip_out:
                    for f in temp_dir.glob("*"):
                        zip_out.write(f, arcname=f.name)
            shutil.rmtree(temp_dir, ignore_errors=True)
            print(f"[KMZ] 処理完了: {file.name}")

if __name__ == '__main__':
    print("📂 処理対象フォルダを選択してください")
    root = Tk()
    root.withdraw()
    folder_selected = filedialog.askdirectory(title="KML/KMZフォルダを選択してください")
    if folder_selected:
        process_folder(folder_selected)
        print("✅ 完了しました(_styled フォルダに出力)")

📌 おまけ:スクリプトの実行手順

  1. Python 3.x をインストール
  2. 必要なライブラリをインストール:
    pip install lxml
  3. 上記スクリプトを保存(例:add_label_style.py
  4. コマンドラインで実行:
    python add_label_style.py

これでGoogle Earth上にラベルが常時表示されるようになります。

コメント

このブログの人気の投稿

位置情報付き写真をGoogle Earthに表示する方法

ワールドファイル付きラスタ(Raster image with world file)からKMZ作成