מסלול הוא נתיב שניתן לניווט בין מיקום התחלה, או מוצא, לבין מיקום סיום, או יעד. אתם יכולים לבחור מסלול לאמצעי תחבורה שונים, כמו הליכה, רכיבה על אופניים או סוגים שונים של כלי רכב. אפשר גם לבקש פרטים על המסלול, כמו מרחק, זמן משוער לניווט במסלול, אגרות צפויות והוראות מפורטות לניווט במסלול.
קוד מקור מלא לדוגמה
בדוגמת הקוד הבאה אפשר לראות איך מקבלים מסלול להוראות נסיעה בין שני מיקומים.
TypeScript
// Initialize and add the map. let map; let mapPolylines: google.maps.Polyline[] = []; const center = { lat: 37.447646, lng: -122.113878 }; // Palo Alto, CA // Initialize and add the map. async function initMap(): Promise<void> { // Request the needed libraries. const [{Map}, {Place}, {Route}] = await Promise.all([ google.maps.importLibrary('maps') as Promise<google.maps.MapsLibrary>, google.maps.importLibrary('places') as Promise<google.maps.PlacesLibrary>, //@ts-ignore google.maps.importLibrary('routes') as Promise<google.maps.Routes> ]); map = new Map(document.getElementById("map") as HTMLElement, { zoom: 12, center: 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'], }; // 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. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = {lat: 37.422000, 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'], }; // 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'], }; // 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, fallbackInfo, geocodingResults} = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. 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.setMap(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. fitMapToPath(routes[0].path!); } // Helper function to fit the map to the path. async function fitMapToPath(path) { const { LatLngBounds } = await google.maps.importLibrary('core') as google.maps.CoreLibrary; const bounds = new LatLngBounds(); path.forEach((point) => { bounds.extend(point); }); map.fitBounds(bounds); } initMap();
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 initMap() { // Request the needed libraries. const [{ Map }, { Place }, { Route }] = await Promise.all([ google.maps.importLibrary('maps'), google.maps.importLibrary('places'), //@ts-ignore google.maps.importLibrary('routes') ]); map = new Map(document.getElementById("map"), { zoom: 12, center: 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'], }; // 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. }; // Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, 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'], }; // 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'], }; // 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, fallbackInfo, geocodingResults } = await Route.computeRoutes(request); // Use createPolylines to create polylines for the route. 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.setMap(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. 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); } initMap();
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>
</head>
<body>
<div id="map"></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>דוגמה לניסיון
מתקשרים אל method computeRoutes() כדי לבקש מסלול בין שני מיקומים. בדוגמה הבאה מוגדרת בקשה ואז מופעלת הפונקציה 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);
בחירת שדות להחזרה
כשמבקשים מסלול, צריך להשתמש במסכת שדות כדי לציין איזה מידע צריך להופיע בתשובה. אפשר לציין את השמות של מאפייני מחלקת המסלול במסכת השדות.
שימוש במסכת שדות גם מבטיח שלא תבקשו נתונים מיותרים, וכך תצמצמו את זמן האחזור של התגובה ותימנעו מהחזרת מידע שהמערכת שלכם לא צריכה.
מציינים את רשימת השדות שרוצים להחזיר על ידי הגדרת המאפיין ComputeRoutesRequest.fields, כמו שמוצג בקטע הקוד הבא:
TypeScript
// Define a routes request. const request = { 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. };
ציון מיקומים למסלול
כדי לחשב מסלול, צריך לציין לפחות את המיקומים של נקודת המוצא והיעד של המסלול, ואת מסכת השדות. אפשר גם להגדיר ציוני דרך ביניים לאורך מסלול, ולהשתמש בציוני דרך כדי לבצע פעולות אחרות כמו הוספת עצירות או נקודות מעבר לאורך מסלול.
ב-ComputeRoutesRequest, אפשר לציין מיקום באחת מהדרכים הבאות:
- מקום (מומלץ)
- קואורדינטות של קו הרוחב/קו האורך
- מחרוזת כתובת ("Chicago, IL" או "Darwin, NT, Australia")
- קוד פלוס
אפשר לציין מיקומים לכל נקודות הדרך בבקשה באותו אופן, או לשלב בין האפשרויות. לדוגמה, אפשר להשתמש בקואורדינטות של קו אורך וקו רוחב לנקודת המוצא, ולהשתמש באובייקט Place לנקודת היעד.
כדי לשפר את היעילות והדיוק, מומלץ להשתמש באובייקטים של מקומות במקום בקואורדינטות של קו רוחב/אורך או במחרוזות של כתובות. מזהי מקומות הם ייחודיים וספציפיים, והם מספקים יתרונות בגיאוקודינג לניתוב, כמו נקודות גישה ומשתני תנועה. הם עוזרים להימנע מהמצבים הבאים שיכולים לקרות בשיטות אחרות לציון מיקום:
- שימוש בקואורדינטות של קווי אורך ורוחב עלול לגרום למיקום להיות צמוד לכביש הקרוב ביותר לקואורדינטות האלה – יכול להיות שזה לא יהיה שביל גישה לנכס, או אפילו כביש שמוביל ליעד במהירות או בבטחה.
- לפני ש-Routes API יכול לחשב מסלול, הוא צריך לבצע גיאו-קידוד של מחרוזות כתובות כדי להמיר אותן לקואורדינטות של קווי אורך ורוחב. ההמרה הזו יכולה להשפיע על הביצועים.
ציון מיקום כאובייקט Place (מומלץ)
כדי לציין מיקום באמצעות מקום, יוצרים מופע חדש של Place. בקטע הקוד הבא מוצגת יצירה של מופעי Place חדשים עבור origin ו-destination, ואז שימוש בהם ב-ComputeRoutesRequest:
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 = { 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.422000, 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'], };
JavaScript
// Use lat/lng in a directions request. // Mountain View, CA const originLatLng = { lat: 37.422000, 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).
כשמעבירים מחרוזת של כתובת כמיקום של נקודת ציון, ספריית המסלולים מבצעת גיאו-קידוד של המחרוזת באופן פנימי כדי להמיר אותה לקואורדינטות של קו רוחב וקו אורך.
בקטע הקוד הבא מוצג תהליך יצירת 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 ישתמש בקואורדינטות לא נכונות של קווי אורך ורוחב שקודדו גאוגרפית. לדוגמה, אתם שולחים בקשה שבה מצוין 'טולדו' כנקודת המוצא ו'מדריד' כיעד של מסלול נסיעה:
// Define a request with an incomplete address string. const request = { origin: 'Toledo', destination: 'Madrid', };
בדוגמה הזו, המילה Toledo מתפרשת כעיר במדינת אוהיו בארצות הברית, ולא בספרד. לכן, הבקשה מחזירה מערך ריק, כלומר לא קיימים מסלולים.
אפשר להגדיר את ה-API כך שיחזיר תוצאות שמוטות לטובת אזור מסוים, על ידי הכללת הפרמטר regionCode. הפרמטר הזה מציין את קוד האזור כערך של ccTLD (דומיין ברמה העליונה) באורך שני תווים. רוב קודי ה-ccTLD זהים לקודי ISO 3166-1, אבל יש כמה יוצאים מן הכלל. לדוגמה, ה-ccTLD של בריטניה הוא uk (.co.uk), אבל קוד ISO 3166-1 שלה הוא gb (טכנית, עבור הישות 'ממלכת בריטניה הגדולה וצפון אירלנד').
בקשת מסלול נסיעה מ-Toledo למדריד שכוללת את הפרמטר regionCode מחזירה תוצאות מתאימות כי המערכת מפרשת את Toledo כעיר בספרד:
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
להרבה אנשים אין כתובת מדויקת, ולכן קשה להם לקבל משלוחים. לחלופין, אנשים עם כתובת עשויים להעדיף לקבל משלוחים במיקומים ספציפיים יותר, כמו כניסה אחורית או רציף טעינה.
קודי OLC הם כמו כתובות של רחובות, והם מיועדים לאנשים או למקומות שאין להם כתובת אמיתית. במקום כתובות עם שמות ומספרי רחובות, קודי OLC מבוססים על קואורדינטות של קו רוחב וקו אורך, ומוצגים כמספרים ואותיות.
Google פיתחה את Plus Codes כדי שכולם יוכלו ליהנות מהיתרונות של כתובות. קוד פלוס הוא הפניה מקודדת למיקום, שנגזרת מקואורדינטות של קו רוחב וקו אורך, ומייצגת אזור בגודל של 1/8000 מעלה על 1/8000 מעלה (בערך 14 מ' על 14 מ' בקו המשווה) או קטן יותר. אתם יכולים להשתמש ב-Plus Codes במקום בכתובות של רחובות במקומות שבהם אין כתובות כאלה, או במקומות שבהם הבניינים לא ממוספרים או שהרחובות לא נקראים בשם.
הפורמט של Plus Codes צריך להיות קוד גלובלי או קוד מורכב:
- קוד גלובלי מורכב מקוד אזור בן 4 תווים ומקוד מקומי בן 6 תווים או יותר. לדוגמה, לכתובת "1600 Amphitheatre Parkway, Mountain View, CA", הקוד הגלובלי הוא "849V" והקוד המקומי הוא "CWC8+R9". אחר כך משתמשים ב-OLC המלא בן 10 התווים כדי לציין את ערך המיקום כ-849VCWC8+R9.
- קוד מורכב מורכב מקוד מקומי באורך 6 תווים או יותר, בשילוב עם מיקום מפורש. לדוגמה, הכתובת "450 Serra Mall, Stanford, CA 94305, USA" כוללת קוד מקומי של "CRHJ+C3". אם הכתובת מורכבת, משלבים את הקוד המקומי עם העיר, המדינה, המיקוד והמדינה של הכתובת בצורה "CRHJ+C3 סטנפורד, קליפורניה 94305, ארה"ב".
בקטע הקוד הבא מוצג חישוב של מסלול על ידי ציון נקודת ביניים לנקודת המוצא ולנקודת היעד של המסלול באמצעות Plus Codes:
TypeScript
// 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'], };
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'], };