כשעוקבים אחרי נסיעה, מיקום הרכב הרלוונטי מוצג לצרכן באפליקציה לצרכן. כדי לעשות את זה, האפליקציה צריכה להתחיל לעקוב אחרי הנסיעה, לעדכן את התקדמות הנסיעה במהלך הנסיעה ולהפסיק לעקוב אחרי הנסיעה כשהיא מסתיימת.
במסמך הזה מפורטים השלבים העיקריים בתהליך:
- הגדרת מפה
- הפעלת מפה והצגת פרטי הנסיעה ששותפו
- עדכון ומעקב אחרי התקדמות הנסיעה
- הפסקת המעקב אחרי נסיעה
- טיפול בשגיאות בנסיעות
הגדרת מפה
כדי לעקוב אחרי איסוף או משלוח של חבילה באפליקציית האינטרנט, צריך לטעון מפה וליצור מופע של Consumer SDK כדי להתחיל לעקוב אחרי המסלול. אפשר לטעון מפה חדשה או להשתמש במפה קיימת. לאחר מכן משתמשים בפונקציית האתחול כדי ליצור מופע של Consumer SDK, כך שתצוגת המפה תתאים למיקום של הפריט שעוקבים אחריו.
טעינת מפה חדשה באמצעות Google Maps JavaScript API
כדי ליצור מפה חדשה, טוענים את Google Maps JavaScript API באפליקציית האינטרנט. בדוגמה הבאה מוצגות הפעולות הנדרשות לטעינת Google Maps JavaScript API, להפעלת ה-SDK ולהפעלת בדיקת האתחול.
- הפרמטר
callback
מריץ את הפונקציהinitMap
אחרי שה-API נטען. - מאפיין
defer
מאפשר לדפדפן להמשיך לעבד את שאר הדף בזמן שה-API נטען.
משתמשים בפונקציה initMap
כדי ליצור מופע של Consumer SDK. לדוגמה:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
טעינת מפה קיימת
אפשר גם לטעון מפה קיימת שנוצרה באמצעות Google Maps JavaScript API, למשל מפה שכבר נמצאת בשימוש.
לדוגמה, נניח שיש לכם דף אינטרנט עם google.maps.Map
ישות רגילה שמוצג עליה סמן כמו שמוגדר בקוד ה-HTML הבא. כך נראית המפה באמצעות אותה פונקציית initMap
בקריאה החוזרת בסוף:
<!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<!--The div element for the map -->
<div id="map"></div>
<script>
// Initialize and add the map
function initMap() {
// The location of Pier 39 in San Francisco
var pier39 = {lat: 37.809326, lng: -122.409981};
// The map, initially centered at Mountain View, CA.
var map = new google.maps.Map(document.getElementById('map'));
map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
// The marker, now positioned at Pier 39
var marker = new google.maps.Marker({position: pier39, map: map});
}
</script>
<!-- Load the API from the specified URL.
* The defer attribute allows the browser to render the page while the API loads.
* The key parameter contains your own API key.
* The callback parameter executes the initMap() function.
-->
<script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</body>
</html>
החלפת מפה קיימת
אתם יכולים להחליף מפה קיימת שכוללת סמנים או התאמות אישיות אחרות בלי לאבד את ההתאמות האישיות האלה.
לדוגמה, אם יש לכם דף אינטרנט עם google.maps.Map
entity רגיל שמוצג עליו סמן, אתם יכולים להחליף את המפה ולהשאיר את הסמן. בקטע הזה מוסבר איך עושים את זה.
כדי להחליף את המפה ולשמור על ההתאמות האישיות, צריך להוסיף את שיתוף הנסיעה לדף ה-HTML באמצעות השלבים הבאים, שממוספרים גם בדוגמה שבהמשך:
מוסיפים קוד למפעל של אסימוני האימות.
מאתחלים ספק מיקום בפונקציה
initMap()
.מאתחלים את תצוגת המפה בפונקציה
initMap()
. התצוגה מכילה את המפה.מעבירים את ההתאמה האישית לפונקציית הקריאה החוזרת של אתחול תצוגת המפה.
מוסיפים את ספריית המיקומים לטוען ה-API.
בדוגמה הבאה אפשר לראות את השינויים שצריך לבצע. אם מפעילים נסיעה עם המזהה שצוין ליד אולורו, הנסיעה תוצג עכשיו במפה:
<!DOCTYPE html>
<html>
<head>
<style>
/* Set the size of the div element that contains the map */
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<!--The div element for the map -->
<div id="map"></div>
<script>
let locationProvider;
// (1) Authentication Token Fetcher
async function authTokenFetcher(options) {
// options is a record containing two keys called
// serviceType and context. The developer should
// generate the correct SERVER_TOKEN_URL and request
// based on the values of these fields.
const response = await fetch(SERVER_TOKEN_URL);
if (!response.ok) {
throw new Error(response.statusText);
}
const data = await response.json();
return {
token: data.Token,
expiresInSeconds: data.ExpiresInSeconds
};
}
// Initialize and add the map
function initMap() {
// (2) Initialize location provider.
locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
projectId: "YOUR_PROVIDER_ID",
authTokenFetcher,
});
// (3) Initialize map view (which contains the map).
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map'),
locationProviders: [locationProvider],
// any styling options
});
locationProvider.tripId = TRIP_ID;
// (4) Add customizations like before.
// The location of Pier 39 in San Francisco
var pier39 = {lat: 37.809326, lng: -122.409981};
// The map, initially centered at Mountain View, CA.
var map = new google.maps.Map(document.getElementById('map'));
map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
// The marker, now positioned at Pier 39
var marker = new google.maps.Marker({position: pier39, map: map});
};
</script>
<!-- Load the API from the specified URL
* The async attribute allows the browser to render the page while the API loads
* The key parameter will contain your own API key (which is not needed for this tutorial)
* The callback parameter executes the initMap() function
*
* (5) Add the SDK to the API loader.
-->
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
</script>
</body>
</html>
איך מאתחלים מפה ומציגים את התקדמות הנסיעה
כשנסיעה מתחילה, האפליקציה צריכה ליצור מופע של ספק מיקום נסיעה ואז לאתחל מפה כדי להתחיל לשתף את התקדמות הנסיעה. דוגמאות מפורטות בקטעים הבאים.
יצירת מופע של ספק מיקום של נסיעה
ל-JavaScript SDK יש ספק מיקום מוגדר מראש עבור Fleet Engine Ridesharing API. משתמשים במזהה הפרויקט ובהפניה למפעל האסימונים כדי ליצור מופע שלו.
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
הפעלת תצוגת המפה
אחרי טעינת JavaScript SDK, מאתחלים את תצוגת המפה ומוסיפים אותה לדף ה-HTML. הדף צריך להכיל רכיב <div>
שמכיל את תצוגת המפה. בדוגמה הבאה, שם הרכיב <div>
הוא map_canvas
.
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise, the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise, the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
עדכון ומעקב אחרי התקדמות הנסיעה
האפליקציה צריכה להאזין לאירועים ולעדכן את התקדמות הנסיעה בזמן שהנסיעה מתקדמת. אפשר לאחזר מידע מטא על נסיעה מאובייקט המשימה באמצעות ספק המיקום. המידע במטא-נתונים כולל את זמן ההגעה המשוער ואת המרחק שנותר עד לאיסוף או להורדה. שינויים במידע המטא מפעילים אירוע עדכון. בדוגמה הבאה אפשר לראות איך להאזין לאירועי השינוי האלה.
JavaScript
locationProvider.addListener('update', e => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
TypeScript
locationProvider.addListener('update', (e:
google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
הפסקת המעקב אחרי נסיעה
בסיום הנסיעה, צריך להפסיק את המעקב אחרי הנסיעה אצל ספק המיקום. כדי לעשות זאת, מסירים את מזהה הנסיעה ואת ספק המיקום. דוגמאות מופיעות בקטעים הבאים.
הסרת מזהה הנסיעה מספק המיקום
בדוגמה הבאה מוצג איך מסירים מזהה נסיעה מספק המיקום.
JavaScript
locationProvider.tripId = '';
TypeScript
locationProvider.tripId = '';
הסרת ספק המיקום מתצוגת המפה
בדוגמה הבאה מוצג איך מסירים ספק מיקום מתצוגת המפה.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
טיפול בשגיאות בנסיעות
שגיאות שמתרחשות באופן אסינכרוני מבקשת פרטי הנסיעה מפעילות אירועי שגיאה. בדוגמה הבאה אפשר לראות איך להאזין לאירועים האלה כדי לטפל בשגיאות.
JavaScript
locationProvider.addListener('error', e => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});
TypeScript
locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});