MapLibre with Geoapify Autocomplete and Reverse Geocoding on Map Click
by Geoapify
HTML
<!-- MapLibre GL CSS -->
<link
href="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.css"
rel="stylesheet"
/>
<!-- Geoapify Geocoder Autocomplete CSS -->
<link link rel="stylesheet" type="text/css" href="https://unpkg.com/@geoapify/geocoder-autocomplete@latest/styles/round-borders.css"/>
<!-- MapLibre GL JS -->
<script src="https://unpkg.com/maplibre-gl@latest/dist/maplibre-gl.js"></script>
<!-- Geoapify Geocoder Autocomplete JS -->
<script src="https://unpkg.com/@geoapify/[email protected]/dist/index.min.js"></script>
<!-- Map container -->
<div id="map"></div>
<!-- Autocomplete container -->
<div class="autocomplete-panel"><div id="autocomplete" class="autocomplete-container"></div></div>
CSS
html,
body {
margin: 0;
height: 100%;
width: 100%;
}
/* Style for the Map */
#map {
height: 100%; /* Set the map container height */
width: 100%; /* Set the map container width */
}
.autocomplete-panel {
position: absolute;
top: 10px;
left: 10px;
width: 400px;
z-index: 1000;
}
.autocomplete-container {
position: relative;
}
JavaScript
// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";
// The MapLibre GL map object
const map = new maplibregl.Map({
container: "map", // ID of the container element
style: `https://maps.geoapify.com/v1/styles/osm-bright-grey/style.json?apiKey=${myAPIKey}`,
center: [-77.02346458179596, 38.908838755401035], // Initial center [longitude, latitude]
zoom: 12, // Initial zoom level
maxZoom: 20, // Max zoom level
});
// Add zoom and rotation controls to bottom-right corner
map.addControl(new maplibregl.NavigationControl({ position: "bottom-right" }));
// check the available autocomplete options on the https://www.npmjs.com/package/@geoapify/geocoder-autocomplete
const autocompleteInput = new autocomplete.GeocoderAutocomplete(
document.getElementById("autocomplete"),
myAPIKey,
{
/* Geocoder options */
},
);
// Generate a marker icon with https://apidocs.geoapify.com/playground/icon
const markerIcon = new maplibregl.Marker({
element: createMarkerIcon(),
anchor: "bottom",
});
function createMarkerIcon() {
const img = document.createElement("img");
img.src = `https://api.geoapify.com/v2/icon/?type=awesome&color=%23ff5b5f&size=50&scaleFactor=2&apiKey=${myAPIKey}`;
img.style.width = "38px";
img.style.height = "55px";
return img;
}
let marker;
autocompleteInput.on("select", (location) => {
// Add marker with the selected location
if (marker) {
marker.remove();
}
if (location) {
marker = new maplibregl.Marker({ element: createMarkerIcon(), offset: [0, -25 /* -(icon height - icon shadow offset) / 2 */]})
.setLngLat([location.properties.lon, location.properties.lat])
.addTo(map);
map.flyTo({
center: [location.properties.lon, location.properties.lat],
zoom: 14,
});
}
});
// Add click event listener to the...