UNPKG

leaflet-control-geocoder

Version:

Extendable geocoder with builtin support for OpenStreetMap Nominatim, Bing, Google, Mapbox, MapQuest, What3Words, Photon, Pelias, HERE, Neutrino, Plus codes

79 lines (69 loc) 2.25 kB
<!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> body { margin: 0; } #map { position: absolute; width: 100%; height: 100%; } </style> </head> <body> <div id="map"></div> <script> const map = new L.Map('map').setView([0, 0], 2); let geocoder = L.Control.Geocoder.nominatim(); // parse /?geocoder=nominatim from URL let params = new URL(document.location.toString()).searchParams; const 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); } const control = L.Control.geocoder({ query: 'Moon', placeholder: 'Search here...', geocoder }).addTo(map); setTimeout(() => { control.setQuery('Earth'); }, 12000); new L.TileLayer('https://tile.osm.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); let marker; map.on('click', e => { geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom())).then(results => { const r = results[0]; if (!r) { return; } if (marker) { marker .setLatLng(r.center) .setPopupContent(r.html || r.name) .openPopup(); } else { marker = new L.Marker(r.center).bindPopup(r.name).addTo(map).openPopup(); } }); }); </script> </body> </html>