0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【maplibre-gl】マーカーをクリックするとマップとマーカーの両方が発火する事象を回避する

0
Last updated at Posted at 2026-02-11

問題

maplibregl.Markerをクリックすると、Mapのclickイベントも発火してしまうため、Markerのクリックイベントだけを発火する方法を調べました。

解決方法

maplibregl.Markerではなく、maplibregl.Mapのclickイベントに追記する必要があります。

const mapInstance = new maplibregl.Map({});

mapInstance.on("click", (event) => {
  if ((event.originalEvent.target as HTMLElement).closest(".maplibregl-marker")) {
        return;
  }
  // マップをクリックした時の処理
}

マーカーをクリックした場合、event.originalEvent.target as HTMLElementはpath要素になります。
このpath要素はmaplibreが自動的に作成したもので、.maplibregl-markerクラスも自動で付与しています。

なので、.maplibregl-markerクラスがあればマーカーと判断し、後続のマップクリック処理を実行させないようにreturnしています。

おわりに

DOMとクラスから判定するという正直すっきりしない書き方です...
他に方法をご存じの方がいらっしゃったら教えてください。

参考

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!
▼▼▼

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?