รับเมทริกซ์เส้นทาง

นักพัฒนาซอฟต์แวร์ในเขตเศรษฐกิจยุโรป (EEA)

เมทริกซ์เส้นทางคืออาร์เรย์ 2 มิติของข้อมูลเส้นทาง โดยแถวจะสอดคล้องกับ จุดเริ่มต้น และคอลัมน์จะสอดคล้องกับจุดหมาย เมื่อได้รับรายการจุดเริ่มต้นและ จุดหมาย คลาส Route Matrix จะคำนวณระยะทางและระยะเวลาของเส้นทางที่เริ่มต้น จากจุดเริ่มต้นแต่ละจุดและสิ้นสุดที่จุดหมายแต่ละจุด ใช้คลาส 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 จะบังคับใช้ขีดจำกัดของคำขอต่อไปนี้สำหรับจุดอ้างอิงโดยใช้อินสแตนซ์ที่อยู่หรือสถานที่ และสำหรับรายการ รายการคือเส้นทาง ระหว่างจุดเริ่มต้นและจุดหมายแต่ละจุดในเมทริกซ์เส้นทาง ดังนั้นจำนวนรายการจึงเท่ากับจำนวน จุดเริ่มต้นคูณด้วยจำนวนจุดหมาย ตัวอย่างเช่น หากคุณมีจุดเริ่มต้น 10 จุดและจุดหมาย 10 จุด คุณจะมี 100 รายการ ดังนี้

  • จำนวนรายการ ต้องไม่เกิน 625 รายการสำหรับเส้นทางที่ไม่ใช่เส้นทาง TRANSIT
  • หากคุณระบุเส้นทาง TRANSIT จำนวนรายการ ต้องไม่เกิน 100 รายการ
  • หากคุณระบุ TRAFFIC_AWARE_OPTIMAL จำนวนรายการ ต้องไม่เกิน 100 รายการ
  • หากคุณระบุจุดเริ่มต้นหรือจุดหมายโดยใช้ที่อยู่หรืออินสแตนซ์สถานที่ คุณ จะระบุได้ทั้งหมดไม่เกิน 50 รายการด้วยวิธีนี้

ดูรายละเอียดเพิ่มเติมได้ที่รับเส้นทางขนส่งสาธารณะ

ตัวอย่างคำขอเมทริกซ์เส้นทาง

ตัวอย่างต่อไปนี้แสดง ComputeRouteMatrixRequest โดยตัวอย่างนี้ จะทำสิ่งต่อไปนี้

  • แสดงการระบุอาร์เรย์ของจุดอ้างอิงจุดเริ่มต้น 2 จุดและจุดอ้างอิงจุดหมาย 2 จุด เมธอด จะคำนวณเส้นทางจากจุดเริ่มต้นแต่ละจุดไปยังจุดหมายแต่ละจุด ดังนั้นการตอบกลับจึงมีสี่ เส้นทาง
    ในอาร์เรย์ องค์ประกอบแรกจะอยู่ที่ดัชนี 0 องค์ประกอบที่ 2 จะอยู่ที่ดัชนี 1 และอื่นๆ
  • ระบุช่องที่จะแสดงผล ในตัวอย่างนี้ คำขอได้รับการกำหนดค่าให้แสดงผล 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'],
};

การตอบกลับจะมีเส้นทางที่เป็นไปได้ 4 เส้นทางสำหรับชุดค่าผสมของจุดอ้างอิงจุดเริ่มต้นและ จุดอ้างอิงจุดหมายทั้งหมด ดังที่แสดงในตัวอย่างต่อไปนี้

"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 ที่เกี่ยวข้องในอาร์เรย์ 2 มิติ ตัวอย่างเช่น RouteMatrixItem ที่อธิบายเส้นทางที่คำนวณจากจุดเริ่มต้นที่ดัชนี 1 และ จุดหมาย 0 ในคำขอจะอยู่ในองค์ประกอบที่ 2 ของ 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']

หากต้องการขอทั้ง 2 อย่าง ฟิลด์มาสก์จะเป็นดังนี้

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

และหากต้องการขอคำแนะนำการเดินทางทั้งหมด ฟิลด์มาสก์จะเป็นดัง นี้

fields: ['travelAdvisory']

ขอเมทริกซ์เส้นทางขนส่งสาธารณะ

รับเมทริกซ์เส้นทางขนส่งมวลชนที่ใช้ตัวเลือกการขนส่งมวลชนที่มีใน ภูมิภาค ตัวเลือกการขนส่งสาธารณะอาจรวมถึงรถประจำทาง รถไฟใต้ดิน และรถไฟ เป็นต้น วิธีขอเมทริกซ์เส้นทางขนส่งสาธารณะ

  • ตั้งค่า travelMode เป็น TRANSIT
  • ขอช่อง travelAdvisory

ดูข้อมูลเพิ่มเติมเกี่ยวกับเส้นทางขนส่งสาธารณะ