みつきんのメモ

組み込みエンジニアです。Interface誌で「Yocto Projectではじめる 組み込みLinux開発入門」連載中

LeafletでGeocoding

簡単に住所検索

Control.Geocoder.jsを使用すると、簡単に住所検索機能が追加できる。

これはどうやらLeafletの開発者本人が作ってるものっぽい。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Leaflet Geocoder Test</title>

    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.4/dist/leaflet.css" />
    <script src="https://unpkg.com/leaflet@1.3.4/dist/leaflet.js"></script>

    <link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
    <script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>

<body>
<div id="map" style="width: 700px; height: 400px"></div>
<script>
    let map = L.map('map').setView([35.731059, 139.739748], 18);
    $(function () {
        L.tileLayer(
            'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
            {
                attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a>',
                maxZoom: 18
            }
        ).addTo(map);
        let options = {
            geocoder: new L.Control.Geocoder.Nominatim()
        };
        L.Control.geocoder(options).addTo(map);
    });
</script>

</body>
</html>

これスゴいのがoptionsに渡すgeocoderを切り替えることで、10種類くらいのGeocoderを簡単に使用することができる。 中には、というか大半は予めAPI Keyを取得しておく必要があるが。。。

簡単に住所検索機能が追加できるのはスゴい。。。