Home > other >  Caching results of Maps API call to reduce volume in Sheets
Caching results of Maps API call to reduce volume in Sheets

Time:12-29

I have a public form which incudes a place name, which I'm using the Places API to get the Place ID, to then do another call to look up an address. I need to optimize the volume of API calls so I'm trying to add caching so that Sheets doesn't re-call the two APIs unnecessarily.

For some reason I can't get the caching to work, either it errors or I get "object object" as the response.

function locId(text) {
  var text = cache.get(cacheLocId);
  if (cacheLocId === null) {
    var API_KEY = 'XYZXYZXYZ';
    var baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
    var queryUrl = baseUrl   '?input='   text   '&inputtype=textquery&key='   API_KEY;
    if (text == null) {
      console. log("I QUIT!")
      return;
      }
    var response = UrlFetchApp.fetch(queryUrl);
    var json = response.getContentText();
    var placeId = JSON.parse(json);
  }
  cache.put(cacheLocId, placeId)
  console. log(text)
  console. log(placeId)
  return placeId.candidates[0].place_id;
}

CodePudding user response:

It looks like you are overwriting the function argument and using cache keys and values the wrong way around. Try this pattern:

function locId(text) {
  if (!text || typeof text !== 'string') {
    return null;
  }
  const cache = CacheService.getDocumentCache();
  const cached = cache.get(text);
  if (cached) {
    return cached;
  }
  const API_KEY = 'XYZXYZXYZ';
  const baseUrl = 'https://maps.googleapis.com/maps/api/place/findplacefromtext/json';
  const queryUrl = baseUrl   '?input='   text   '&inputtype=textquery&key='   API_KEY;
  const response = UrlFetchApp.fetch(queryUrl);
  const placeId = JSON.parse(response.getContentText()).candidates[0].place_id;
  cache.put(text, placeId);
  return placeId;
}
  • Related