LoginSignup
3
1

More than 5 years have passed since last update.

【BingMaps】Infoboxへ埋め込んだDOMにイベントを設定する方法

Posted at

BingMapsのWebAPIを使ったとき、infobox内に差し込んだDOMにおいて、イベントが発生しませんでした。その解決策をご紹介します。

 ※公式で用意されているinfobox(アクション付)
スクリーンショット 2018-12-22 21.56.45.png
引用:BingMaps GO!|Infobox:Pushpin/event

動的に差し込んだDOMはイベントに反応しない!

どうしてもwebアイコンをinfoboxに入れたくて、下図のようにDOMを差し込みました。
スクリーンショット 2018-12-22 22.02.00.png

map.js
  mapPushpin(lat, lon, id, color, t, d) {
    const location = new Microsoft.Maps.Location(lat, lon);

    let infobox = this.mapInfobox(lat, lon);
    let pin = new Microsoft.Maps.Pushpin(location, {
      color: color
    });

    pin.metadata = {
      title: "店名",
      description: '<i class="fas fa-camera-retro"></i>'
    };

    Microsoft.Maps.Events.addHandler(pin, "click", e => {
      if (e.target.metadata) {
        infobox.setOptions({
          location: e.target.getLocation(),
          title: e.target.metadata.title,
          description: e.target.metadata.description,
          visible: true
        });

      }
    });

    this.map.entities.push(pin);
  }

 qiita_map.gif

そしてクリックイベントを設定しようと思ったら問題が…。全く反応しないんです。documentをクリックしても無反応…。困ったので、色々調べてみました。

map.js
$(document).on("click", el => {
  console.log(el.target);
});

BingMapsにはイベントクラスがある

公式ページで、Microsoft.Maps.Eventsを使うと、イベントを設定できることが判明。

Events can be added and removed by using the methods available through the Microsoft.Maps.Events class. The Events class has the following static methods available.

 引用:公式サイト:Events Class

ただ、イベント対象になるtargetの型はobject形式なので、DOMはダメっぽい…。

onchangeやonclickなどの属性を入れよう!

なので、DOMにonchangeやonclickを入れて解決しました。自分でクリックイベント後の処理を関数化すれば、バッチリ機能します!

参考になれば幸いです!

map.js
    pin.metadata = {
      title: "店名",
      description: '<i class="fas fa-camera-retro" onClick='console.log("hello")'></i>'
    };

qiita_map2.gif

参考URL

3
1
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
3
1