フリートを表示する

このセクションでは、JavaScript フリート トラッキング ライブラリを使用してフリートを表示する方法について説明します。以下の手順は、フリート トラッキング ライブラリを設定し、地図を読み込んでいることを前提としています。詳しくは、JavaScript フリート トラッキング ライブラリを設定するをご覧ください。

このドキュメントでは、フリートを表示するときにできることについて説明します。

  1. フリートの追跡を開始します
  2. イベントをリッスンしてエラーを処理します
  3. [トラッキングを停止] をタップします。
  4. フリートの表示中に 1 台の車両を追跡する

フリートのトラッキングを開始する

フリートを追跡するには、次のセクションで説明するように、フリート位置情報プロバイダをインスタンス化し、地図のビューポートの位置情報の制限を設定する必要があります。

フリート位置情報プロバイダをインスタンス化する

JavaScript フリート トラッキング ライブラリには、Fleet Engine から複数の車両を取得する位置情報プロバイダが含まれています。

インスタンス化する手順は次のとおりです。

  1. プロジェクト ID とトークン フェッチャーへの参照を使用します。

  2. 車両フィルタ クエリを使用する: 車両フィルタ クエリは、地図に表示する車両を制御します。フィルタは Fleet Engine に渡されます。

  3. 車両ディスプレイの境界領域を設定しますlocationRestriction を使用して、地図上に車両を表示するエリアを制限します。この設定が行われるまで、位置情報プロバイダはアクティブになりません。位置情報の境界は、コンストラクタで設定することも、コンストラクタの後に設定することもできます。

  4. マップビューを初期化します

次の例は、オンデマンド タスクとスケジュール設定されたタスクの両方のシナリオでフリート ロケーション プロバイダをインスタンス化する方法を示しています。これらの例では、コンストラクタで locationRestriction を使用して位置情報プロバイダを有効にする方法も示しています。

オンデマンドのルート

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

スケジュール設定されたタスク

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

コンストラクタの後に locationRestriction を設定するには、次の JavaScript の例に示すように、コードの後半で locationProvider.locationRestriction を追加します。

   // You can choose to not set locationRestriction in the constructor.
   // In this case, the location provider *DOES NOT START* after this line, because
   // no locationRestriction is set.
   locationProvider = new google.maps.journeySharing.DeliveryFleetLocationProvider({
   ... // not setting locationRestriction here
   });

   // You can then set the locationRestriction *after* the constructor.
   // After this line, the location provider is active.
   locationProvider.locationRestriction = {
     north: 1,
     east: 2,
     south: 0,
     west: 1,
   };

地図のビューポートを使用して地域の制限を設定する

locationRestriction の境界を地図ビューに現在表示されている領域に合わせることもできます。

オンデマンドのルート

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

スケジュール設定されたタスク

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

マップビューを初期化する

位置情報プロバイダを構築したら、単一の車両を追跡する場合と同じ方法で地図ビューを初期化します。

JavaScript Journey Sharing ライブラリを読み込んだら、地図ビューを初期化して HTML ページに追加します。ページには、地図ビューを保持する <div> 要素を含める必要があります。次の例では、<div> 要素の名前は map_canvas です。

オンデマンドのルート

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId
                        = 'your-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.VehicleId
                        = 'your-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

スケジュール設定されたタスク

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

イベントをリッスンしてエラーを処理する

フリートのフォローを開始したら、次のセクションで説明するように、イベントの変更をリッスンし、発生したエラーを処理する必要があります。

変更イベントをリッスンする

位置情報プロバイダを使用して、車両オブジェクトからフリートに関するメタ情報を取得できます。メタ情報の変更により、更新イベントがトリガーされます。メタ情報には、ナビゲーションの状態、残り距離、カスタム属性などの車両プロパティが含まれます。

詳細については、以下を参照してください。

次の例は、これらの変更イベントをリッスンする方法を示しています。

オンデマンドのルート

JavaScript

locationProvider.addListener('update', e => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  for (vehicle of e.vehicles) {
    console.log(vehicle.navigationStatus);
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});

スケジュール設定されたタスク

JavaScript

locationProvider.addListener('update', e => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});

エラーをリッスンする

また、車両の追跡中に発生するエラーをリッスンして処理することもできます。車両情報の要求から非同期的に発生するエラーは、エラー イベントをトリガーします。

次の例は、これらのイベントをリッスンしてエラーを処理する方法を示しています。

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

フリートのトラッキングを停止する

フリートの追跡を停止するには、位置情報プロバイダの境界を null に設定し、次のセクションで説明するように、位置情報プロバイダを地図ビューから削除します。

位置情報プロバイダの境界を null に設定する

位置情報プロバイダがフリートの追跡を停止するには、位置情報プロバイダの境界を null に設定します。

オンデマンドのルート

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

スケジュール設定されたタスク

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

マップビューから位置情報プロバイダを削除する

次の例は、地図ビューから位置情報プロバイダを削除する方法を示しています。

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

配送車両を追跡しながら配送車両のフリートを表示する

スケジュール設定されたタスクに Mobility サービスを使用している場合は、フリートを表示し、同じ地図ビューで特定の配送車両のルートと今後のタスクを表示できます。これを行うには、配達フリート位置情報プロバイダと配達車両位置情報プロバイダの両方をインスタンス化し、両方を地図ビューに追加します。インスタンス化されると、配達車両の位置情報プロバイダは地図上に配達車両の表示を開始します。次の例は、両方の位置情報プロバイダをインスタンス化する方法を示しています。

JavaScript

deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});

TypeScript

deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});

マーカーのカスタマイズを使用して配送車両を追跡する

配送車両の位置情報プロバイダが、フリート マーカーをクリックしたときに配送車両を追跡できるようにする手順は次のとおりです。

  1. マーカーをカスタマイズしてクリック アクションを追加します。

  2. マーカーを非表示にして、マーカーの重複を防ぎます。

これらの手順の例については、以降のセクションをご覧ください。

マーカーをカスタマイズしてクリック アクションを追加する

JavaScript

// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };

TypeScript

// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };

マーカーを非表示にして、マーカーの重複を防ぐ

配送車両の位置情報プロバイダからマーカーを非表示にして、同じ車両のマーカーが 2 つ表示されないようにします。

JavaScript

// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };

TypeScript

// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params: deliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };

次のステップ