Help

Re: Geocode addresses within Airtable

145 0
cancel
Showing results for 
Search instead for 
Did you mean: 
kpetrowski
4 - Data Explorer
4 - Data Explorer

Posting this here for anyone else who might find it helpful. While there are some great extensions for geocoding, I needed to simply convert an address into latitude and longitude and had a hard time finding a script to do it in Airtable + Google Maps API. 

I found this awesome script but had to modify it to only run on a particular view so that it didn't hit the automation / script limits. Here's my version for anyone looking for a way to geocode the record once it hits a particular view: 

Create number fields called Lat and Lng, get a Google Maps API key, create a view of records that have Address, but not Lat that can trigger an automation. 

let table = base.getTable('<TABLE NAME GOES HERE>');
let view = table.getView('<VIEW NAME GOES HERE>');
let result = await view.selectRecordsAsync({
sorts: [
{ field: 'Lat', direction: 'asc' },
{ field: 'Address', direction: 'asc' },
{ field: 'Lng', direction: 'asc' }
]
});

const GOOGLE_MAPS_API_KEY = '<API KEY GOES HERE>;

await Promise.all(
result.records.map(async record => {
let address = record.getCellValue('Address')
let lats = record.getCellValue('Lat')
let lngs = record.getCellValue('Lng')

if (!address) {
return
}

if (lats) {
console.log(`Skipping, location already exists: ${address}`)

}

console.log('Geocoding: ${address}')

let geo = await fetch(
`https://maps.googleapis.com/maps/api/geocode/json?address=${address.replace(
' ',
'+'
)}&key=${GOOGLE_MAPS_API_KEY}`
).then(r => r.json())

if (!geo.results || geo.results.length === 0) {
console.log(`No geocode results found for: ${address}`)
return
}

let {
geometry: {
location: { lat, lng }
}
} = geo.results[0]


console.log(lat,lng)
return await table.updateRecordAsync(record, {
Lat: lat,
Lng: lng
})
})
)

console.log('# Done!')

1 Reply 1
Cale_Barnett
4 - Data Explorer
4 - Data Explorer

Thank you so much for this. This just saved me sooo much time and effort!

Just to note - there is a small syntax error in your script. Where you place the API code is missing a closing  apostrophe. Other than that, this works like a dream 🙂

const GOOGLE_MAPS_API_KEY = '<API KEY GOES HERE>;

should be

const GOOGLE_MAPS_API_KEY = '<API KEY GOES HERE>';