skip to Main Content

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


  1. 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 the location within the geometry field.

    I am assuming that the data contains a results array with at least one object according to the documentation.

    const data = JSON.parse(response.getContentText());
    
    console.log(data); // View the response in its entirety
    
    const { lat, lng } = data.results[0].geometry.location;
    

    References:

    Please read the API documentation, if you are unfamiliar with how it works.

    Login or Signup to reply.
  2. Google UrlFetchApp class returns an HTTPResponse object. You can get the contents of the response data as a string with getContentText()

    var response = UrlFetchApp.fetch(serviceUrl, options);
    var content_text = response.getContentText()
    

    Your geocoding response will look something like but as a string:

    {
       results:[
          // some result
       ]
    }
    

    You can get the data by using

    var content = JSON.parse(content_text)
    

    Each element in the results object will have a geometry key such as:

    {
       results:[
          {
             // some stuff
             "geometry": {
                "location": {
                   "lat": 37.4224428,
                   "lng": -122.0842467
             },
             // some more stuff
          }
       ]
    }
    
    

    So you can get the lat and lng of any entry with something like:

    var some_entry = content.results[0] // note: I'm querying the first entry, but you can use any index
    
    var some_entry_lat = some_entry.geometry.location.lat
    var some_entry_lng = some_entry.geometry.location.lng
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search