Skip to content

Instantly share code, notes, and snippets.

@DataGreed
Created May 5, 2024 22:43
Show Gist options
  • Save DataGreed/39ab0923f0a20effbb81cb11a4128ffe to your computer and use it in GitHub Desktop.
Save DataGreed/39ab0923f0a20effbb81cb11a4128ffe to your computer and use it in GitHub Desktop.
Google Apps Script - extract the coordinates from shortened google maps links to use in Google Sheets
function extractAddressFromURL(url) {
// Find the start of the parameters after '?'
var queryStart = url.indexOf('?') + 1;
// Extract the substring from the start of the parameters to the end of the URL
var queryParams = url.substring(queryStart);
// Split the query parameters into an array of key-value pairs
var pairs = queryParams.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if (pair[0] === 'q' && pair[1]) {
// Decode the parameter value from URL encoding and return it
return decodeURIComponent(pair[1].replace(/\+/g, ' '));
}
}
return "Address not found";
}
function extractCoordinates(shortUrl) {
try {
// Fetch the URL and follow redirects to reach the final URL
var response = UrlFetchApp.fetch(shortUrl, {followRedirects: false});
console.log(response.toString())
console.log(response.getHeaders())
var longUrl = response.getHeaders()['Location'];
console.log("long url " + longUrl)
var address = extractAddressFromURL(longUrl)
console.log("address - " + address)
var coded = Maps.newGeocoder().geocode(address);
console.log("geocoded- " + coded)
for (var i = 0; i < coded.results.length; i++) {
var result = coded.results[i];
console.log('%s: %s, %s', result.formatted_address, result.geometry.location.lat,
result.geometry.location.lng);
return ""+result.geometry.location.lat+","+result.geometry.location.lng
}
return "coordinates not found"
} catch (e) {
// console.log("geocoded - " + Maps.newGeocoder().geocode(longUrl).results)
throw e;
return "Error fetching or parsing URL - "+longUrl; + String(e) // Error handling
}
}
// var z = "https://maps.app.goo.gl/iccVtVr1oDMCpvWU9?g_st=ic"
// // debug.log(extractCoordinates(z))
// console.log(extractCoordinates(z))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment