Sử dụng API Tra cứu khu vực bằng Google Trang tính

Bạn có thể tra cứu ID địa điểm cho các khu vực ngoại tuyến bằng cách gọi API Tra cứu khu vực từ Google Trang tính bằng Apps Script. Bạn nên áp dụng cách này cho các tập dữ liệu có tham số đầu vào không rõ ràng và có thể phân giải thành nhiều mã địa điểm (ví dụ: "10 Main Street"), có thể yêu cầu gỡ lỗi. Đã cung cấp một tập lệnh mẫu có các hàm sau:

  • SearchRegionByLocation tìm kiếm một địa điểm có ranh giới chứa toạ độ vĩ độ/kinh độ được chỉ định.
  • SearchRegionByAddress tìm kiếm một địa điểm có ranh giới chứa địa chỉ đã chỉ định.
  • SearchRegionByPlaceId tìm kiếm một địa điểm có mã địa điểm đã chỉ định.
  • LookupRegionByName tra cứu một địa điểm có tên đã được chỉ định.
  • LookupRegionByUnitCode tra cứu một địa điểm bằng mã đơn vị đã chỉ định.

Hàm tùy chỉnh của Tra cứu khu vực

Để sử dụng các hàm tuỳ chỉnh, trước tiên, bạn phải thêm mã tập lệnh .gs tuỳ chỉnh vào trình chỉnh sửa tập lệnh Apps Script. Sau khi tải tập lệnh, bạn có thể gọi các hàm như cách bạn gọi bất kỳ hàm nào khác trong bảng tính. Các tập lệnh lấy dữ liệu đầu vào từ các ô. Gọi các hàm tuỳ chỉnh từ trang tính như sau: =LookupRegionByName(A2,C2,D2,E2)

Kết quả sẽ được xuất trong ô chứa hàm và hai ô ở bên phải. Nếu có mã địa điểm đề xuất, kết quả cho các mã địa điểm đó cũng sẽ được xuất trong các ô liền kề. Một đường liên kết đến trang địa điểm hiển thị tên khu vực và đa giác trong Google Maps sẽ được cung cấp để xác minh. Trong ví dụ sau, nếu hàm được dán vào ô A1, kết quả sẽ có dạng như sau:

Mã địa điểm URL Vị trí Trang Mã lỗi
ChIJLQQwv4qBb0gRIMaY1COLDQU https://www.google.com/maps/search/?api=1&query=%20&query_place_id=ChIJLQQwv4qBb0gRIMaY1COLDQU

Trong ví dụ trước, yêu cầu thành công nên ô lỗi được để trống. Đối với các lỗi khiến tập lệnh không chạy đúng cách (chẳng hạn như bỏ qua khoá API hợp lệ), lỗi sẽ xuất hiện dưới dạng nhận xét cho ô chứa hàm.

Thêm hàm tuỳ chỉnh vào Apps Script

  1. Mở một bảng tính trong Google Trang tính.
  2. Chọn mục trong trình đơn Tiện ích > Apps Script.
  3. Xoá bất kỳ mã nào trong trình chỉnh sửa tập lệnh.
  4. Sao chép và dán mã trong ví dụ bên dưới vào trình chỉnh sửa tập lệnh.
  5. Thay thế YOUR_API_KEY bằng một khoá API không bị hạn chế thuộc về một dự án đã bật API tra cứu khu vực.
  6. Ở trên cùng, hãy nhấp vào biểu tượng Lưu .
/**
 * @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);
}