रास्ता मैट्रिक्स पाएं

यूरोपियन इकनॉमिक एरिया (ईईए) के डेवलपर

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

पूरे उदाहरण का सोर्स कोड देखें

इस उदाहरण में बताया गया है कि Route Matrix क्लास का इस्तेमाल करके, एक से ज़्यादा जगहों से अलग-अलग मंज़िलों तक की यात्रा में लगने वाले समय और दूरी का हिसाब कैसे लगाया जाता है.

TypeScript

// Initialize and add the map.
let map;
let markers: google.maps.marker.AdvancedMarkerElement[] = [];
let center = { lat: 51.55, lng: -1.8 };

async function initMap(): Promise<void> {
  //  Request the needed libraries.
  //@ts-ignore
  const [{Map}, {Place}, {AdvancedMarkerElement, PinElement}, {RouteMatrix}] = await Promise.all([
    google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>,
    google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>,
    google.maps.importLibrary('marker') as Promise<google.maps.MarkerLibrary>,
    google.maps.importLibrary('routes') as Promise<google.maps.RoutesLibrary>
  ]);

  const bounds = new google.maps.LatLngBounds();

  map = new Map(document.getElementById('map') as HTMLElement, {
    zoom: 8,
    center: center,
    mapId: 'DEMO_MAP_ID',
  });

  // Build the request using Place instances.
  const origin1 = new Place({
    id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK
  });
  const origin2 = new Place({
    id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK
  });
  const destinationA = new Place({
    id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK
  });
  const destinationB = new Place({
    id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK
  });

  await Promise.all([
    origin1.fetchFields({ fields: ['location', 'displayName']}),
    origin2.fetchFields({ fields: ['location', 'displayName']}),
    destinationA.fetchFields({ fields: ['location', 'displayName']}),
    destinationB.fetchFields({ fields: ['location', 'displayName']}),
  ]);

  const request = {
    origins: [origin1, origin2], 
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    units: google.maps.UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
  };

  // Show the request.
  (document.getElementById("request") as HTMLDivElement).innerText =
    JSON.stringify(request, null, 2);

  // Get the RouteMatrix response.
  const response = await RouteMatrix.computeRouteMatrix(request); 

  // Show the response.
  (document.getElementById("response") as HTMLDivElement).innerText =
    JSON.stringify(response, null, 2);

  // Add markers for the origins.
  for (const origin of request.origins) {
    if (origin.location) {
      const pin = new PinElement({
        //@ts-ignore
        glyphText: "O",
        glyphColor: "white",
        background: "#137333",
        borderColor: "white",
      });
      const marker = new AdvancedMarkerElement({
        map,
        position: origin.location,
        content: pin.element,
        title: `Origin: ${origin.displayName}`,
      });
      markers.push(marker);
      bounds.extend(origin.location);
    }
  }

  // Add markers for the destinations.
  for (let i = 0; i < request.destinations.length; i++) {
    const destination = request.destinations[i];
    if (destination.location) {
      const pin = new PinElement({
        //@ts-ignore
        glyphText: "D",
        glyphColor: "white",
        background: "#C5221F",
        borderColor: "white",
      });

      const marker = new AdvancedMarkerElement({
        map,
        position: destination.location,
        content: pin.element,
        title: `Destination: ${destination.displayName}`,
      });

      markers.push(marker);
      bounds.extend(destination.location);
    }
  }

  // Fit the map to the bounds of all markers.
  map.fitBounds(bounds);
}

initMap();

JavaScript

