index.html 2.37 KB
Newer Older
JOE XMG's avatar
update  
JOE XMG committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<!DOCTYPE html>
<html>
  <head>
    <title>Leaflet Control Geocoder</title>

    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, user-scalable=no initial-scale=1, maximum-scale=1"
    />

    <link rel="stylesheet" href="https://unpkg.com/leaflet@latest/dist/leaflet.css" />
    <link rel="stylesheet" href="../dist/Control.Geocoder.css" />

    <script src="https://unpkg.com/leaflet@latest/dist/leaflet-src.js"></script>
    <script src="../dist/Control.Geocoder.js"></script>
    <style type="text/css">
      body {
        margin: 0;
      }
      #map {
        position: absolute;
        width: 100%;
        height: 100%;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>

    <script type="text/javascript">
      var map = L.map('map').setView([0, 0], 2);

      var geocoder = L.Control.Geocoder.nominatim();
      if (typeof URLSearchParams !== 'undefined' && location.search) {
        // parse /?geocoder=nominatim from URL
        var params = new URLSearchParams(location.search);
        var geocoderString = params.get('geocoder');
        if (geocoderString && L.Control.Geocoder[geocoderString]) {
          console.log('Using geocoder', geocoderString);
          geocoder = L.Control.Geocoder[geocoderString]();
        } else if (geocoderString) {
          console.warn('Unsupported geocoder', geocoderString);
        }
      }

      var control = L.Control.geocoder({
        query: 'Moon',
        placeholder: 'Search here...',
        geocoder: geocoder
      }).addTo(map);
      var marker;

      setTimeout(function() {
        control.setQuery('Earth');
      }, 12000);

      L.tileLayer('https://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors'
      }).addTo(map);

      map.on('click', function(e) {
        geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom()), function(results) {
          var r = results[0];
          if (r) {
            if (marker) {
              marker
                .setLatLng(r.center)
                .setPopupContent(r.html || r.name)
                .openPopup();
            } else {
              marker = L.marker(r.center)
                .bindPopup(r.name)
                .addTo(map)
                .openPopup();
            }
          }
        });
      });
    </script>
  </body>
</html>