استخدام واجهة برمجة تطبيقات البحث عن المنطقة في "جداول بيانات Google"

يمكنك البحث عن معرّفات الأماكن لمناطق غير متصلة بالإنترنت من خلال استدعاء واجهة برمجة تطبيقات Region Lookup API من "جداول بيانات Google" باستخدام "برمجة تطبيقات Google". ننصح بتنفيذ هذا الإجراء لمجموعات البيانات التي تكون فيها مَعلمات الإدخال غامضة ويمكن أن يتم تحويلها إلى أرقام تعريف أماكن متعدّدة (على سبيل المثال، "10 Main Street")، والتي قد تتطلّب تصحيح الأخطاء. تم تقديم نموذج نصي مع الدوال التالية:

  • تبحث دالة SearchRegionByLocation عن مكان يحتوي حدوده على إحداثيات خط العرض/خط الطول المحددة.
  • يبحث SearchRegionByAddress عن مكان تحتوي حدوده على العنوان المحدد.
  • يبحث SearchRegionByPlaceId عن مكان له معرّف المكان المحدد.
  • يبحث LookupRegionByName عن مكان يحمل الاسم المحدّد.
  • يبحث LookupRegionByUnitCode عن مكان يحمل رمز الوحدة المحدّد.

الدوال المخصّصة للبحث عن المنطقة

لاستخدام الدوال المخصّصة، يجب أولاً إضافة رمز النص البرمجي gs .للدوال المخصّصة إلى محرِّر النصوص البرمجية لـ "برمجة تطبيقات Google". بمجرد تحميل النص البرمجي، يمكنك استدعاء الدوال كما تستدعي أي دالة أخرى في جدول البيانات. تأخذ البرامج النصية بيانات الإدخال من الخلايا. استدعِ الدوال المخصّصة من ورقة البيانات على النحو التالي: =LookupRegionByName(A2,C2,D2,E2)

النتائج هي مخرجات في الخلية التي تحتوي على الدالة، والخليتين على اليمين. إذا كانت معرّفات الأماكن المرشحة متاحة، فسيتم أيضًا إخراج نتائج معرّفات الأماكن هذه في الخلايا المجاورة. يتوفر رابط إلى صفحة المكان الذي يعرض اسم المنطقة والمضلّع في "خرائط Google" بهدف التحقّق. في المثال التالي، إذا تم لصق الدالة في الخلية A1، فستبدو النتائج مشابهة لما يلي:

معرّف المكان ‏‫عنوان URL لصفحة المكان‬ رمز الخطأ
ChIJLQQwv4qBb0gRIMaY1COLDQU https://www.google.com/maps/search/?api=1&query=%20&query_place_id=ChIJLQQwv4qBb0gRIMaY1COLDQU

في المثال السابق، نجح الطلب ولذلك أصبحت خلية الخطأ فارغة. بالنسبة إلى الأخطاء التي تمنع تشغيل النص البرمجي بشكل صحيح (مثل حذف مفتاح واجهة برمجة تطبيقات صالح)، سيظهر الخطأ كتعليق للخلية التي تحتوي على الدالة.

إضافة الدوال المخصّصة إلى "برمجة تطبيقات Google"

  1. افتح جدول بيانات في Google Sheets.
  2. اختَر عنصر القائمة الإضافات > برمجة التطبيقات.
  3. احذف أي رمز في أداة تعديل النصوص البرمجية.
  4. انسخ الرمز من المثال أدناه والصقه في مُحرِّر النصوص البرمجية.
  5. استبدِل YOUR_API_KEY بمفتاح واجهة برمجة تطبيقات غير مشروط ينتمي لمشروع تم تفعيله من خلال واجهة برمجة التطبيقات للبحث عن المنطقة فيه.
  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);
}