搭配 Google 試算表使用 Region Lookup API

您可以透過 Google 試算表使用 Apps Script 呼叫 Region Lookup API,離線查詢區域的地點 ID。如果資料集的輸入參數不明確,且可能會解析為多個地點 ID (例如「10 Main Street」),或許就需要進行偵錯,在這種情況下,我們建議採取上述做法。這裡提供一個指令碼範例,包含下列函式:

  • SearchRegionByLocation:搜尋邊界包含指定經緯度座標的地點。
  • SearchRegionByAddress:搜尋邊界包含指定地址的地點。
  • SearchRegionByPlaceId:搜尋包含指定地點 ID 的地點。
  • LookupRegionByName:查詢包含指定名稱的地點。
  • LookupRegionByUnitCode:查詢包含指定單位代碼的地點。

區域查詢自訂函式

如要使用自訂函式,請先將自訂函式 .gs 指令碼程式碼,加進 Apps Script 指令碼編輯器。載入指令碼後,您可以呼叫這些函式,與呼叫任何其他試算表函式相同。指令碼會從儲存格取得輸入資料。透過試算表呼叫自訂函式,如下所示: =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 Script 中加入自訂函式

  1. 在 Google 試算表中開啟試算表。
  2. 在選單項目中依序選取「擴充功能」>「Apps Script」
  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);
}