دریافت ماتریس مسیر

توسعه‌دهندگان منطقه اقتصادی اروپا (EEA)

ماتریس مسیر آرایه‌ای دوبعدی از اطلاعات مسیر است که در آن ردیف‌ها مربوط به مبدأها و ستون‌ها مربوط به مقصدها است. با داشتن فهرستی از مبدأها و مقصدها، کلاس «ماتریس مسیر» مسافت و مدت‌زمان مسیری را که از هر مبدأ شروع می‌شود و به هر مقصد ختم می‌شود محاسبه می‌کند. از کلاس Route Matrix برای محاسبه مسافت و مدت‌زمان مسیر برای چند مبدأ و مقصد استفاده کنید.

مشاهده کد منبع نمونه کامل

این مثال نشان می‌دهد که چگونه از کلاس Route Matrix برای محاسبه فاصله‌ها و مدت‌زمان‌ها برای سفر بین چندین مبدأ و مقصد استفاده کنید.

TypeScript

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

async function init(): Promise<void> {
    //  Request the needed libraries.
    const [
        { Map },
        { Place },
        { AdvancedMarkerElement, PinElement },
        { RouteMatrix },
        { LatLngBounds, UnitSystem },
    ] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes'),
        google.maps.importLibrary('core'),
    ]);

    const bounds = new LatLngBounds();

    map = new Map(document.getElementById('map')!, {
        zoom: 8,
        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 destinations = [destinationA, destinationB];
    const origins = [origin1, origin2];
    const request: google.maps.routes.ComputeRouteMatrixRequest = {
        origins,
        destinations,
        travelMode: 'DRIVING',
        units: 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 origins) {
        if (origin.location) {
            const pin = new PinElement({
                glyphText: 'O',
                glyphColor: 'white',
                background: '#137333',
                borderColor: 'white',
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                title: `Origin: ${origin.displayName}`,
            });
            marker.append(pin);
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }

    // Add markers for the destinations.
    for (const destination of destinations) {
        if (destination.location) {
            const pin = new PinElement({
                glyphText: 'D',
                glyphColor: 'white',
                background: '#C5221F',
                borderColor: 'white',
            });

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

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

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

void init();

JavaScript

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

async function init() {
    //  Request the needed libraries.
    const [
        { Map },
        { Place },
        { AdvancedMarkerElement, PinElement },
        { RouteMatrix },
        { LatLngBounds, UnitSystem },
    ] = await Promise.all([
        google.maps.importLibrary('maps'),
        google.maps.importLibrary('places'),
        google.maps.importLibrary('marker'),
        google.maps.importLibrary('routes'),
        google.maps.importLibrary('core'),
    ]);

    const bounds = new LatLngBounds();

    map = new Map(document.getElementById('map'), {
        zoom: 8,
        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 destinations = [destinationA, destinationB];
    const origins = [origin1, origin2];
    const request = {
        origins,
        destinations,
        travelMode: 'DRIVING',
        units: 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 origins) {
        if (origin.location) {
            const pin = new PinElement({
                glyphText: 'O',
                glyphColor: 'white',
                background: '#137333',
                borderColor: 'white',
            });
            const marker = new AdvancedMarkerElement({
                map,
                position: origin.location,
                title: `Origin: ${origin.displayName}`,
            });
            marker.append(pin);
            markers.push(marker);
            bounds.extend(origin.location);
        }
    }

    // Add markers for the destinations.
    for (const destination of destinations) {
        if (destination.location) {
            const pin = new PinElement({
                glyphText: 'D',
                glyphColor: 'white',
                background: '#C5221F',
                borderColor: 'white',
            });

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

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

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

void init();

CSS

/*
 * 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

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

        <link rel="stylesheet" type="text/css" href="./style.css" />
        <script type="module" src="./index.js"></script>
        <script>
            // prettier-ignore
            (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: "GOOGLE_MAPS_API_KEY"
            });
        </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>
    </body>
</html>

حدود درخواست

روش computeRouteMatrix محدودیت‌های درخواست زیر را برای نقطه‌مسیرها بااستفاده از نمونه‌های نشانی یا «مکان» و برای موارد اعمال می‌کند. موارد همان مسیرهای بین هر مبدأ و مقصد در ماتریس مسیر هستند، بنابراین تعداد موارد برابر است با تعداد مبدأها ضرب در تعداد مقصدها. برای مثال، اگر ۱۰ مبدأ و ۱۰ مقصد داشته باشید، ۱۰۰ مورد دارید:

  • تعداد موارد برای مسیرهایی که مسیرهای TRANSIT نیستند نمی‌تواند از ۶۲۵ بیشتر باشد.
  • اگر TRANSIT مسیر مشخص کنید، تعداد موارد نمی‌تواند از ۱۰۰ بیشتر باشد.
  • اگر TRAFFIC_AWARE_OPTIMAL را مشخص کنید، تعداد موارد نمی‌تواند از ۱۰۰ بیشتر باشد.
  • اگر مبدأ یا مقصد را بااستفاده از نشانی‌ها یا نمونه‌های «مکان» مشخص کنید، می‌توانید حداکثر ۵۰ مورد را به این روش مشخص کنید.

برای جزئیات بیشتر، دریافت مسیر حمل‌ونقل عمومی را ببینید.

نمونه درخواست ماتریس مسیر

مثال زیر ComputeRouteMatrixRequest را نشان می‌دهد. این مثال کارهای زیر را انجام می‌دهد:

  • نمایش تعیین آرایه‌ای از دو نقطه‌مسیر مبدأ و دو نقطه‌مسیر مقصد. این روش مسیری را از هر مبدأ به هر مقصد محاسبه می‌کند، بنابراین پاسخ حاوی چهار مسیر است.
    در آرایه، عنصر اول در نمایه ۰، عنصر دوم در نمایه ۱، و غیره قرار دارد.
  • فیلدهایی را که باید برگردانده شوند مشخص می‌کند. در این مثال، درخواست به‌گونه‌ای پیکربندی شده است که durationMillis، distanceMeters، و condition را برای هر مسیر برگرداند.

TypeScript

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

JavaScript

const destinations = [destinationA, destinationB];
const origins = [origin1, origin2];
const request = {
    origins,
    destinations,
    travelMode: 'DRIVING',
    units: 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
        }
      ]
    }
  ]
}
    

هر مسیر را در نتیجه بااستفاده از نمایه مبدأ و مقصد شناسایی کنید تا RouteMatrixItem مربوطه را در آرایه دوبعدی پیدا کنید. برای مثال، 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
        }
      ]
    }
  },
    

اگر می‌خواهید فقط فیلد tollInfo را برای RouteMatrixItem برگردانید، پوشش فیلد شما به‌صورت زیر است:

fields: ['travelAdvisory.tollInfo']

اگر درعوض می‌خواهید مصرف سوخت تخمینی را درخواست کنید، ماسک فیلد شما به‌صورت زیر است:

fields: ['travelAdvisory.fuelConsumptionMicroliters']

اگر می‌خواهید هر دو را درخواست کنید، پوشش فیلد شما به‌صورت زیر است:

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

و اگر می‌خواهید مجموعه کامل توصیه‌های مسافرتی را درخواست کنید، ماسک فیلد شما به‌صورت زیر است:

fields: ['travelAdvisory']

درخواست ماتریس مسیر حمل‌ونقل عمومی

ماتریس مسیر حمل‌ونقل عمومی را دریافت کنید که از گزینه‌های حمل‌ونقل عمومی دردسترس در منطقه استفاده می‌کند. گزینه‌های حمل‌ونقل عمومی ممکن است شامل اتوبوس، مترو، قطار، و غیره باشد. برای درخواست ماتریس مسیر حمل‌ونقل عمومی:

  • تنظیم کردن travelMode روی TRANSIT
  • فیلد travelAdvisory را درخواست کنید.

درباره مسیرهای حمل‌ونقل عمومی بیشتر بدانید.