DEV Community

XING
XING

Posted on • Updated on

Getting Name from Latitude and Longitude - Google Geocode API

I wrote this utility function that tells me the approximate location given a latitude and longitude in the form of a promise holding a string. You just have to put in the latitude, longitude and API key. It also contains a cache holding onto all queried latitude and longitude.

How does it work?

The utility function to query the API is an async function for obvious reasons (we do not want the main thread to wait for the response). I used axios to issue a HTTP GET request to the API endpoint, and parsed the response to get the formatted address. This is then returned as an awaited string. The end result? We get a Promise that returns a String which we can then handle and set it to the state accordingly. Since the demo is written in React, changing the state will trigger a rerender of the component and our new string is now displayed.
https://codesandbox.io/s/google-geocoding-api-demo-ipyfx?file=/src/utils.js

Ideally, the API key should be loaded from the environment, but hey, this is just a demo. I also did zero error handling for the same reason :)

You can get the API key and documentation from the official google site:
https://developers.google.com/maps/documentation/geocoding/overview

Discussion (0)