dayjournal memo

Total 975 articles!!

Mapbox GL JS #048 – ツールチップ表示

Yasunori Kirimoto's avatar


画像



ツールチップを表示するメモ。



画像



script.js

// MIERUNE Streets読み込み
const map = new mapboxgl.Map({
  container: "map",
  style:
    "https://api.maptiler.com/maps/jp-mierune-streets/style.json?key=[APIキー]",
  center: [139.767, 35.681],
  zoom: 14,
});

// コントロール関係表示
map.addControl(new mapboxgl.NavigationControl());

map.on('load', function () {
    // サークル設定
    map.addSource('point_sample', {
        type: 'geojson',
        data: '/vector/sample.geojson',
    });

    // スタイル設定
    map.addLayer({
        id: 'point_sample',
        type: 'circle',
        source: 'point_sample',
        layout: {},
        paint: {
            'circle-color': '#FF0000',
            'circle-radius': 10,
        },
    });

    // ポップアップ設定
    const popup = new mapboxgl.Popup({
        closeButton: false,
        closeOnClick: false,
    });

    // ツールチップ表示
    map.on('mouseenter', 'point_sample', function (e) {
        map.getCanvas().style.cursor = 'pointer';
        // 経緯度取得
        const coordinates = e.lngLat;
        // 属性設定
        const description =
            'field01: ' +
            e.features[0].properties.field01 +
            '<br>' +
            'field02: ' +
            e.features[0].properties.field02 +
            '<br>' +
            'field03: ' +
            e.features[0].properties.field03;
        while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
            coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
        }
        popup.setLngLat(coordinates).setHTML(description).addTo(map);
    });

    // ツールチップ非表示
    map.on('mouseleave', 'point_sample', function () {
        map.getCanvas().style.cursor = '';
        popup.remove();
    });
});



Mapbox GL JS を手軽に始めるビルド環境公開しています。
mapboxgljs-starter



book

Q&A