スケジュール設定されたタスク用に JavaScript Consumer SDK をセットアップしたので、コンシューマー アプリで荷物を追跡できるようになりました。このドキュメントでは、このプロセスの次の主な手順について説明します。
- 地図を初期化して共有された経路を表示する
 - ジャーニーの進捗状況を更新してフォローする
 - 配送のフォローを停止する
 - 配送追跡エラーを処理する
 
地図を設定する
ウェブアプリで荷物の集荷または配達を追跡するには、地図を読み込んで Consumer SDK をインスタンス化し、荷物の追跡を開始する必要があります。新しい地図を読み込むことも、既存の地図を使用することもできます。次に、初期化関数を使用して Consumer SDK をインスタンス化し、地図ビューが追跡対象アイテムの位置に対応するようにします。
Google Maps JavaScript API を使用して新しい地図を読み込む
新しい地図を作成するには、ウェブアプリで Google Maps JavaScript API を読み込みます。次の例は、Google Maps JavaScript API を読み込み、SDK を有効にして、初期化チェックをトリガーする方法を示しています。
callbackパラメータは、API の読み込み後に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 で作成された既存の地図(すでに使用している地図など)を読み込むこともできます。
たとえば、次の HTML コードで定義されているマーカーが表示される標準の google.maps.Map エンティティを含むウェブページがあるとします。これにより、最後にコールバックで同じ 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>
配送場所プロバイダをインスタンス化する
配送場所プロバイダと、以前に定義した認証トークン フェッチャーを使用して、Fleet Engine からのデータの受信を開始します。
次の例は、位置情報プロバイダをインスタンス化する方法を示しています。
JavaScript
const locationProvider =
  new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
      projectId: 'your-project-id',
      authTokenFetcher: authTokenFetcher,  // the fetcher defined previously
  });
TypeScript
const locationProvider =
  new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
      projectId: 'your-project-id',
      authTokenFetcher: authTokenFetcher,  // the fetcher defined previously
  });
共有された行程を表示する
スケジュール設定されたタスクの進行状況を表示するには、ビューを初期化します。これにより、地図のフレームが、追跡されたルートの場所に対応するように設定されます。進行状況は、Fleet Engine から情報を取得した後に Consumer SDK によって提供されます。
ヒント:
地図ビューを保持する <div> 要素がページに含まれていることを確認します。次の例では、<div> 要素の名前は
map_canvasです。Fleet Engine が追跡対象の乗車に適用するデフォルトの可視性ルールに注意してください。アクティブな車両配送タスクとスケジュールされた停止タスクの可視性ルールを構成することもできます。タスクを構成するガイドのタスクの可視性をカスタマイズするをご覧ください。
次の例は、地図ビューを初期化する方法を示しています。
JavaScript
function initMap() {
  const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
    element: document.getElementById('map_canvas'),
    // Any undefined styling options use defaults.
  });
  // If you did not specify a tracking ID in the location
  // provider constructor, you may do so here.
  // Location tracking starts as soon as this is set.
  locationProvider.trackingId = 'your-tracking-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 wish.
  mapView.map.setCenter({lat: 37.2, lng: -121.9});
  mapView.map.setZoom(14);
}
TypeScript
function initMap() {
  const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
    element: document.getElementById('map_canvas'),
   // Any undefined styling options will use defaults.
  });
  // If you did not specify a tracking ID in the location
  // provider constructor, you may do so here.
  // Location tracking starts as soon as this is set.
  locationProvider.trackingId = 'your-tracking-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 wish.
  mapView.map.setCenter({lat: 37.2, lng: -121.9});
  mapView.map.setZoom(14);
}
配送状況を更新する
イベントをリッスンし、配送の進行状況に応じてジャーニーの進行状況を更新できます。位置情報プロバイダを使用して、taskTrackingInfo オブジェクトからメタ情報を取得します。メタ情報の変更は、更新イベントをトリガーします。taskTrackingInfo オブジェクトは次の機能を提供します。
- ETA
 - 残りの経由地数
 - 受け取りまたは配達までの残り距離
 
次の例は、これらの変更イベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('update', e => {
  // e.taskTrackingInfo contains data that may be useful
  // to the rest of the UI.
  console.log(e.taskTrackingInfo.remainingStopCount);
});
TypeScript
locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
  // e.taskTrackingInfo contains data that may be useful
  // to the rest of the UI.
  console.log(e.taskTrackingInfo.remainingStopCount);
});
複数のタスクの条件を表示する
スケジュール設定されたタスク用の Consumer SDK では、地図上にトラッキング ID ごとに 1 つのタスクのみが表示されます。ただし、通常は、特定の配送商品に 1 つのトラッキング ID を割り当て、その商品がシステム内で移動する間、その ID が商品に関連付けられたままになります。つまり、1 つの追跡 ID が複数のタスクに関連付けられている可能性があります。たとえば、同じ荷物の集荷タスクと配達タスク、または荷物の配送失敗タスクが複数ある場合などです。
この状況に対処するため、Fleet Engine は次の表に示すタスクの表示条件を適用します。
| タスクの条件 | 結果 | 
|---|---|
| 集荷タスクを開く | |
| 1 つだけ存在する | タスクを表示する | 
| 複数存在する場合 | エラーを生成する | 
| Closed pickup tasks(クローズされた集荷タスク) | |
| 1 つだけ存在する | タスクを表示する | 
| 複数存在(結果時間が設定されているものもある) | 最も新しい結果時刻のタスクを表示する | 
| 複数存在(結果の時間が設定されていない) | エラーを生成する | 
| 配達タスクを開く | |
| 1 つだけ存在する | タスクを表示する | 
| 複数存在する場合 | エラーを生成する | 
| 配達タスクが完了している | |
| 1 つだけ存在する | タスクを表示する | 
| 複数存在(結果時間が設定されているものもある) | 最も新しい結果時刻のタスクを表示する | 
| 複数存在(結果の時間が設定されていない) | エラーを生成する | 
配送のフォローを停止する
配送の過程が完了またはキャンセルされた場合、コンシューマー アプリは、地図ビューからトラッキング ID と位置情報プロバイダを削除して、配送の追跡を停止する必要があります。詳しくは、次のセクションをご覧ください。
トラッキング ID を削除する
配送業者が荷物の追跡を停止するには、配送業者から追跡 ID を削除します。次の例に、その方法を示します。
JavaScript
locationProvider.trackingId = '';
TypeScript
locationProvider.trackingId = '';
マップビューから位置情報プロバイダを削除する
次の例は、地図ビューから位置情報プロバイダを削除する方法を示しています。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
配送追跡エラーを処理する
配送情報のリクエストから非同期で発生するエラーは、error イベントをトリガーします。次の例は、これらのイベントをリッスンしてエラーを処理する方法を示しています。
JavaScript
locationProvider.addListener('error', e => {
  // e.error is the error that triggered the event.
  console.error(e.error);
});
TypeScript
locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error is the error that triggered the event.
  console.error(e.error);
});
注: 予期しないエラーを処理するために、ライブラリ呼び出しを try...catch ブロックでラップしてください。