将 Region Find API 与 Google 表格搭配使用

您可以使用 Apps 脚本在 Google 表格中调用 Region Lookup API,离线查找地区的地点 ID。如果数据集的输入参数不明确且可能会解析为多个地点 ID(例如“主街 10 号”),就可能需要进行调试,对于这种情况,我们建议使用以上方式。我们提供了一个示例脚本,其中包含以下函数:

  • SearchRegionByLocation:用于搜索边界包含指定纬度/经度坐标的地点。
  • SearchRegionByAddress:用于搜索边界包含指定地址的地点。
  • SearchRegionByPlaceId:用于搜索具有指定地点 ID 的地点。
  • LookupRegionByName:用于查找具有指定名称的地点。
  • LookupRegionByUnitCode:用于查找包含指定单位代码的地点。

地区查找自定义函数

若要使用自定义函数,您必须先将自定义函数 .gs 脚本代码添加到 Apps 脚本的脚本编辑器中。加载此脚本后,您就可以像调用任何其他电子表格函数一样调用这些函数。这些脚本会从单元格获取输入数据。从工作表中调用自定义函数,如下所示:=LookupRegionByName(A2,C2,D2,E2)

结果会输出到函数所在的单元格和右侧两个单元格中。如果有可用的候选地点 ID,这些地点 ID 的结果也会输出到相邻的单元格中。我们提供一个指向地点页面的链接,该页面会显示 Google 地图上的地区名称和多边形,以便您进行验证。在下面的示例中,如果将函数粘贴到单元格 A1 中,结果将如下所示:

地点 ID 地点页面网址 错误代码
ChIJLQQwv4qBb0gRIMaY1COLDQU https://www.google.com/maps/search/?api=1&query=%20&query_place_id=ChIJLQQwv4qBb0gRIMaY1COLDQU

在上面的示例中,请求成功,因此错误代码单元格为空。导致脚本无法正常运行的错误(例如省略有效的 API 密钥)会在函数所在的单元格中显示为注释。

将自定义函数添加到 Apps 脚本中

  1. 在 Google 表格中打开电子表格。
  2. 依次选择扩展程序 > Apps 脚本菜单项。
  3. 删除脚本编辑器中的所有代码。
  4. 复制以下示例中的代码并将其粘贴到脚本编辑器中。
  5. YOUR_API_KEY 替换为不受限制的 API 密钥,该密钥应属于已启用 Region Lookup API 的项目。
  6. 点击顶部的“保存”图标
/**
 * @fileoverview Provides custom Geo functions in Google Sheets for matching boundaries.
 * * SearchRegionByLocation searches for a region whose boundary contains the specified latitude/longitude coordinates.
 * * SearchRegionByAddress searches for a region whose boundary contains the specified address.
 * * SearchRegionByPlaceId searches for a region whose boundary contains the specified place ID.
 * * LookupRegionByName looks up a region with the specified name.
 * * LookupRegionByUnitCode looks up a region with the specified unit code.
 * @OnlyCurrentDoc
 */

var api_key = "YOUR_API_KEY"; // An unrestricted key is recommended for local use only (deployment is NOT recommended).

function format_url(place_id) {
  return place_id && 'https://www.google.com/maps/search/?api=1&query=%20&query_place_id=' + place_id;
}

function format_result(result) {
  let matches = result.matches || [];
  let firstMatch = result.matches[0] || {};

  let placeId = firstMatch.matchedPlaceId || '';
  let debugInfo = firstMatch.debugInfo || '';
  let candidates = firstMatch.candidatePlaceIds || [];

  return [[
    placeId || '(NULL)',
    format_url(placeId),
    debugInfo,
    candidates[0],
    format_url(candidates[0]),
    candidates[1],
    format_url(candidates[1]),
    candidates[2],
    format_url(candidates[2])
    ]];
}

/**
 * Searches for a place whose boundary contains the specified latitude/longitude coordinates.
 *
 * @param {number} latitude - The latitude where the place will be found (e.g., 37.531939).
 * @param {number} longitude - The longitude where the place will be found (e.g., -122.2994121).
 * @param {string} place_type - The place type of the place ("postal_code", "administrative_area_level_1", "administrative_area_level_2", "locality", or "country").
 *
 * @return {string} The place_id of the place, or null if none was found.
 *
 * @customfunction
 */
function SearchRegionByLocation(
  latitude, longitude, place_type) {
  var data = {
    "search_values": [ {
      "latlng": { 'latitude': latitude, 'longitude': longitude }, // { latitude: 37.531939, longitude: -122.2994121 }
      "place_type": place_type,
      "region_code": null,
      "language_code": null,
    } ]
  };

  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
        'X-Goog-Api-Key' : api_key
      },
      // Convert the JavaScript object to a JSON string.
      'payload' : JSON.stringify(data)
    };

  var response = UrlFetchApp.fetch(
    'https://regionlookup.googleapis.com/v1alpha:searchRegion',
    options);

  var resultText = response.getContentText();
  console.log(resultText);
  var result = JSON.parse(resultText);

  return format_result(result);
}