// Initialize and add the map.
let map;
let markers = [];
let center = { lat: 51.55, lng: -1.8 };
async function initMap() {
    //  Request the needed libraries.
    //@ts-ignore
    const [{ Map }, { Place }, { AdvancedMarkerElement, PinElement }, { RouteMatrix }] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes')
    ]);
    const bounds = new google.maps.LatLngBounds();
    map = new Map(document.getElementById('map'), {
        zoom: 8,
        center: center,
        mapId: 'DEMO_MAP_ID',
    });
    // Build the request using Place instances.
    const origin1 = new Place({
        id: "ChIJ83WZp86p2EcRbMrkYqGncBQ", // Greenwich, London, UK
    });
    const origin2 = new Place({
        id: "ChIJCSkVvleJc0gR8HHaTGpajKc", // Southampton, UK
    });
    const destinationA = new Place({
        id: "ChIJYdizgWaDcUgRH9eaSy6y5I4", // Bristol, UK
    });
    const destinationB = new Place({
        id: "ChIJ9VPsNNQCbkgRDmeGZdsGNBQ", // Cardiff, UK
    });
    await Promise.all([
        origin1.fetchFields({ fields: ['location', 'displayName'] }),
        origin2.fetchFields({ fields: ['location', 'displayName'] }),
        destinationA.fetchFields({ fields: ['location', 'displayName'] }),
        destinationB.fetchFields({ fields: ['location', 'displayName'] }),
    ]);
    const request = {
        origins: [origin1, origin2],
        destinations: [destinationA, destinationB],
        travelMode: 'DRIVING',
        units: google.maps.UnitSystem.METRIC,
        fields: ['distanceMeters', 'durationMillis', 'condition'],
    };
    // Show the request.
    document.getElementById("request").innerText =
        JSON.stringify(request, null, 2);
    // Get the RouteMatrix response.
    const response = await RouteMatrix.computeRouteMatrix(request);
    // Show the response.
    document.getElementById("response").innerText =
        JSON.stringify(response, null, 2);
    // Add markers for the origins.
    for (const origin of request.origins) {
        if (origin.location) {
            const pin = new PinElement({
                //@ts-ignore
                glyphText: "O",
                glyphColor: "white",
                background: "#137333",
                borderColor: "white",
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                content: pin.element,
                title: `Origin: ${origin.displayName}`,
            });
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }
    // Add markers for the destinations.
    for (let i = 0; i < request.destinations.length; i++) {
        const destination = request.destinations[i];
        if (destination.location) {
            const pin = new PinElement({
                //@ts-ignore
                glyphText: "D",
                glyphColor: "white",
                background: "#C5221F",
                borderColor: "white",
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: destination.location,
                content: pin.element,
                title: `Destination: ${destination.displayName}`,
            });
            markers.push(marker);
            bounds.extend(destination.location);
        }
    }
    // Fit the map to the bounds of all markers.
    map.fitBounds(bounds);
}
initMap();

सीएसएस

/*
 * Always set the map height explicitly to define the size of the div element
 * that contains the map.
 */
/* Optional: Makes the sample page fill the window. */
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

#container {
  height: 100%;
  display: flex;
}

#sidebar {
  flex-basis: 15rem;
  flex-grow: 1;
  padding: 1rem;
  max-width: 30rem;
  height: 100%;
  box-sizing: border-box;
  overflow: auto;
}

#map {
  flex-basis: 0;
  flex-grow: 4;
  height: 100%;
}

#sidebar {
  flex-direction: column;
}

एचटीएमएल

<html>
  <head>
    <title>Route matrix</title>

    <link rel="stylesheet" type="text/css" href="./style.css" />
    <script type="module" src="./index.js"></script>
  </head>
  <body>
    <div id="container">
      <div id="map"></div>
      <div id="sidebar">
        <h3 style="flex-grow: 0">Request</h3>
        <pre style="flex-grow: 1" id="request"></pre>
        <h3 style="flex-grow: 0">Response</h3>
        <pre style="flex-grow: 1" id="response"></pre>
      </div>
    </div>
    <!-- prettier-ignore -->
    <script>(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})
        ({key: "AIzaSyA6myHzS10YXdcazAFalmXvDkrYCp5cLc8", v: "beta"});</script>
  </body>
</html>

सैंपल आज़माएं

अनुरोध की सीमाएं

computeRouteMatrix तरीके में, पतों या जगहों के इंस्टेंस और आइटम का इस्तेमाल करके वेपॉइंट के लिए अनुरोध की ये सीमाएं लागू होती हैं. आइटम, रूट मैट्रिक्स में मौजूद हर शुरुआती जगह और मंज़िल के बीच के रास्ते होते हैं. इसलिए, आइटम की संख्या, शुरुआती जगहों की संख्या और मंज़िलों की संख्या के गुणनफल के बराबर होती है. उदाहरण के लिए, अगर आपके पास 10 मूल जगहें और 10 मंज़िलें हैं, तो आपके पास 100 आइटम हैं:

  • TRANSIT रूट के अलावा अन्य रूट के लिए, आइटम की संख्या 625 से ज़्यादा नहीं हो सकती.
  • अगर आपने TRANSIT route एट्रिब्यूट की वैल्यू दी है, तो प्रॉडक्ट की संख्या 100 से ज़्यादा नहीं हो सकती.
  • अगर आपने TRAFFIC_AWARE_OPTIMAL तय किया है, तो आइटम की संख्या 100 से ज़्यादा नहीं हो सकती.
  • अगर पतों या जगह के इंस्टेंस का इस्तेमाल करके, मूल जगह या मंज़िलें तय की जाती हैं, तो इस तरीके से ज़्यादा से ज़्यादा 50 मूल जगह या मंज़िलें तय की जा सकती हैं.

ज़्यादा जानकारी के लिए, बस, मेट्रो वगैरह का रास्ता पाना लेख पढ़ें.

रूट मैट्रिक्स के अनुरोध का उदाहरण

यहां ComputeRouteMatrixRequest का उदाहरण दिया गया है. इस उदाहरण में, ये काम किए गए हैं:

  • इसमें, यात्रा शुरू करने की दो जगहों और मंज़िल की दो जगहों के लिए, रास्ते में रुकने की जगहों की जानकारी देने वाली एक ऐरे दिखाई गई है. यह तरीका, हर शुरुआती जगह से हर मंज़िल तक के रास्ते का हिसाब लगाता है. इसलिए, जवाब में चार रास्ते शामिल होते हैं.
    ऐरे में, पहला एलिमेंट इंडेक्स 0 पर होता है, दूसरा इंडेक्स 1 पर होता है, और इसी तरह आगे भी होता है.
  • इससे यह पता चलता है कि कौनसे फ़ील्ड की वैल्यू दिखानी है. इस उदाहरण में, अनुरोध को इस तरह कॉन्फ़िगर किया गया है कि हर रूट के लिए durationMillis, distanceMeters, और condition वैल्यू दिखे.

TypeScript

const request = {
  origins: [origin1, origin2], 
  destinations: [destinationA, destinationB],
  travelMode: 'DRIVING',
  units: google.maps.UnitSystem.METRIC,
  fields: ['distanceMeters', 'durationMillis', 'condition'],
};

JavaScript

const request = {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: 'DRIVING',
    units: google.maps.UnitSystem.METRIC,
    fields: ['distanceMeters', 'durationMillis', 'condition'],
};

जवाब में, सभी शुरुआती और मंज़िल वाले वेपॉइंट के कॉम्बिनेशन के लिए, चार संभावित रास्ते शामिल हैं. जैसा कि यहां दिए गए उदाहरण में दिखाया गया है:

"matrix": {
  "rows": [
    {
      "items": [
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 202587,
          "durationMillis": 10040000
        },
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 252734,
          "durationMillis": 12240000
        }
      ]
    },
    {
      "items": [
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 166135,
          "durationMillis": 6596000
        },
        {
          "condition": "ROUTE_EXISTS",
          "distanceMeters": 216282,
          "durationMillis": 8797000
        }
      ]
    }
  ]
}
    

नतीजे में मौजूद हर रास्ते की पहचान करें. इसके लिए, ऑरिजिन और डेस्टिनेशन इंडेक्स का इस्तेमाल करके, 2D ऐरे में मौजूद RouteMatrixItem ढूंढें. उदाहरण के लिए, अनुरोध में इंडेक्स 1 पर मौजूद शुरुआती जगह और इंडेक्स 0 पर मौजूद मंज़िल से कैलकुलेट किए गए रूट की जानकारी देने वाला RouteMatrixItem, RouteMatrix.rows कलेक्शन के दूसरे एलिमेंट और RouteMatrixRow.items कलेक्शन के पहले एलिमेंट में होगा.

