In this blog post, we demonstrate how to retrieve the current location from the browser, then use the longitude and latitude coordinates to determine the exact location. We’ll use a free API from Maps.co to perform reverse geocoding, which converts coordinates into a human-readable
Steps to Implement:
Get Current Location: We access the user’s current location, which the browser provides (with user permission). This will give us the latitude and longitude values.
Reverse Geocode API: With these coordinates, we make an API call to Maps.co’s Reverse Geocoding API to get the full address. You can get an API key for free by signing up on their platform.
API Endpoint: The endpoint for reverse geocoding is:
https://geocode.maps.co/reverse?lat=latitude&lon=longitude&api_key=YOUR_API_KEY
Replace latitude and longitude with the actual values, and YOUR_API_KEY with your personal API key.
`const api_key = "you key";
const currentLocation = () => {
navigator.geolocation.getCurrentPosition((position) => {
fetchLocation(position.coords.longitude, position.coords.latitude)
}, (error) => {
console.error("Current Location", error);
})
}
const fetchLocation = async (lon, lat) => {
try {
const location = await fetch(`https://geocode.maps.co/reverse?lat=${lat}&lon=${lon}&api_key=${api_key}`)
const response = await location.json();
console.log(response?.display_name);
}
catch (error) {
console.error("Error fetching location:", error);
}
}
currentLocation();`