Geocoding example using the Leaflet Control Geocoder.
<html>
<head>
<meta charset="UTF-8" />
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.css" />
<style>
body { width: 100%; height: 100%; padding: 0; margin: 0; }
#map { width: 100%; height: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
<script src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<script>
// Initialize Leaflet map
let map = L.map("map").setView([47.26816, 11.40037], 13);
// Add Maptoolkit tiles as L.tileLayer
L.tileLayer("https://maptoolkit.p.rapidapi.com/tiles/{z}/{x}/{y}/terrain.png?rapidapi-key=your-api-key{ratio}", {
ratio: L.Browser.retina ? "&ratio=2" : "",
maxZoom: 18,
attribution:
"© <a href='https://www.maptoolkit.com' target='_blank'>Maptoolkit</a> \
© <a href='https://www.openstreetmap.org/copyright' target='_blank'>OSM</a>",
}).addTo(map);
// Add geocoder control
L.Control.geocoder({
geocoder: {
geocode: (query, callback, context) => {
fetch(`https://maptoolkit.p.rapidapi.com/geocode/search?q=${query}&language=en&rapidapi-key=your-api-key`).then((r) => r.json()).then((result) => {
callback.call(context, result.map((e) => ({
bbox: [[e.boundingbox[0], e.boundingbox[2]], [e.boundingbox[1], e.boundingbox[3]]],
center: [e.lat, e.lon],
name: e.display_name,
})));
});
},
suggest: function(query, callback, context) {
return this.geocode(query, callback, context);
},
}
}).addTo(map);
</script>
</body>
</html>