Skip to content

Instantly share code, notes, and snippets.

@bhubr
Last active March 13, 2024 15:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bhubr/bbddcb34d570aec75b5c53943fb7f5d1 to your computer and use it in GitHub Desktop.
Save bhubr/bbddcb34d570aec75b5c53943fb7f5d1 to your computer and use it in GitHub Desktop.
Call Google Geocoding API to get latitude and longitude of a given address
module.exports = {
googleApiKey: 'INSERT_YOUR_KEY_HERE'
}
const { googleApiKey } = require('./config')
const axios = require('axios')
/**
* Query Google Geocoding API to get latitude&longitude from address
*
* Usage Example:
* geocodingQuery('1 place du Capitole', 'Toulouse')
* .then(({ lat, lng }) => {
* // do something with lat&lng
* })
*
* @param {string} address street address in the city
* @param {string} city city
*/
const geocodingQuery = (address, city) => {
const geocoderQuery = encodeURIComponent(`${address} ${city}`.replace(/ /g, '+'))
return axios.get(`https://maps.googleapis.com/maps/api/geocode/json?address=${geocoderQuery}&key=${googleApiKey}`)
.then(res => res.data)
.then(json => {
if (json.results.length === 0) {
return null
}
let lat = json.results['0'].geometry.location.lat
let lng = json.results['0'].geometry.location.lng
return {lat, lng}
})
}
module.exports = geocodingQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment