ड्राइविंग दूरी कैलकुलेट करें और मीटर को मील में बदलें

कोडिंग का लेवल: शुरुआती
कुल समय: 10 मिनट
प्रोजेक्ट टाइप: कस्टम फ़ंक्शन और कस्टम मेन्यू की मदद से ऑटोमेशन की सुविधा

मकसद

  • समझें कि समाधान क्या है.
  • जानें कि Apps Script सेवा के अंदर क्या काम करती है.
  • स्क्रिप्ट सेट अप करें.
  • स्क्रिप्ट चलाएं.

इस सलूशन के बारे में जानकारी

कस्टम फ़ंक्शन का इस्तेमाल करके, दो जगहों के बीच की ड्राइविंग की दूरी का पता लगाया जा सकता है और दूरी को मीटर से मील में बदला जा सकता है. इसके अलावा, ऑटोमेशन से एक कस्टम मेन्यू मिलता है. इसकी मदद से, नई शीट में शुरुआती पते से आखिरी पते तक सिलसिलेवार तरीके से निर्देश जोड़े जा सकते हैं.

किसी शीट में ड्राइविंग दिशा-निर्देशों का स्क्रीनशॉट.

यह कैसे काम करता है

स्क्रिप्ट में दो कस्टम फ़ंक्शन और एक ऑटोमेशन का इस्तेमाल किया जाता है.

  • drivingDistance(origin, destination) फ़ंक्शन, दो जगहों के बीच ड्राइविंग दिशा-निर्देशों का पता लगाने और मीटर में दो पतों के बीच की दूरी का पता लगाने के लिए, Maps सेवा का इस्तेमाल करता है.
  • metersToMiles(meters) फ़ंक्शन, मीटर की दी गई संख्या के लिए मील की बराबर संख्या की गणना करता है.
  • ऑटोमेशन, उपयोगकर्ता को शुरुआती और आखिरी पते की किस पंक्ति में जाने के लिए कहता है, ताकि ड्राइविंग दिशा-निर्देश का हिसाब लगाया जा सके. इसके बाद, एक नई शीट में सिलसिलेवार तरीके से ड्राइविंग दिशा-निर्देश जोड़े जाते हैं.

Apps Script सेवाएं

यह समाधान इन सेवाओं का इस्तेमाल करता है:

  • स्प्रेडशीट सेवा– इसमें कस्टम मेन्यू जोड़ा जाता है, इस समाधान की जांच करने के लिए डेमो डेटा जोड़ा जाता है. साथ ही, जब स्क्रिप्ट ड्राइविंग दिशा-निर्देश जोड़ती है, तो नई शीट को फ़ॉर्मैट किया जाता है.
  • बुनियादी सेवा–यह उपयोगकर्ता को निर्देशों के लिए पंक्ति नंबर डालने का निर्देश देने के लिए, Browser क्लास का इस्तेमाल करता है. साथ ही, कोई गड़बड़ी होने पर, उपयोगकर्ता को सूचना देता है.
  • उपयोगिताएं–टेंप्लेट की स्ट्रिंग को उपयोगकर्ता की तय की गई जानकारी से अपडेट किया जाता है.
  • मैप सेवा– इसमें Google Maps के शुरुआती पते से लेकर आखिरी पते तक के निर्देश सिलसिलेवार मिलते हैं.

ज़रूरी शर्तें

इस सैंपल का इस्तेमाल करने के लिए, आपको ये ज़रूरी शर्तें पूरी करनी होंगी:

  • Google खाता (Google Workspace खातों के लिए एडमिन की अनुमति ज़रूरी हो सकती है).
  • इंटरनेट ऐक्सेस करने वाला वेब ब्राउज़र.

स्क्रिप्ट सेट अप करें

  1. ड्राइविंग दूरी की गणना करें और मीटर को मील में बदलें स्प्रेडशीट की कॉपी बनाएं. इस समाधान का Apps Script प्रोजेक्ट, स्प्रेडशीट में अटैच किया गया है.
    कॉपी बनाएं
  2. अपनी शीट में हेडर और डेमो डेटा जोड़ने के लिए, निर्देश > शीट तैयार करें पर क्लिक करें. इस कस्टम मेन्यू को दिखाने के लिए आपको पेज को रीफ़्रेश करना पड़ सकता है.
  3. जब कहा जाए, तब स्क्रिप्ट को अनुमति दें. अगर OAuth के लिए सहमति देने वाली स्क्रीन पर चेतावनी दिखती है, इस ऐप्लिकेशन की पुष्टि नहीं हुई है, तो बेहतर > को चुनकर जारी रखें {Project Name} पर जाएं (असुरक्षित).

  4. निर्देश > शीट तैयार करें पर फिर से क्लिक करें.