यहां दिए गए कोड स्निपेट से पता चलता है कि किसी खास जगह से दूसरी जगह तक जाने का रास्ता ढूंढने के लिए, RouteMatrixItem की पहचान कैसे की जाती है:

// Find the route for origin 'x' and destination 'y'.
const {matrix} = await RouteMatrix.computeRouteMatrix(request);
const myRouteMatrixItem = matrix.rows[x].items[y];
    

वापस लाने के लिए फ़ील्ड चुनें

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

फ़ील्ड मास्क का इस्तेमाल करने से, यह भी पक्का होता है कि आपने गैर-ज़रूरी डेटा का अनुरोध नहीं किया है. इससे जवाब मिलने में लगने वाले समय को कम करने में मदद मिलती है. साथ ही, यह ऐसी जानकारी को वापस आने से रोकता है जिसकी आपके सिस्टम को ज़रूरत नहीं है.

आपको जिन फ़ील्ड की ज़रूरत है उनकी सूची देने के लिए, ComputeRoutesMatrixRequest.fields प्रॉपर्टी सेट करें. यहां दिए गए स्निपेट में इसका उदाहरण दिया गया है:

fields: ['durationMillis', 'distanceMeters', 'condition'],
    

तय करें कि किन फ़ील्ड मास्क का इस्तेमाल करना है

यहां यह तय करने का तरीका बताया गया है कि आपको किन फ़ील्ड का इस्तेमाल करना है. साथ ही, उनके लिए फ़ील्ड मास्क बनाने का तरीका भी बताया गया है:

  1. ['*'] के फ़ील्ड मास्क का इस्तेमाल करके, सभी फ़ील्ड का अनुरोध करें.
  2. आपको जिन फ़ील्ड की ज़रूरत है उनके लिए, RouteMatrixItem क्लास में फ़ील्ड की हैरारकी देखें.
  3. अपने फ़ील्ड मास्क बनाएं. इसके लिए, पिछले चरण में दिखाए गए फ़ील्ड के क्रम का इस्तेमाल करें. साथ ही, इस फ़ॉर्मैट का इस्तेमाल करें:

    topLevelField[.secondLevelField][.thirdLevelField][...]

उदाहरण के लिए, इस RouteMatrixItem के लिए:

  "travelAdvisory": {
    "fuelConsumptionMicroliters": 0,
    "tollInfo": {
      "estimatedPrices": [
        {
          "currencyCode": "USD",
          "units": 4,
          "nanos": 400000000
        }
      ]
    }
  },
    

अगर आपको RouteMatrixItem के लिए सिर्फ़ tollInfo फ़ील्ड की वैल्यू चाहिए, तो आपका फ़ील्ड मास्क इस तरह होगा:

fields: ['travelAdvisory.tollInfo']

अगर आपको ईंधन की अनुमानित खपत का अनुरोध करना है, तो आपका फ़ील्ड मास्क इस तरह होगा:

fields: ['travelAdvisory.fuelConsumptionMicroliters']

अगर आपको दोनों के लिए अनुरोध करना है, तो आपका फ़ील्ड मास्क इस तरह होगा:

fields: ['travelAdvisory.fuelConsumptionMicroliters', 'travelAdvisory.tollInfo']

अगर आपको यात्रा से जुड़ी पूरी सलाह का अनुरोध करना है, तो आपका फ़ील्ड मास्क इस तरह होगा:

fields: ['travelAdvisory']

सार्वजनिक परिवहन के रूट मैट्रिक्स का अनुरोध करना

किसी इलाके में उपलब्ध सार्वजनिक परिवहन के विकल्पों का इस्तेमाल करके, ट्रांज़िट रूट मैट्रिक्स पाएं. ट्रांज़िट के विकल्पों में बसें, मेट्रो, और ट्रेनें शामिल हो सकती हैं. सार्वजनिक परिवहन के रूट मैट्रिक्स का अनुरोध करने के लिए:

  • travelMode को TRANSIT पर सेट करें
  • travelAdvisory फ़ील्ड के लिए अनुरोध करें.

ट्रांज़िट रूट के बारे में ज़्यादा जानें.