מעקב אחר נסיעה ב-JavaScript

בחירת פלטפורמה: Android iOS JavaScript

כשאתם משתפים מסלול, אפליקציית הצרכן מציגה את המיקום של את הרכב המתאים לצרכן. כדי לעשות זאת, האפליקציה צריכה להתחיל בשיתוף במסע, לעדכן את ההתקדמות בנסיעה במהלך הנסיעה ולהפסיק לשתף את כשהטיול מסתיים.

במסמך הזה מפורטים השלבים העיקריים הבאים בתהליך הזה:

  1. הגדרת מפה
  2. הפעלת מפה והצגת התהליך המשותף
  3. עדכון ההתקדמות בנסיעה ומעקב אחרי ההתקדמות
  4. הפסקת שיתוף הנסיעות
  5. טיפול בשגיאות בשיתוף של התהליך

הגדרת מפה

כדי לעקוב אחרי איסוף או משלוח באפליקציית האינטרנט שלך, צריך לטעון מפה וליצור את ה-SDK לצרכנים כדי להתחיל לעקוב אחרי התהליך שאתם עוברים. אפשר לטעון במפה חדשה או להשתמש במפה קיימת. לאחר מכן משתמשים באתחול כדי ליצור את ה-SDK לצרכן, כך שתצוגת המפה תואמת של הפריט שעקבו אחריו.

טעינת מפה חדשה באמצעות JavaScript API של מפות Google

כדי ליצור מפה חדשה, צריך לטעון את JavaScript API של מפות Google אל אפליקציית האינטרנט. הדוגמה הבאה מראה איך לטעון את ממשק ה-API של JavaScript של מפות Google, להפעיל את SDK, והפעלה של בדיקת האתחול.

  • הפרמטר callback מריץ את הפונקציה initMap אחרי שה-API נטען.
  • המאפיין defer מאפשר לדפדפן להמשיך לעבד את שאר בזמן שה-API נטען.

שימוש בפונקציה initMap כדי ליצור את ה-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 רגיל שבה מוצג סמן, ניתן להחליף את המפה ולהשאיר את הסמן. בקטע הזה מתוארים השלבים שצריך לבצע כדי לעשות זאת.

כדי להחליף את המפה ולשמור על התאמות אישיות, אפשר להוסיף את האפשרות 'שיתוף הנסיעות' אל בדף ה-HTML באמצעות השלבים האלה, שממוספרים גם הם בדוגמה ככה:

  1. צריך להוסיף קוד למפעל של אסימון האימות.

  2. מפעילים ספק מיקום בפונקציה initMap().

  3. אפשר לאתחל את תצוגת המפה בפונקציה initMap(). התצוגה מכילה את מפה

  4. העברת ההתאמה האישית לפונקציית קריאה חוזרת בתצוגת המפה באתחול.

  5. מוסיפים את ספריית המיקומים לטעינת ה-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 Rideshare 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);
});

המאמרים הבאים

עיצוב מפה