स्क्रिप्ट चलाएं

  1. सेल C2 में, =DRIVINGDISTANCE(A2,B2) फ़ॉर्मूला डालें और Enter दबाएं. अगर आप ऐसी जगह पर हैं जहां दशमलव कॉमा का इस्तेमाल किया जाता है, तो आपको =DRIVINGDISTANCE(A2;B2) डालना पड़ सकता है.
  2. सेल D2 में, =METERSTOMILES(C2) फ़ॉर्मूला डालें और Enter दबाएं.
  3. (ज़रूरी नहीं) शुरुआती और आखिरी पतों की अतिरिक्त पंक्तियां जोड़ें. साथ ही, अलग-अलग जगहों के बीच की ड्राइविंग दूरी का हिसाब लगाने के लिए, C और D कॉलम में दिए गए फ़ॉर्मूला को कॉपी करें.
  4. निर्देश > सिलसिलेवार तरीके से जनरेट करें पर क्लिक करें.
  5. डायलॉग में उन पतों की पंक्ति का नंबर डालें जिनके लिए आपको निर्देश जनरेट करने हैं और ठीक है पर क्लिक करें.
  6. स्क्रिप्ट की बनाई गई नई शीट में, ड्राइविंग के दिशा-निर्देशों की समीक्षा करें.

कोड की समीक्षा करें

इस समाधान के Apps Script कोड की समीक्षा करने के लिए, नीचे सोर्स कोड देखें पर क्लिक करें:

सोर्स कोड देखें

Code.gs

sheets/customFunctions/customFunctions.gs
/**
 * @OnlyCurrentDoc Limits the script to only accessing the current sheet.
 */

/**
 * A special function that runs when the spreadsheet is open, used to add a
 * custom menu to the spreadsheet.
 */
function onOpen() {
  try {
    const spreadsheet = SpreadsheetApp.getActive();
    const menuItems = [
      {name: 'Prepare sheet...', functionName: 'prepareSheet_'},
      {name: 'Generate step-by-step...', functionName: 'generateStepByStep_'}
    ];
    spreadsheet.addMenu('Directions', menuItems);
  } catch (e) {
    // TODO (Developer) - Handle Exception
    console.log('Failed with error: %s' + e.error);
  }
}

/**
 * A custom function that converts meters to miles.
 *
 * @param {Number} meters The distance in meters.
 * @return {Number} The distance in miles.
 */
function metersToMiles(meters) {
  if (typeof meters !== 'number') {
    return null;
  }
  return meters / 1000 * 0.621371;
}

/**
 * A custom function that gets the driving distance between two addresses.
 *
 * @param {String} origin The starting address.
 * @param {String} destination The ending address.
 * @return {Number} The distance in meters.
 */
function drivingDistance(origin, destination) {
  const directions = getDirections_(origin, destination);
  return directions.routes[0].legs[0].distance.value;
}

/**
 * A function that adds headers and some initial data to the spreadsheet.
 */
function prepareSheet_() {
  try {
    const sheet = SpreadsheetApp.getActiveSheet().setName('Settings');
    const headers = [
      'Start Address',
      'End Address',
      'Driving Distance (meters)',
      'Driving Distance (miles)'];
    const initialData = [
      '350 5th Ave, New York, NY 10118',
      '405 Lexington Ave, New York, NY 10174'];
    sheet.getRange('A1:D1').setValues([headers]).setFontWeight('bold');
    sheet.getRange('A2:B2').setValues([initialData]);
    sheet.setFrozenRows(1);
    sheet.autoResizeColumns(1, 4);
  } catch (e) {
    // TODO (Developer) - Handle Exception
    console.log('Failed with error: %s' + e.error);
  }
}

/**
 * Creates a new sheet containing step-by-step directions between the two
 * addresses on the "Settings" sheet that the user selected.
 */
