在 JavaScript 中追蹤行程

選取平台: Android iOS JavaScript

追蹤行程時,消費者應用程式會向消費者顯示相應車輛的位置。如要執行這項操作,應用程式必須開始追蹤行程、在行程期間更新旅程進度,並在行程完成時停止追蹤。

本文將說明這個程序中的下列重要步驟:

  1. 設定地圖
  2. 初始化地圖並顯示共用行程
  3. 更新並追蹤行程進度
  4. 停止追蹤行程
  5. 處理行程錯誤

設定地圖

如要在網頁應用程式中追蹤取貨或送貨進度,您必須載入地圖並例項化 Consumer SDK,才能開始追蹤行程。您可以載入新地圖,也可以使用現有地圖。接著,您可以使用初始化函式例項化 Consumer SDK,讓地圖檢視畫面與追蹤項目的位置相符。

使用 Google Maps JavaScript API 載入新地圖

如要建立新地圖,請在網頁應用程式中載入 Google Maps JavaScript API。下列範例說明如何載入 Google Maps JavaScript API、啟用 SDK,以及觸發初始化檢查。

  • API 載入後,callback 參數會執行 initMap 函式。
  • 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 實體和標記,可以替換地圖並保留標記。本節將說明如何執行這些步驟。

如要替換地圖並保留自訂項目,請按照下列步驟將行程分享功能新增至 HTML 網頁。以下範例也標示了步驟編號:

  1. 新增驗證權杖 Factory 的程式碼。

  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 Ridesharing API 的位置資訊供應器。使用專案 ID 和權杖工廠的參照,例項化權杖工廠。

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);
});

停止追蹤行程

行程結束時,您必須停止位置資訊供應器追蹤行程。如要這麼做,請移除行程 ID 和定位服務供應商。如需範例,請參閱以下各節。

從位置資訊供應商移除行程 ID

以下範例說明如何從位置資訊供應器移除行程 ID。

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);
});

後續步驟

設定地圖樣式