Using Leaflet Coordinates with Google Maps Reverse Geocoding API

  1. Make sure to have Leaflet.js in your HTML and Javascript file. Use the ‘Getting Stared’ quick tutorial to make sure the map is up and running. The tutorial will have you use a onMapClick(e) function to set a popup upon a click on the map. You will notice that the popup will the LatLng coordinates as a string.

2. Got to Google’s Cloud Platform and sign in or create an account if you don’t already have one. Google has many API’s to choose from but you are going to want the Google Maps Geocoding API

You must enable this on your profile. You need to put down valid credit card or payment information so that if your request to the API reaches a certain limit or you’re using it commercially it can charge you accordingly.

You should now have access to the URL to fetch the data you need. You are going to want to make a fetch request to a URL that has the latlng query parameter with your API key that was generated. It will look something like this -${},${e.latlng.lng}&result_type=${filters2}&key={authenticationKey}

3. Now, in your onMapClick(e) function, you want to send a GET request to this URL. We know that when we click a spot on the map we get the latlng by using the event(e) such as e.latlng,, and e.latlng.lng.

if you want the information from the results of the fetch request to appear on your app you have to set it to an element’s value or textContent. For me, I used an input in a form element to display the city and country name for the spot I clicked. You need to nest into the data returned from the fetch request to display this particular data. My code looked like this -

.then(response => response.json())
.then(data => {
$location.value = data.results[0].formatted_address

That is all you need to do to cross-reference Leaflet.js’s latitude and longitude to the latitude and longitude in the Google Maps Geocoding API!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store