Created
August 29, 2019 06:25
-
-
Save planemad/eb8d3e03cb448de2d3f7b12f6b5f293f to your computer and use it in GitHub Desktop.
Google Sheet script to reverse geocode coordinnates
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
// Mapbox Reverse Geocode Addresses | |
// based on https://github.com/nuket/google-sheets-geocoding-macro/blob/master/Code.gs | |
// Copyright (c) 2016 - 2017 Max Vilimpoc | |
// | |
// Reverse Geocode -- GPS position to nearest address. | |
function positionToAddress() { | |
var sheet = SpreadsheetApp.getActiveSheet(); | |
var cells = sheet.getActiveRange(); | |
var cells = sheet.getRange("A1:P2582"); | |
var startingRow = 1176 | |
var popup = SpreadsheetApp.getUi(); | |
// Must have selected at least 3 columns (Address, Lat, Lng). | |
// Must have selected at least 1 row. | |
var columnCount = cells.getNumColumns(); | |
if (columnCount < 3) { | |
popup.alert(columnCount); | |
return; | |
} | |
var latColumn = 1; | |
var lngColumn = 2; | |
var addressColumn = columnCount-1; | |
for (addressRow=startingRow; addressRow <= cells.getNumRows(); ++addressRow) { | |
sleep(200); | |
var lat = cells.getCell(addressRow, latColumn).getValue(); | |
var lng = cells.getCell(addressRow, lngColumn).getValue(); | |
// Geocode the lat, lng pair to an address. | |
token = 'pk.eyJ1IjoicGxhbmVtYWQiLCJhIjoiemdYSVVLRSJ9.g3lbg_eN0kztmsfIPxa9MQ'; | |
url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/' + lng+','+ lat + '.json?access_token='+ token +'&routing=true'; | |
var address,place,postcode; | |
var response = UrlFetchApp.fetch(url).getContentText() | |
// Only change cells if geocoder seems to have gotten a | |
// valid response. | |
if (true) { | |
response = JSON.parse(response); | |
Logger.log(response); | |
address = response.features[0].place_name | |
response.features.forEach(function(feature){ | |
if(feature.place_type[0]=='postcode'){ | |
postcode = feature.text | |
} | |
}) | |
cells.getCell(addressRow, addressColumn).setValue(address); | |
cells.getCell(addressRow, addressColumn+1).setValue(postcode); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment