เส้นทางคือเส้นทางที่นำทางได้ระหว่างสถานที่เริ่มต้นหรือต้นทางกับสถานที่สิ้นสุด สถานที่หรือปลายทาง คุณสามารถเลือกรับเส้นทางสำหรับการเดินทางด้วยโหมดต่างๆ เช่น การเดิน การปั่นจักรยาน หรือยานพาหนะประเภทต่างๆ นอกจากนี้ คุณยังขอรายละเอียดเส้นทาง เช่น ระยะทาง เวลาโดยประมาณในการเดินทางตามเส้นทาง ค่าผ่านทางที่คาดไว้ และวิธีการทีละขั้นตอนในการเดินทางตามเส้นทางได้ด้วย
ดูซอร์สโค้ดตัวอย่างฉบับเต็ม
ตัวอย่างโค้ดต่อไปนี้แสดงวิธีรับเส้นทางสำหรับการขับรถระหว่างสถานที่ 2 แห่ง
TypeScript
// Initialize and add the map. let map: google.maps.Map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function init(): Promise<void> { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map')!, { zoom: 12, center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; console.log({ requestWithAddressStrings }); // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; console.log({ requestWithPlaceIds }); // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; console.log({ requestWithLatLngs }); // Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; console.log({ requestWithPlusCodes }); // Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => { polyline.setMap(map); }); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => { marker.map = map; }); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. void fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path: google.maps.LatLngLiteral[]) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } void init();
JavaScript
// Initialize and add the map. let map; let mapPolylines = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function init() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), google.maps.importLibrary('routes'), ]); map = new Map(document.getElementById('map'), { zoom: 12, center, mapTypeControl: false, mapId: 'DEMO_MAP_ID', }); // Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], }; console.log({ requestWithAddressStrings }); // Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. }; console.log({ requestWithPlaceIds }); // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], }; console.log({ requestWithLatLngs }); // Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], }; console.log({ requestWithPlusCodes }); // Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. }; // Call computeRoutes to get the directions. const { routes } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. if (!routes) { console.warn('No routes found.'); return; } mapPolylines = routes[0].createPolylines(); // Add polylines to the map. mapPolylines.forEach((polyline) => { polyline.setMap(map); }); // Create markers to start and end points. const markers = await routes[0].createWaypointAdvancedMarkers(); // Add markers to the map markers.forEach((marker) => { marker.map = map; }); // Display the raw JSON for the result in the console. console.log(`Response:\n ${JSON.stringify(routes, null, 2)}`); // Fit the map to the path. void fitMapToPath(routes[0].path); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core'); const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } void init();
CSS
/* * Always set the map height explicitly to define the size of the div element * that contains the map. */ #map { height: 100%; } /* * Optional: Makes the sample page fill the window. */ html, body { height: 100%; margin: 0; padding: 0; }
HTML
<html>
<head>
<title>Get directions</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="map"></div>
</body>
</html>เรียกใช้เมธอด computeRoutes()
เพื่อขอเส้นทางระหว่างสถานที่ 2 แห่ง ตัวอย่างต่อไปนี้แสดงการกำหนดa
คำขอ แล้วเรียกใช้ computeRoutes() เพื่อรับเส้นทาง
// Import the Routes library. const { Route } = await google.maps.importLibrary('routes'); // Define a computeRoutes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
เลือกช่องที่จะแสดงผล
เมื่อขอเส้นทาง คุณต้องใช้ Field Mask เพื่อระบุข้อมูลที่การตอบกลับ ควรแสดงผล คุณสามารถระบุชื่อพร็อพเพอร์ตี้ของคลาส Route ใน Field Mask ได้
การใช้ Field Mask ยังช่วยให้คุณไม่ขอข้อมูลที่ไม่จำเป็น ซึ่งจะช่วยลดเวลาในการตอบสนองและหลีกเลี่ยงการแสดงผลข้อมูลที่ระบบไม่ต้องการ
ระบุรายการช่องที่ต้องการโดยตั้งค่า
ComputeRoutesRequest.fields
พร็อพเพอร์ตี้ ดังที่แสดงในข้อมูลโค้ดต่อไปนี้
TypeScript
// Define a routes request. const request: google.maps.routes.ComputeRoutesRequest = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Define a routes request. const request = { origin: 'Mountain View, CA', destination: 'San Francisco, CA', travelMode: 'DRIVING', fields: ['path'], // Request fields needed to draw polylines. };
ระบุสถานที่สำหรับเส้นทาง
หากต้องการคำนวณเส้นทาง คุณต้องระบุสถานที่ต้นทางและ ปลายทางของเส้นทาง รวมถึง Field Mask เป็นอย่างน้อย นอกจากนี้ คุณยังระบุจุดแวะพักระหว่างทางตามเส้นทาง และใช้จุดแวะพักเพื่อทำสิ่งอื่นๆ เช่น การเพิ่มจุดแวะพักหรือจุดผ่านตามเส้นทางได้ด้วย
ใน ComputeRoutesRequest คุณสามารถระบุสถานที่ได้ด้วยวิธีใดวิธีหนึ่งต่อไปนี้
- สถานที่ (แนะนำ)
- พิกัดละติจูด/ลองจิจูด
- สตริงที่อยู่ ("Chicago, IL" หรือ "Darwin, NT, Australia")
- Plus Code
คุณสามารถระบุสถานที่สำหรับจุดแวะพักทั้งหมดในคำขอด้วยวิธีเดียวกัน หรือจะระบุสถานที่แบบผสมกันก็ได้ เช่น คุณสามารถใช้พิกัดละติจูด/ลองจิจูดสำหรับจุดอ้างอิงต้นทาง และใช้ออบเจ็กต์สถานที่สำหรับจุดอ้างอิงปลายทาง
ใช้ Place Object แทนพิกัดละติจูด/ลองจิจูดหรือ สตริงที่อยู่เพื่อประสิทธิภาพและความถูกต้อง Place ID มีความชัดเจนและไม่ซ้ำกัน รวมถึงให้ประโยชน์ในการเข้ารหัสพิกัดภูมิศาสตร์สำหรับการกำหนดเส้นทาง เช่น จุดเข้าถึงและตัวแปรการจราจร ซึ่งช่วยหลีกเลี่ยงสถานการณ์ต่อไปนี้ที่ อาจเกิดขึ้นจากการระบุสถานที่ด้วยวิธีอื่นๆ
- การใช้พิกัดละติจูด/ลองจิจูดอาจทำให้สถานที่ถูกปักหมุดไว้บนถนน ที่ใกล้กับพิกัดเหล่านั้นมากที่สุด ซึ่งอาจไม่ใช่จุดเข้าถึงที่พัก หรือแม้แต่ ถนนที่นำไปสู่ปลายทางได้อย่างรวดเร็วหรือปลอดภัย
- Routes API ต้องเข้ารหัสพิกัดภูมิศาสตร์สตริงที่อยู่ก่อนเพื่อแปลงเป็น พิกัดละติจูด/ลองจิจูด จึงจะคำนวณเส้นทางได้ การแปลงนี้อาจส่งผลต่อ ประสิทธิภาพ
ระบุสถานที่เป็น Place Object (แนะนำ)
หากต้องการระบุสถานที่โดยใช้สถานที่ ให้สร้างอินสแตนซ์ Place ใหม่ ข้อมูลโค้ดต่อไปนี้แสดงการสร้างอินสแตนซ์ใหม่สำหรับและแล้วใช้ในPlaceorigindestinationComputeRoutesRequest
TypeScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds: google.maps.routes.ComputeRoutesRequest = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
JavaScript
// Use Place IDs in a directions request. const originPlaceInstance = new Place({ id: 'ChIJiQHsW0m3j4ARm69rRkrUF3w', // Mountain View, CA }); const destinationPlaceInstance = new Place({ id: 'ChIJIQBpAG2ahYAR_6128GcTUEo', // San Francisco, CA }); const requestWithPlaceIds = { origin: originPlaceInstance, destination: destinationPlaceInstance, fields: ['path'], // Request fields needed to draw polylines. };
พิกัดละติจูด/ลองจิจูด
หากต้องการระบุสถานที่เป็นพิกัดละติจูด/ลองจิจูด ให้สร้างอินสแตนซ์ใหม่
google.maps.LatLngLiteral, google.maps.LatLngAltitude, หรือ
google.maps.LatLngAltitudeLiteral ข้อมูลโค้ดต่อไปนี้แสดงการสร้าง
อินสแตนซ์ใหม่google.maps.LatLngLiteralสำหรับ origin และ destination,
แล้วใช้ใน computeRoutesRequest:
TypeScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs: google.maps.routes.ComputeRoutesRequest = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422, lng: -122.084058 }; // San Francisco, CA const destinationLatLng = { lat: 37.774929, lng: -122.419415 }; // Define a computeRoutes request. const requestWithLatLngs = { origin: originLatLng, destination: destinationLatLng, fields: ['path'], };
สตริงที่อยู่
สตริงที่อยู่คือที่อยู่ที่แท้จริงซึ่งแสดงด้วยสตริง (เช่น "1600 Amphitheatre Parkway, Mountain View, CA") การเข้ารหัสพิกัดภูมิศาสตร์คือกระบวนการแปลงสตริงที่อยู่เป็น ละติจูดและลองจิจูด (เช่น ละติจูด 37.423021 และลองจิจูด -122.083739)
เมื่อส่งสตริงที่อยู่เป็นสถานที่ของจุดแวะพัก ไลบรารี Routes เข้ารหัสพิกัดภูมิศาสตร์สตริงภายในเพื่อแปลงเป็นพิกัดละติจูดและลองจิจูด
ข้อมูลโค้ดต่อไปนี้แสดงการสร้าง ComputeRoutesRequest ที่มีสตริงที่อยู่สำหรับ origin และ destination:
TypeScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
JavaScript
// Use address strings in a directions request. const requestWithAddressStrings = { origin: '1600 Amphitheatre Parkway, Mountain View, CA', destination: '345 Spear Street, San Francisco, CA', fields: ['path'], };
ตั้งค่าภูมิภาคสำหรับที่อยู่
หากคุณส่งสตริงที่อยู่ที่ไม่สมบูรณ์เป็นสถานที่ของจุดแวะพัก API อาจใช้ พิกัดละติจูด/ลองจิจูดที่เข้ารหัสพิกัดภูมิศาสตร์ไม่ถูกต้อง ตัวอย่างเช่น คุณส่งคำขอที่ระบุ "Toledo" เป็นต้นทางและ "Madrid" เป็นปลายทางสำหรับเส้นทางการขับรถ
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
ในตัวอย่างนี้ ระบบจะตีความ "Toledo" เป็นเมืองในรัฐโอไฮโอของสหรัฐอเมริกา ไม่ใช่ในสเปน ดังนั้น คำขอจะแสดงผลอาร์เรย์ว่างเปล่า ซึ่งหมายความว่าไม่มีเส้นทาง
คุณสามารถกำหนดค่า API ให้แสดงผลลัพธ์ที่ให้น้ำหนักพิเศษกับบางภูมิภาคได้โดยใส่พารามิเตอร์ regionCode พารามิเตอร์นี้จะระบุรหัสภูมิภาคเป็นค่า ccTLD ("โดเมนระดับบนสุด") แบบ 2 ตัวอักษร รหัส ccTLD ส่วนใหญ่จะเหมือนกับรหัส ISO 3166-1 ยกเว้นบางรายการ เช่น ccTLD ของสหราชอาณาจักรคือ "uk" (.co.uk) ขณะที่รหัส ISO 3166-1 code คือ "gb" (ในทางเทคนิคแล้วคือสำหรับหน่วยงาน "สหราชอาณาจักรบริเตนใหญ่และไอร์แลนด์เหนือ" )
คำขอเส้นทางจาก "Toledo" ไป "Madrid" ที่มีพารามิเตอร์ regionCode จะแสดงผลลัพธ์ที่เหมาะสม เนื่องจากระบบจะตีความ "Toledo" เป็นเมืองในสเปน
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
หลายคนไม่มีที่อยู่ที่แน่นอน ซึ่งอาจทำให้รับ พัสดุได้ยาก หรือบางคนที่มีที่อยู่อาจต้องการรับพัสดุในสถานที่ที่เฉพาะเจาะจงมากขึ้น เช่น ประตูหลังหรือท่าเทียบเรือ
Plus Codes เป็นเหมือนที่อยู่ของผู้คนหรือสถานที่ซึ่งไม่มีที่อยู่อย่างเป็นทางการ Plus Codes ไม่ใช่ข้อมูลที่อยู่ที่ประกอบด้วยชื่อถนนและบ้านเลขที่ แต่จะเป็นชุดตัวเลขและตัวอักษรที่สร้างขึ้นโดยอิงจากพิกัดละติจูด/ลองจิจูด
Google พัฒนา Plus Codes ขึ้นเพื่อให้ทุกคนและทุกสิ่งได้รับประโยชน์จากที่อยู่ Plus Code คือข้อมูลอ้างอิงสถานที่ที่เข้ารหัส ซึ่งได้มาจากพิกัดละติจูด/ลองจิจูด และแสดงถึงพื้นที่ขนาด 1/8000 องศา x 1/8000 องศา (ประมาณ 14 ม. x 14 ม. ที่เส้นศูนย์สูตร) หรือเล็กกว่า คุณ สามารถใช้ Plus Codes แทนที่อยู่ได้ในสถานที่ที่ไม่มีที่อยู่ หรือ สถานที่ที่ไม่มีการระบุหมายเลขอาคารหรือชื่อถนน
Plus Codes ต้องจัดรูปแบบเป็นรหัสสากลหรือรหัสผสม
- รหัสสากล ประกอบด้วยรหัสพื้นที่ 4 หลักและรหัสท้องถิ่น 6 หลักขึ้นไป ตัวอย่างเช่น สำหรับที่อยู่ "1600 Amphitheatre Parkway, Mountain View, CA" รหัสสากลคือ "849V" และรหัสท้องถิ่นคือ "CWC8+R9" จากนั้นใช้ Plus Code ทั้งหมด 10 หลัก เพื่อระบุค่าสถานที่เป็น "849VCWC8+R9"
- รหัสผสม ประกอบด้วยรหัสท้องถิ่น 6 หลักขึ้นไปที่รวมกับ สถานที่ที่ชัดเจน ตัวอย่างเช่น ที่อยู่ "450 Serra Mall, Stanford, CA 94305, USA" มีรหัสท้องถิ่นเป็น "CRHJ+C3" สำหรับที่อยู่แบบผสม ให้รวมรหัสท้องถิ่นกับส่วนเมือง รัฐ/จังหวัด รหัสไปรษณีย์ และประเทศของที่อยู่ในรูปแบบ "CRHJ+C3 Stanford, CA 94305, USA"
ข้อมูลโค้ดต่อไปนี้แสดงการคำนวณเส้นทางโดยการระบุจุดอ้างอิงสำหรับต้นทางและปลายทางของเส้นทางโดยใช้ Plus Codes:
TypeScript
// Use Plus Codes in a directions request. const requestWithPlusCodes: google.maps.routes.ComputeRoutesRequest = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };
JavaScript
// Use Plus Codes in a directions request. const requestWithPlusCodes = { origin: '849VCWC8+R9', // Mountain View, CA destination: 'CRHJ+C3 Stanford, CA 94305, USA', // Stanford, CA fields: ['path'], };