function generateStepByStep_() {
  try {
    const spreadsheet = SpreadsheetApp.getActive();
    const settingsSheet = spreadsheet.getSheetByName('Settings');
    settingsSheet.activate();

    // Prompt the user for a row number.
    const selectedRow = Browser
        .inputBox('Generate step-by-step', 'Please enter the row number of' +
        ' the' + ' addresses to use' + ' (for example, "2"):',
        Browser.Buttons.OK_CANCEL);
    if (selectedRow === 'cancel') {
      return;
    }
    const rowNumber = Number(selectedRow);
    if (isNaN(rowNumber) || rowNumber < 2 ||
      rowNumber > settingsSheet.getLastRow()) {
      Browser.msgBox('Error',
          Utilities.formatString('Row "%s" is not valid.', selectedRow),
          Browser.Buttons.OK);
      return;
    }


    // Retrieve the addresses in that row.
    const row = settingsSheet.getRange(rowNumber, 1, 1, 2);
    const rowValues = row.getValues();
    const origin = rowValues[0][0];
    const destination = rowValues[0][1];
    if (!origin || !destination) {
      Browser.msgBox('Error', 'Row does not contain two addresses.',
          Browser.Buttons.OK);
      return;
    }

    // Get the raw directions information.
    const directions = getDirections_(origin, destination);

    // Create a new sheet and append the steps in the directions.
    const sheetName = 'Driving Directions for Row ' + rowNumber;
    let directionsSheet = spreadsheet.getSheetByName(sheetName);
    if (directionsSheet) {
      directionsSheet.clear();
      directionsSheet.activate();
    } else {
      directionsSheet =
        spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets());
    }
    const sheetTitle = Utilities
        .formatString('Driving Directions from %s to %s', origin, destination);
    const headers = [
      [sheetTitle, '', ''],
      ['Step', 'Distance (Meters)', 'Distance (Miles)']
    ];
    const newRows = [];
    for (const step of directions.routes[0].legs[0].steps) {
      // Remove HTML tags from the instructions.
      const instructions = step.html_instructions
          .replace(/<br>|<div.*?>/g, '\n').replace(/<.*?>/g, '');
      newRows.push([
        instructions,
        step.distance.value
      ]);
    }
    directionsSheet.getRange(1, 1, headers.length, 3).setValues(headers);
    directionsSheet.getRange(headers.length + 1, 1, newRows.length, 2)
        .setValues(newRows);
    directionsSheet.getRange(headers.length + 1, 3, newRows.length, 1)
        .setFormulaR1C1('=METERSTOMILES(R[0]C[-1])');

    // Format the new sheet.
    directionsSheet.getRange('A1:C1').merge().setBackground('#ddddee');
    directionsSheet.getRange('A1:2').setFontWeight('bold');
    directionsSheet.setColumnWidth(1, 500);
    directionsSheet.getRange('B2:C').setVerticalAlignment('top');
    directionsSheet.getRange('C2:C').setNumberFormat('0.00');
    const stepsRange = directionsSheet.getDataRange()
        .offset(2, 0, directionsSheet.getLastRow() - 2);
    setAlternatingRowBackgroundColors_(stepsRange, '#ffffff', '#eeeeee');
    directionsSheet.setFrozenRows(2);
    SpreadsheetApp.flush();
  } catch (e) {
    // TODO (Developer) - Handle Exception
    console.log('Failed with error: %s' + e.error);
  }
}

/**
 * Sets the background colors for alternating rows within the range.
 * @param {Range} range The range to change the background colors of.
 * @param {string} oddColor The color to apply to odd rows (relative to the
 *     start of the range).
 * @param {string} evenColor The color to apply to even rows (relative to the
 *     start of the range).
 */
function setAlternatingRowBackgroundColors_(range, oddColor, evenColor) {
  const backgrounds = [];
  for (let row = 1; row <= range.getNumRows(); row++) {
    const rowBackgrounds = [];
    for (let column = 1; column <= range.getNumColumns(); column++) {
      if (row % 2 === 0) {
        rowBackgrounds.push(evenColor);
      } else {
        rowBackgrounds.push(oddColor);
      }
    }
    backgrounds.push(rowBackgrounds);
  }
  range.setBackgrounds(backgrounds);
}

/**
 * A shared helper function used to obtain the full set of directions
 * information between two addresses. Uses the Apps Script Maps Service.
 *
 * @param {String} origin The starting address.
 * @param {String} destination The ending address.
 * @return {Object} The directions response object.
 */
function getDirections_(origin, destination) {
  const directionFinder = Maps.newDirectionFinder();
  directionFinder.setOrigin(origin);
  directionFinder.setDestination(destination);
  const directions = directionFinder.getDirections();
  if (directions.status !== 'OK') {
    throw directions.error_message;
  }
  return directions;
}

योगदानकर्ता

Google, इस सैंपल को मैनेज करने के लिए Google Developer के विशेषज्ञों की मदद लेता है.

अगले चरण