1

我在 Google 表格中开发了一个使用付费 API 的自定义函数。问题是每次打开工作表时功能都会刷新(正常的 Google 工作表行为)。我该如何解决这个问题?

只有在参数发生变化的情况下,该函数如何才能运行?

如果不是这种情况,它应该保留以前的结果。


/**
 * Gets distances
 *
 * @param {string} postalcode The origin
 * @param {string} apikey The Google API key
 * @param {Array} cities The destinations
 * @return The distances
 * @customfunction
 */
function C_GETDIST(postalcode, apikey, cities){
  if(postalcode == "")
    return "";

  var placeid = GETPID(postalcode,apikey);

  if(placeid == null)
    return "NO RESULTS GEO-CODING API";

  cities = cities.filter(function(city){ return city[0] !== "" ? true : false }).map(function(city){ return city[0].split(" ").join("+") });
  cities = cities.join('|');

  var d = new Date();
  d.setDate(d.getDate() + 1);
  d.setHours(9);
  var time = Math.round(d/1000);

  var endpoint = "https://maps.googleapis.com/maps/api/distancematrix/json";
  var query_basic = "origins=place_id:" + placeid
                    + "&"
                    + "destinations=" + encodeURIComponent(cities)
                    + "&"
                    + "arrival_time=" + time
                    + "&"
                    + "key=" + apikey;
  var query_transit = "mode=transit&transit_mode=rail";

  var requests = [
    endpoint + "?" + query_basic,
    endpoint + "?" + query_basic + "&" + query_transit
  ];  

  var responses = UrlFetchApp.fetchAll(requests);

  var distances_durations = [];
  for(var i = 0;i < responses.length; i++){
    var response = JSON.parse(responses[i].getContentText());
    if(!i)
      response["rows"][0]["elements"].map(function(element,index){          
        distances_durations[index] = element["status"] === "OK" ? [element["distance"]["value"],element["duration"]["value"]] : ["",""];
      },distances_durations)
    else
      response["rows"][0]["elements"].map(function(element,index){
        if(element["status"] === "OK")          
          distances_durations[index].push(element["distance"]["value"],element["duration"]["value"]);
        else
          distances_durations[index].push("",""); 
      },distances_durations)
  }

  return distances_durations
}

/**
 * Gets place id
 *
 * @param {string} postalcode Postal code
 * @param {string} apikey The Google API key
 * @return The place id
 */
function GETPID(postalcode, apikey){
  var endpoint = "https://maps.googleapis.com/maps/api/geocode/json";
  var query = "address=united%20kingdom&components=postal_code:";  

  var request = endpoint 
                + "?" 
                + query 
                + encodeURIComponent(postalcode) 
                + "&key=" 
                + apikey;

  var response = UrlFetchApp.fetch(request);

  var json = JSON.parse(response.getContentText());
  return json["status"] === "OK" ? [json["results"][0]["place_id"]] : null; // added as an array item 
}
4

1 回答 1

0

使用属性服务来存储以前的值和某种标志来告诉您的自定义函数何时应该获取存储在相应属性存储中的值以及何时应该从付费 API 中获取它。

有关的

于 2020-07-23T23:38:46.233 回答