4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Bootstrap Tooltip を地図のマーカー ラベルにしてみる

Last updated at Posted at 2016-08-26

Bootstrap Tooltip はよくご存知だと思います。これね。

スクリーンショット 2016-08-26 20.07.40.png

これを Leaflet.js のマーカーのラベル表示に応用します。
Leafle.js のプラグインにはラベル表示のためのライブラリがいくつかありますが、もし Bootstrap を併用することが前提であれば、この方法を使えばわざわざプラグインを採用せずにラベル表示を実現できますよ。

スクリーンショット 2016-08-26 20.10.27.png

Bootstrap Tooltip

Bootstrap Tooltip は DOM に必要な属性を与えてあげて、JS で初期化するだけです。
下のコードは Bootstrap ページに載ってるスニペットそのままです。

<button type="button" class="btn btn-default" data-toggle="tooltip" data-placement="top" title="Tooltip on top">Tooltip on top</button>
$(function () {
  $('[data-toggle="tooltip"]').tooltip()
})

Leaflet マーカーへの適用

Leaflet.js のマーカーももちろん DOM を持ってますから、同じ要領でやればマーカーに tooltip を適用できます。
下のコードは GeoJSON で読み込んだ複数マーカーに対して tooltip を適用する場合の実装例です。
簡単で便利なので、ぜひやってみてください。

var geojson = L.geoJson(data).addTo(map);
// GeoJSON の各マーカーをループ処理で参照
geojson.eachLayer(function (layer) {
  // マーカーの DOM 要素
  var markerElm = $(layer._icon);
  // Bootstrap tooltip 適用のための属性を追加
  markerElm.attr({
    'data-toggle': 'tooltip',
    'data-placement': 'top'
  });
  // マーカー要素の tooltip 初期化と属性データを表示テキストに指定
  markerElm.tooltip({ title: layer.feature.properties['場所名'], container: 'body' });
});

実際に動くデモとコードはこちらにあるので併せてご覧ください。
今回の実装は No.22 の Bootstrap Tooltip です。

4
5
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
4
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?