/**
 * Searches for a place whose boundary contains the specified address.
 *
 * @param {string} address - An address within the place boundaries (e.g., "1505 Salado Dr, Mountain View, CA").
 * @param {string} place_type - The geo type id of the place (e.g., "locality").
 * @param {string} [region_code='us'] - The region code of the place (e.g., "US").
 * @param {string} [language_code='en'] - The language code of the place's name. (e.g., "en").
 *
 * @return {string} The place_id of the place, or null if none was found.
 *
 * @customfunction
 */

function SearchRegionByAddress(
  address, place_type, region_code, language_code) {

  var data = {
    "search_values": {
        "address": address,
        "place_type" : place_type,
        "region_code": region_code || 'us',
        "language_code": language_code || 'en',
      }
  };

  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
        'X-Goog-Api-Key' : api_key
      },
      // Convert the JavaScript object to a JSON string.
      'payload' : JSON.stringify(data)
    };

  var response = UrlFetchApp.fetch(
    'https://regionlookup.googleapis.com/v1alpha:searchRegion',
    options);

  var resultText = response.getContentText();
  console.log(resultText);
  var result = JSON.parse(resultText);

  return format_result(result);
}

/**
 * Searches for a place with the specified place ID.
 *
 * @param {string} place_id - The place ID to search for.
 * @param {string} place_type - The geo type id of the place (e.g., "locality").
 * @param {string} [region_code='us'] - The region code of the place (e.g., "US").
 * @param {string} [language_code='en'] - The language code of the place's name. (e.g., "en").
 *
 * @return {string} The place_id of the place, or null if none was found.
 *
 * @customfunction
 */
function SearchRegionByPlaceId(
  place_id, place_type, region_code, language_code) {

 var data = {
   "search_values": {
       "place_id": place_id,
       "place_type" : place_type,
       "region_code": region_code || 'us',
       "language_code": language_code || 'en',
     }
 };

 var options = {
   'method' : 'post',
   'contentType': 'application/json',
   'headers': {
       'X-Goog-Api-Key' : api_key
     },
     // Convert the JavaScript object to a JSON string.
     'payload' : JSON.stringify(data)
   };

 var response = UrlFetchApp.fetch(
   'https://regionlookup.googleapis.com/v1alpha:searchRegion',
   options);
  var resultText = response.getContentText();
 console.log(resultText);
 var result = JSON.parse(resultText);

 return format_result(result);
}

/**
 * Looks up a place with the specified name.
 *
 * @param {string} place_name - The name of the place (e.g., "Palo Alto").
 * @param {string} place_type - The geo type id of the place (e.g., "locality").
 * @param {string} [region_code='us'] - The region code of the place (e.g., "US").
 * @param {string} [language_code='en'] - The language code of the place's name. (e.g., "en").
 *
 * @return {string} The place_id of the place, or null if none was found.
 *
 * @customfunction
 */
function LookupRegionByName(
  place, place_type, region_code, language_code) {
  var data = {
    "identifiers": [ {
        "place": '' + place,
        "place_type": place_type,
        "region_code": region_code || 'us',
        "language_code": language_code || 'en',
      }
    ]
  };

  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
        'X-Goog-Api-Key' : api_key
      },
      // Convert the JavaScript object to a JSON string.
      'payload' : JSON.stringify(data),
      //'muteHttpExceptions' : true,
    };

  var response = UrlFetchApp.fetch(
    'https://regionlookup.googleapis.com/v1alpha:lookupRegion',
    options);

  var resultText = response.getContentText();

  console.log(resultText);
  var result = JSON.parse(resultText);

  return format_result(result);
}

/**
 * Looks up a place with the specified unit code.
 *
 * @param {string} place_name - The name of the place (e.g., "Palo Alto").
 * @param {string} place_type - The geo type id of the place (e.g., "locality").
 * @param {string} [region_code='us'] - The region code of the place (e.g., "US").
 * @param {string} [language_code='en'] - The language code of the place's name. (e.g., "en").
 *
 * @return {string} The place_id of the place, or null if none was found.
 *
 * @customfunction
 */
function LookupRegionByUnitCode(
  unit_code, place_type, region_code, language_code) {
  var data = {
    "identifiers": [ {
        "unit_code": '' + unit_code,
        "place_type": place_type,
        "region_code": region_code || 'us',
        "language_code": language_code || 'en',
      }
    ]
  };

  var options = {
    'method' : 'post',
    'contentType': 'application/json',
    'headers': {
        'X-Goog-Api-Key' : api_key
      },
      // Convert the JavaScript object to a JSON string.
      'payload' : JSON.stringify(data),
      //'muteHttpExceptions' : true,
    };

  var response = UrlFetchApp.fetch(
    'https://regionlookup.googleapis.com/v1alpha:lookupRegion',
    options);

  var resultText = response.getContentText();

  console.log(resultText);
  var result = JSON.parse(resultText);

  return format_result(result);
}