Leafletの使い方ノート

Leafletとは、Web上で簡単に地図表示ができるJavaScriptライブラリです。
利用する過程で学んだ内容を再確認できるよう整理しました(内容は入門レベルです)。
地図は国土地理院タイルを利用します。
公式サイトへのリンク
Leaflet
国土地理院(タイル一覧)

下の灰色のボタンで表示を絞り込むことができます。

    基本設定(Leaflet & 国土地理院地図)

    HTMLのheadタグ内
                                        
                                            <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"
                                                integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI="
                                                crossorigin=""/>
                                            <script src="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"
                                                integrity="sha256-WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM="
                                                crossorigin=""></script>
    
                                            <script>
                                                const map_sample = L.map('map_sample')
                                                L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
                                                    attribution: "<a href='https://maps.gsi.go.jp/development/ichiran.html'
                                                    target='_blank'>地理院タイル</a>"
                                                }).addTo(map_sample);
                                                map_sample.setView([35.5, 138.5], 5); // ([緯度, 経度], 地図のZoom倍率)
                                            </script>
                                        
                                    
    HTMLのbodyタグ内(地図の配置)

    <div id="map_sample"></div>

    CSSファイル例

    #map_sample {
      height: 500px;
    }

    マーカー・ポップアップ

    マーカーの追加(jsファイル)

    const marker = L.marker([32.5, 131.1]).addTo(map_sample);

    円の追加(jsファイル)
                                        
                                            const circle = L.circle([32.5, 131.1], {
                                                color: '#008000',
                                                fillColor: '#3cb371',
                                                fillOpacity: 0.5,
                                                radius: 30000 # 30kmの半径
                                            }).addTo(map_sample);
                                        
                                    
    ポップアップ(jsファイル)
                                        
                                            const popup = L.popup()
                                                .setLatLng([51.513, -0.09])
                                                .setContent("I am a standalone popup.")
                                                .openOn(map_sample);
                                        
                                    
    クリックでポップアップ(jsファイル)
                                        
                                            const popup = L.popup();
                                            function onMapClick(e) {
                                                popup
                                                .setLatLng(e.latlng)
                                                .setContent("クリックした場所 " + e.latlng.toString())
                                                .openOn(map_sample);
                                            }
                                            map_sample.on('click', onMapClick);
                                        
                                    
    アイコン(jsファイル)
                                        
                                            const greenIcon = L.icon({
                                            iconUrl: 'leaf-green.png',
                                            shadowUrl: 'leaf-shadow.png',
                                            iconSize: [38, 95],
                                            shadowSize: [50, 64],
                                            // マーカーの位置に対応するアイコンのポイント(0,0でマーカー左上の端)
                                            iconAnchor: [22, 94],
                                            shadowAnchor: [4, 62],
                                            // ポップアップを表示する位置(iconAnchor基準)
                                            p;popupAnchor: [-3, -76]
                                            });
                                            L.marker([51.5, -0.09], {icon: greenIcon}).bindPopup('ポップアップ').addTo(map_sample);
                                        
                                    
    レイヤー(jsファイル)
                                        
                                            // 地図上に表示するグループ
                                            const group1 = L.layerGroup();
                                            const group2 = L.layerGroup();
    
                                            // 独自のアイコンを設定
                                            const groupIcon = L.icon({
                                                iconUrl: "画像ファイルの場所URL",
                                                iconSize: [40, 40],
                                                iconAnchor: [25, 25],
                                                popupAnchor: [0, -10]
                                            });
    
                                            // マーカーをグループ1とグループ2に分けて登録
                                            // グループ1には独自のアイコンを設定
                                            L.marker([35, 135], { icon: groupIcon}).bindPopup('This is member1.').addTo(group1);
                                            L.marker([35, 135.1], { icon: groupIcon}).bindPopup('This is member2.').addTo(group1);
                                            L.marker([35, 135.2]).bindPopup('This is member3.').addTo(group2);
                                            L.marker([35, 135.3]).bindPopup('This is member4.').addTo(group2);
    
                                            // 下地の地図の設定(例は国土地理院の標準地図)
                                            const map1 = L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/std/{z}/{x}/{y}.png', {
                                                maxZoom: 18,
                                                attribution: "&copy; <a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>"
                                            });
    
                                            // 下地の地図(2つ目)の設定(例は国土地理院の淡色地図)
                                            const map2 = L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png', {
                                                maxZoom: 18,
                                                attribution: "&copy; <a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>"
                                            });
    
                                            // デフォルトで表示する下地の地図と重ねて表示するグループの設定
                                            const map_sample = L.map('map_sample', {
                                                center: [35, 135],
                                                zoom: 9,
                                                layers: [map1, group1]
                                            });
    
                                            // 下地に使う地図を格納するオブジェクト(ラジオボタンで切替)
                                            const baseLayers = {
                                                'Map1': map1,
                                                'Map2': map2,
                                            };
    
                                            // 地図に重ねて表示するグループを格納するオブジェクト(チェックボックスで選択)
                                            const overlays = {
                                                'Group1': group1,
                                                'Group2': group2,
                                            };
    
                                            // レイヤーコントロールを作成し、マップに追加
                                            const layerControl = L.control.layers(baseLayers, overlays).addTo(map_sample);
    
                                            // グループを追加(必要に応じて)
                                            const group3 = L.layerGroup();
                                            const test1 = L.marker([32.5, 131.5]).bindPopup('テスト1').addTo(group3);
                                            const test2 = L.marker([32.6, 131.6]).bindPopup('テスト2').addTo(group3);
                                            layerControl.addOverlay(group3, 'グループ3');
                                        
                                    
    表示サンプル

    中心の緯度経度を取得

    Javasciptの記述
                                        
                                            <script>
                                                $(function () {
                                                    const map_sample = L.map('map_sample')
                                                    L.tileLayer('https://cyberjapandata.gsi.go.jp/xyz/pale/{z}/{x}/{y}.png', {
                                                        maxZoom: 18,
                                                        minZoom: 2,
                                                        attribution: "<a href='https://maps.gsi.go.jp/development/ichiran.html' target='_blank'>地理院タイル</a>",
                                                    }).addTo(map_sample);
                                                    // 初期表示([緯度, 経度], ズーム倍率)、表示する地図の範囲を限定([[緯度, 経度], [緯度, 経度]])
                                                    map_sample.setView([35, 135], 6).setMaxBounds([[0, 0], [90, 180]]);
    
                                                    // マーカー(照準)を地図中央に表示
                                                    const crossIcon = L.icon({
                                                        // 地図中央に表示するマーカーの画像
                                                        iconUrl: 'https://サイト名など/markar.png',
                                                        iconSize: [32, 32],
                                                        iconAnchor: [16, 16]
                                                    });
    
                                                    const crossMarker = L.marker(map_sample.getCenter(),{
                                                        icon:crossIcon,
                                                        zIndexOffset:100,
                                                        interactive:false
                                                    }).addTo(map_sample);
    
                                                    map_sample.on('move', function(e) {
                                                        // 照準の表示
                                                        const center = map_sample.getCenter();
                                                        crossMarker.setLatLng(center);
                                                        // 緯度経度の取得(小数点以下1位まで)
                                                        const lat = Math.round(center.lat * 10) / 10;
                                                        const lng = Math.round(center.lng * 10) / 10;
                                                        // 地図を操作した後の値を渡す
                                                        document.getElementById('latitude').value = lat
                                                        document.getElementById('longitude').value = lng
                                                        // 地図を操作した後の文字列を渡す
                                                        document.getElementById("text").textContent = "緯度:" + lat + "経度:" + lng;
                                                    });
                                                });
                                            </script>