Using IP Geolocation and HTML Geolocation with MapLibre GL
This code allows you to obtain a user's city-level location through IP geolocation with the Geoapify IP Geolocation API, and displays it on a Maplibre GL map.
by Geoapify
HTML
<script src="https://unpkg.com/[email protected]/dist/maplibre-gl.js"></script>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/maplibre-gl.css">
<div id="map"></div>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
JavaScript
// The API Key provided is restricted to JSFiddle website
// Get your own API Key on https://myprojects.geoapify.com
const myAPIKey = "6dc7fb95a3b246cfa0f3bcef5ce9ed9a";
const map = new maplibregl.Map({
container: 'map',
style: `https://maps.geoapify.com/v1/styles/klokantech-basic/style.json?apiKey=${myAPIKey}`,
});
fetch(`https://api.geoapify.com/v1/ipinfo?apiKey=${myAPIKey}`)
.then(response => response.json())
.then(positionData => {
console.log(`Lat: ${positionData.location.latitude}, lon: ${positionData.location.longitude}`);
// Locate the map to the city level
map.flyTo({center: [positionData.location.longitude, positionData.location.latitude], zoom: 10});
});
// Create the geolocate control.
const geolocate = new maplibregl.GeolocateControl({
positionOptions: {
enableHighAccuracy: true
},
trackUserLocation: false
});
// Add the control to the map
map.addControl(geolocate, 'bottom-right');
// Listen for the geolocate event
geolocate.on('geolocate', function(positionData) {
// get address by coordinates with Geoapify Reverse Geocoding API
console.log(`Lat: ${positionData.coords.latitude}, lon: ${positionData.coords.longitude}`);
getAddress(positionData.coords.latitude, positionData.coords.longitude).then(address => {
console.log(address);
})
});
function getAddress(lat, lon) {
return fetch(`https://api.geoapify.com/v1/geocode/reverse?lat=${lat}&lon=${lon}&format=json&apiKey=${myAPIKey}`).then(result => result.json()).then(result => {
if (result && result.results.length) {
return result.results[0].formatted
}
return null
})
}