Explain Codes LogoExplain Codes Logo

Get city name using geolocation

javascript
geolocation
reverse-geocoding
api-marketplace
Nikita BarsukovbyNikita Barsukov·Jan 4, 2025
TLDR

To derive your city name from geolocation data, first, gather latitude and longitude coordinates via the Geolocation API. Feed those coordinates into a reverse geocoding API to retrieve the location details. Let's demonstrate this using the navigator.geolocation function along with the free bigdatacloud API for reverse geocoding:

navigator.geolocation.getCurrentPosition(async (position) => { const { latitude: lat, longitude: lon } = position.coords; // your precious coordinates are ready! const res = await fetch(`https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=en`); const { city } = await res.json(); // the city secret revealed! console.log(`City Name: ${city}`); }, console.log);

Remember to handle errors, and cater to varied browser support in your final code.

Graciously managing failures

Errors! They happen, but how you spring back matters most. When dealing with navigator.geolocation, it could potentially fail due to user denial or other unforeseen glitches. In such scenarios, handle errors gracefully and provide meaningful feedback. Here's how to do it:

function errorCallback(error) { switch(error.code) { case error.PERMISSION_DENIED: console.error("User denied the request for Geolocation. What a party pooper!"); // Oh come on! We've to start over now. break; case error.POSITION_UNAVAILABLE: console.error("Location information is unavailable. Seems like you're off the grid!"); // Are we in Bermuda Triangle!! break; case error.TIMEOUT: console.error("The request to get user location timed out. Internet, are you okay?"); // This ain't a snail race! break; case error.UNKNOWN_ERROR: console.error("An unknown error occurred. Somebody, call Sherlock!"); // Truly, we are in the unknown! break; } } navigator.geolocation.getCurrentPosition(successCallback, errorCallback);

Checking out the API marketplace

Pondering reverse geocoding, one might think it's just Google Maps API everywhere. But the API market offers varied flavors. Alternative APIs serve unique benefits, and here are a couple of them worth your attention:

  1. Geolocation-db.com API: A service that gets you geolocation sans user permission. Feel like a secret agent yet?
$.getJSON('https://geolocation-db.com/json/') .done (data => { console.log(data.city); // Behold, the city reveals itself });
  1. Ipinfo.io: A worthy contender, serving you location details from an IP address. Here’s where those IP classes in school pay off!
$.getJSON('https://ipinfo.io', data => { console.log(data.city); // City unmasked! The magic happening in just one line. });

These services, with their simpler operations, could be your knight in shining armor - ideal for lightweight applications not needing extensive details.

Cracking the JSON Rosetta Stone

Reverse geocoding APIs typically return their wisdom wrapped in JSON, with various address components bundled up. Your treasure hunt is for elements like city, region, country, and often a formatted_address, which is the holy grail of addresses. To gain the true city name, parsing these with ninja skills is key:

// Assuming successful geocoder response `geocoderResult` let city; $.each(geocoderResult.address_components, function(i, component) { if (component.types[0] === "locality") { city = component.long_name; return false; // Aha! Found the city, let's stop here. } }); console.log(`City Name: ${city}`); // Voila! The city stands revealed!

This magical spell goes through each address component, finds where the city (locality) is hiding, and reveals it to the world!

The cost of wisdom: API limitations and costs

Before you say 'API.AI', remember limitations and costs that come with it. Many APIs put a cap on free requests and make you part with your treasure(charges!) when that quota runs over. Another handy sword is to specify a language for the response; Google Translate ain't always your savior!

const languageParam = 'en'; // Here you can set your favorite language—for instance, the lingua franca: English.

Especially while challenging Google Maps API for geocoding, do check for google.maps.GeocoderStatus.OK to ensure success.

User privacy: Don't be that creepy stalker

Ensure you always have explicit consent from users before using location data. Though geolocation request triggers, a browser prompt, always be transparent about the purpose. Privacy is paramount, so respect decisions and provide alternatives if geolocation permission is turned down.