|
| 1 | +<!doctype html> |
| 2 | +<html> |
| 3 | + <head> |
| 4 | + <title>Leaflet Control Geocoder</title> |
| 5 | + |
| 6 | + <meta charset="utf-8" /> |
| 7 | + <meta |
| 8 | + name="viewport" |
| 9 | + content="width=device-width, user-scalable=no initial-scale=1, maximum-scale=1" |
| 10 | + /> |
| 11 | + |
| 12 | + <link rel="stylesheet" href="node_modules/leaflet/dist/leaflet.css" /> |
| 13 | + <link rel="stylesheet" href="src/style.css" /> |
| 14 | + |
| 15 | + <style> |
| 16 | + body { |
| 17 | + margin: 0; |
| 18 | + } |
| 19 | + #map { |
| 20 | + position: absolute; |
| 21 | + width: 100%; |
| 22 | + height: 100%; |
| 23 | + } |
| 24 | + </style> |
| 25 | + </head> |
| 26 | + <body> |
| 27 | + <div id="map"></div> |
| 28 | + |
| 29 | + <script type="module"> |
| 30 | + import * as L from 'leaflet'; |
| 31 | + import { Geocoder } from './src/index.ts'; |
| 32 | + const map = new L.Map('map').setView([0, 0], 2); |
| 33 | + |
| 34 | + let geocoder = Geocoder.nominatim(); |
| 35 | + // parse /?geocoder=nominatim from URL |
| 36 | + let params = new URL(document.location.toString()).searchParams; |
| 37 | + const geocoderString = params.get('geocoder'); |
| 38 | + if (geocoderString && Geocoder[geocoderString]) { |
| 39 | + console.log('Using geocoder', geocoderString); |
| 40 | + geocoder = Geocoder[geocoderString](); |
| 41 | + } else if (geocoderString) { |
| 42 | + console.warn('Unsupported geocoder', geocoderString); |
| 43 | + } |
| 44 | + |
| 45 | + const control = new Geocoder({ |
| 46 | + query: 'Moon', |
| 47 | + placeholder: 'Search here...', |
| 48 | + geocoder |
| 49 | + }).addTo(map); |
| 50 | + |
| 51 | + setTimeout(() => { |
| 52 | + control.setQuery('Earth'); |
| 53 | + }, 12000); |
| 54 | + |
| 55 | + new L.TileLayer('https://tile.osm.org/{z}/{x}/{y}.png', { |
| 56 | + attribution: '© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' |
| 57 | + }).addTo(map); |
| 58 | + |
| 59 | + let marker; |
| 60 | + map.on('click', e => { |
| 61 | + geocoder.reverse(e.latlng, map.options.crs.scale(map.getZoom())).then(results => { |
| 62 | + const r = results[0]; |
| 63 | + if (!r) { |
| 64 | + return; |
| 65 | + } |
| 66 | + if (marker) { |
| 67 | + marker |
| 68 | + .setLatLng(r.center) |
| 69 | + .setPopupContent(r.html || r.name) |
| 70 | + .openPopup(); |
| 71 | + } else { |
| 72 | + marker = new L.Marker(r.center).bindPopup(r.name).addTo(map).openPopup(); |
| 73 | + } |
| 74 | + }); |
| 75 | + }); |
| 76 | + </script> |
| 77 | + </body> |
| 78 | +</html> |
0 commit comments