I’m trying to get the Google Maps geocode API working. I can’t figure out how to make use of a JSON response inside of Apps Script
Here’s what I have:
function geocode(address) {
var options = {
muteHttpExceptions: true,
contentType: "application/json",
};
var serviceUrl = "https://maps.googleapis.com/maps/api/geocode/json?address=" + "address" + "&key=" + YOUR_API_KEY;
var response = UrlFetchApp.fetch(serviceUrl, options);
if (response.getResponseCode() == 200) {
WHAT GOES HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
}
}
How do I get the Lat Lng from this? It’s been 5 hours and I can’t figure it out everything just errors or returns blank entries. Any help is great.
2
Answers
You will need to access the content as text and parse it as JSON. Once you have the data, you can access the latitude (
lat
) and longitude (lng
) values from thelocation
within thegeometry
field.I am assuming that the data contains a
results
array with at least one object according to the documentation.References:
Please read the API documentation, if you are unfamiliar with how it works.
Google UrlFetchApp class returns an HTTPResponse object. You can get the contents of the response data as a string with
getContentText()
Your geocoding response will look something like but as a
string
:You can get the data by using
Each element in the
results object
will have ageometry
key such as:So you can get the
lat
andlng
of any entry with something like: