מסלול הוא נתיב שאפשר לנווט בו בין מיקום התחלה (או נקודת מוצא) לבין מיקום סיום (או יעד). אתם יכולים לבחור מסלול לאמצעי תחבורה שונים, כמו הליכה, רכיבה על אופניים או סוגים שונים של כלי רכב. אתם יכולים גם לבקש פרטי מסלול כמו מרחק, זמן משוער לניווט במסלול, אגרות צפויות והוראות מפורטות לניווט במסלול.
קוד מקור מלא לדוגמה
דוגמת הקוד הבאה מראה איך לקבל מסלול נסיעה בין שני מיקומים.
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>מפעילים את ה-method computeRoutes() כדי לבקש מסלול בין שני מיקומים. בדוגמה הבאה מוגדרת בקשה ואז מתבצעת קריאה ל-computeRoutes() כדי לקבל מסלול.
computeRoutes() היא שיטה סטטית של המחלקה Route, אז צריך לקרוא ישירות ל-Route.computeRoutes(request). בבקשה צריך גם להגדיר את המאפיין fields למסכת שדה של תגובה.
// 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', fields: ['path'], // Required: response field mask. }; // Call the computeRoutes() method to get routes. const {routes} = await Route.computeRoutes(request);
כדי לשרטט את המסלול במפה, מפעילים את הפונקציה
createPolylines()
במסלול שביקשתם באמצעות השדה path. מידע נוסף זמין במאמר הצגת קווים פוליגוניים במפה.
בחירת השדות שיוחזרו
כששולחים בקשה למסלול, צריך להשתמש במסכת שדות כדי לציין איזה מידע התגובה צריכה להחזיר. אפשר לציין את השמות של המאפיינים של המחלקה Route במסכת השדות.
שימוש במסכת שדות גם מבטיח שלא תבקשו נתונים מיותרים, וכך עוזר לצמצם את זמן האחזור של התגובה ומונע החזרה של מידע שהמערכת שלכם לא צריכה.
מציינים את רשימת השדות שצריך על ידי הגדרת המאפיין 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. };
ציון מיקומים במסלול
כדי לחשב מסלול, צריך לציין לפחות את המיקומים של נקודת המוצא ונקודת היעד של המסלול, ומסכת שדות. אפשר גם לציין נקודות ציון לאורך המסלול, ולהשתמש בהן כדי לבצע פעולות אחרות כמו הוספת עצירות או נקודות מעבר לאורך המסלול.
בComputeRoutesRequest, אפשר לציין מיקום בכל אחת מהדרכים הבאות:
- מקום (מועדף)
- קואורדינטות של קו הרוחב/קו האורך
- מחרוזת כתובת ("Chicago, IL" או "Darwin, NT, Australia")
- Plus Code
אתם יכולים לציין מיקומים לכל נקודות הדרך בבקשה באותו אופן, או לשלב ביניהם. לדוגמה, אפשר להשתמש בקואורדינטות של קו רוחב/קו אורך לנקודת הציון של המוצא, ולהשתמש באובייקט Place לנקודת הציון של היעד.
כדי לשפר את היעילות והדיוק, כדאי להשתמש באובייקטים מסוג 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: 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"). המרת כתובות לקואורדינטות (geocoding) היא תהליך של המרת מחרוזת כתובת לקואורדינטות של קווי רוחב ואורך (למשל, קו רוחב 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 ישתמש בקואורדינטות שגויות של קווי אורך ורוחב. לדוגמה, אתם שולחים בקשה שבה מציינים את "Toledo" כנקודת המוצא ואת "Madrid" כיעד למסלול נסיעה:
// 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" (מבחינה טכנית, עבור הישות "הממלכה המאוחדת של בריטניה הגדולה וצפון אירלנד").
בקשה לקבלת מסלול מ "טולדו" ל "מדריד" שכוללת את הפרמטר regionCode מחזירה תוצאות מתאימות, כי "טולדו" מפורשת כעיר בספרד:
const request = { origin: 'Toledo', destination: 'Madrid', region: 'es', // Specify the region code for Spain. };
Plus Code
להרבה אנשים אין כתובת מדויקת, ולכן קשה להם לקבל משלוחים. או שאנשים עם כתובת יעדיפו לקבל משלוחים במיקומים ספציפיים יותר, כמו כניסה אחורית או רציף טעינה.
Plus Codes הם כמו כתובות רחוב של אנשים או מקומות שאין להם כתובת אמיתית. במקום כתובות עם שמות רחובות ומספרי בתים, קודי Plus Code מבוססים על קואורדינטות של קווי רוחב ואורך, ומוצגים כמספרים ואותיות.
Google פיתחה את Plus Codes כדי שכולם יוכלו ליהנות מהיתרונות של כתובות. Plus Code הוא הפניה מקודדת למיקום, שנגזרת מקואורדינטות של קו רוחב/קו אורך ומייצגת אזור: 1/8,000 של מעלה על 1/8,000 של מעלה (בערך 14 מ' על 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'], };