Last active
March 13, 2024 15:45
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module.exports = { | |
googleApiKey: 'INSERT_YOUR_KEY_HERE' | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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