JavaScript フリート トラッキング ライブラリを使用してフリートを追跡

JavaScript Fleet Tracking Library を使用すると、フリート内の車両の位置をほぼリアルタイムで可視化できます。このライブラリでは、Deliveries API を使用して、配達車両とタスクを可視化しています。JavaScript 配送トラッキング ライブラリと同様に、このライブラリには Fleet Engine に接続するための標準の google.maps.Map エンティティとデータ コンポーネントの代わりに使用できる JavaScript マップ コンポーネントが含まれています。

コンポーネント

JavaScript Fleet Tracking Library は、配達車両と停車地を可視化するためのコンポーネントと、到着予定時刻や配達までの距離の元データフィードを提供します。

フリート トラッキングの地図表示

Fleet Tracking の地図表示コンポーネントは、車両とタスクの位置情報を可視化します。車両のルートがわかっている場合、地図表示コンポーネントでは、車両が予測された経路に沿って移動するにつれて、その車両がアニメーション表示されます。

フリート トラッキングの地図表示の例

位置情報プロバイダ

位置情報プロバイダは Fleet Engine に保存された情報を使用して、追跡対象オブジェクトの位置情報をジャーニー共有マップに送信します。

配達車両位置情報プロバイダ

配達車両位置情報プロバイダは、1 つの配達車両の位置情報を表示します。車両の場所と配達車両によって完了したタスクに関する情報が含まれています。

配達フリート位置情報プロバイダ

配達車両位置情報プロバイダは、複数の車両の位置情報を表示します。特定の車両や場所でフィルタすることも、フリート全体を表示することもできます。

追跡中の場所の公開設定を管理します

このセクションでは、Fleet Engine の事前定義された位置情報プロバイダの地図上の追跡対象位置情報オブジェクトの公開設定ルールについて説明します。カスタムまたは派生の位置情報プロバイダが公開設定ルールを変更することがあります。

配達車両

配達車両は、Fleet Engine で作成されるとすぐに表示され、タスクに関係なくルート全体に表示されます。

タスクの場所マーカー

予定されている車両の停車場所は、車両の停車場所マーカーとして地図上に表示されます。完了したタスクのマーカーは、車両の計画されている停車地とは異なるスタイルで表示されます。

タスク結果の場所は、タスク結果マーカーとともに表示されます。結果が SUCCEEDED のタスクは成功したタスクマーカーとともに表示され、他のすべてのタスクは失敗したタスクマーカーとともに表示されます。

JavaScript フリート トラッキング ライブラリを使ってみる

JavaScript Fleet Tracking Library を使用する前に、Fleet Engine と API キーの取得について理解しておいてください。次に、タスク ID と配達用車両 ID の申し立てを作成します。

タスク ID と配達用車両 ID の申請を作成する

配達車両位置情報プロバイダを使用して配達車両を追跡するには、タスク ID と配達車両 ID クレームを含む JSON Web Token(JWT)を作成します。

JWT ペイロードを作成するには、taskiddeliveryvehicleid キーを使用して承認セクションにクレームを追加し、各キーの値を * に設定します。トークンは Fleet Engine サービス スーパー ユーザーの Cloud IAM ロールを使用して作成する必要があります。これにより、Fleet Engine エンティティを作成、読み取り、変更するための幅広いアクセス権が付与されるため、信頼できるユーザーとのみ共有する必要があります。

次の例は、車両とタスクごとにトラッキングするためのトークンを作成する方法を示しています。

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "private_key_id_of_consumer_service_account"
}
.
{
  "iss": "superuser@yourgcpproject.iam.gserviceaccount.com",
  "sub": "superuser@yourgcpproject.iam.gserviceaccount.com",
  "aud": "https://fleetengine.googleapis.com/",
  "iat": 1511900000,
  "exp": 1511903600,
  "scope": "https://www.googleapis.com/auth/xapi",
  "authorization": {
     "taskid": "*",
     "deliveryvehicleid": "*",
   }
}

認証トークン フェッチャーを作成する

認証トークン フェッチャーを作成すると、プロジェクトのサービス アカウント証明書を使用して、サーバー上で適切なクレームで作成されたトークンを取得できます。トークンはサーバー上でのみ作成し、クライアント上では決して共有しないことが重要です。そうしないと、システムのセキュリティが侵害されます。

フェッチャーは、Promise でラップされた 2 つのフィールドを持つデータ構造を返す必要があります。

  • 文字列 token
  • 数値 expiresInSeconds。トークンは、取得後、この時間内に期限切れになります。

次のいずれかに該当する場合、JavaScript Fleet Tracking Library は認証トークン フェッチャーを介してトークンをリクエストします。

  • 有効なトークンがない(新しいページの読み込み時にフェッチャーが呼び出されていない場合や、フェッチャーがトークンで返されていない場合など)。
  • 以前に取得したトークンの有効期限が切れています。
  • 以前に取得したトークンが 1 分以内に期限切れになる。

それ以外の場合、ライブラリは以前に発行された有効なトークンを使用し、フェッチャーを呼び出しません。

次の例は、認証トークン フェッチャーを作成する方法を示しています。

JavaScript

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

TypeScript

function authTokenFetcher(options: {
  serviceType: google.maps.journeySharing.FleetEngineServiceType,
  context: google.maps.journeySharing.AuthTokenContext,
}): Promise<google.maps.journeySharing.AuthToken> {
  // The developer should generate the correct
  // SERVER_TOKEN_URL based on options.
  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.expiration_timestamp_ms - Date.now(),
  };
}

トークンを作成するためのサーバーサイド エンドポイントを実装する場合は、次の点に注意してください。

  • エンドポイントはトークンの有効期限を返す必要があります。上記の例では、data.ExpiresInSeconds と指定されています。
  • 認証トークン フェッチャーは、例に示すように有効期限(フェッチした時点から秒単位)をライブラリに渡す必要があります。
  • SERVER_TOKEN_URL はバックエンドの実装によって異なります。サンプルアプリ バックエンドの URL は次のとおりです。
    • https://SERVER_URL/token/delivery_driver/DELIVERY_VEHICLE_ID
    • https://SERVER_URL/token/delivery_consumer/TRACKING_ID
    • https://SERVER_URL/token/fleet_reader

HTML から地図を読み込む

次の例は、指定した URL から JavaScript ジャーニー共有ライブラリを読み込む方法を示しています。callback パラメータにより、API の読み込み後に initMap 関数が実行されます。defer 属性を使用すると、API の読み込み中でもブラウザがページの残りの部分をレンダリングし続けることができます。

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>

配達車両に従う

このセクションでは、JavaScript Fleet Tracking Library を使用して配送車両を追跡する方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込むようにしてください。

配達車両位置プロバイダをインスタンス化する

JavaScript Fleet Tracking Library は、Fleet Engine Deliveries API の位置情報プロバイダを事前定義します。プロジェクト ID とトークン ファクトリへの参照を使用して、トークン ファクトリをインスタンス化します。

JavaScript

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

          // Optionally, you may specify 
          // deliveryVehicleId to immediately start
          // tracking.
          deliveryVehicleId: 'your-delivery-id',
});

TypeScript

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

          // Optionally, you may specify
          // deliveryVehicleId to immediately start
          // tracking.
          deliveryVehicleId: 'your-delivery-id',
});

地図表示を初期化する

JavaScript 移動共有ライブラリを読み込んだら、地図ビューを初期化して 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 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 wish.
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],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// 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 wish.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

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

タスクに関するメタ情報は、位置情報プロバイダを使用して deliveryVehicle オブジェクトから取得できます。メタ情報には、到着予定時刻と、車両が次の乗車または降車するまでの距離が含まれます。メタ情報が変更されると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。

JavaScript

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

TypeScript

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

エラーをリッスンする

配達車両情報のリクエストとは非同期に発生するエラーにより、エラーイベントがトリガーされます。次の例は、エラーを処理するためにこれらのイベントをリッスンする方法を示しています。

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

トラッキングを停止

位置情報プロバイダが配送車両を追跡しないようにするには、配送車両 ID を位置情報プロバイダから削除します。

JavaScript

locationProvider.deliveryVehicleId = '';

TypeScript

locationProvider.deliveryVehicleId = '';

地図表示から位置情報プロバイダを削除する

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

配送フリートを表示する

このセクションでは、JavaScript ジャーニー共有ライブラリを使用して、デリバリー フリートを表示する方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込むようにしてください。

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

JavaScript Fleet Tracking Library は、FleetEngine Deliveries API から複数の車両を取得する位置情報プロバイダを事前定義します。プロジェクト ID とトークン フェッチャーへの参照を使用して、トークンをインスタンス化します。

JavaScript

locationProvider =
    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"',
        });

TypeScript

locationProvider =
    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"',
        });

deliveryVehicleFilter には、地図に表示される車両をフィルタするクエリを指定します。このフィルタは Fleet Engine に直接渡されます。サポートされている形式については、ListDeliveryVehiclesRequest.filter をご覧ください。

locationRestriction は、地図上に車両を表示する領域を制限します。また、位置情報の追跡を有効にするかどうかも制御します。設定されるまで位置情報の追跡は開始されません。

位置情報プロバイダを構築したら、地図ビューを初期化します。

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

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

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

位置情報プロバイダを使用して、フリートに関するメタ情報を deliveryVehicles オブジェクトから取得できます。メタ情報には、ナビゲーション状態、残り距離、カスタム属性などの車両プロパティが含まれます。詳しくは、リファレンス ドキュメントをご覧ください。メタ情報が変更されると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。

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

エラーをリッスンする

配送フリートの情報のリクエストとは非同期に発生するエラーは、エラーイベントをトリガーします。これらのイベントをリッスンする方法の例については、エラーをリッスンするをご覧ください。

トラッキングを停止

位置情報プロバイダが配達フリートを追跡しないようにするには、位置情報プロバイダの境界を null に設定します。

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

地図表示から位置情報プロバイダを削除する

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

配達車両を追跡しながら配達車両を追跡する

フリートの表示中に、特定の配達車両のルートと今後のタスクを表示できます。これを行うには、Delivery Fleet Location Provider と Delivery Vehicle Location Provider の両方をインスタンス化し、両方を地図ビューに追加します。

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

配達車両位置プロバイダが配達車両を地図に表示し始めます。マーカーのカスタマイズを使用して、フリート マーカーがクリックされたときに配達車両位置情報プロバイダが配達車両を追跡できるようにします。

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

基本地図のデザインをカスタマイズする

地図コンポーネントのデザインをカスタマイズするには、クラウドベースのツールを使用するか、コードで直接オプションを設定して、地図のスタイルを設定します。

Cloud ベースのマップのスタイル設定を使用する

Cloud ベースのマップのスタイル設定を使用すると、Google Cloud コンソールから、Google マップを使用するすべてのアプリ用の地図のスタイルを作成、編集できます。コードを変更する必要はありません。地図のスタイルは、Cloud プロジェクトにマップ ID として保存されます。JavaScript フリート トラッキング マップにスタイルを適用するには、JourneySharingMapView の作成時に mapId を指定します。JourneySharingMapView がインスタンス化された後に、mapId フィールドを変更したり追加したりすることはできません。次の例では、以前に作成した地図のスタイルをマップ ID で有効にする方法を示しています。

JavaScript

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

TypeScript

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

コードベースの地図のスタイル設定を使用する

地図のスタイルをカスタマイズするもう 1 つの方法は、JourneySharingMapView の作成時に mapOptions を設定することです。

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

マーカーのカスタマイズ機能を使用する

JavaScript Fleet Tracking Library を使って、地図に追加されたマーカーのデザインをカスタマイズできます。そのためには、マーカーのカスタマイズを指定します。カスタマイズを行うと、地図にマーカーを追加する前やマーカーが更新されるたびに、フリート トラッキング ライブラリによって適用されます。

最も簡単なカスタマイズは、同じタイプのすべてのマーカーに適用する MarkerOptions オブジェクトを指定することです。オブジェクトで指定した変更は、マーカーが作成されるたびに適用され、デフォルトのオプションはすべて上書きされます。

より高度な方法は、カスタマイズ関数を指定することです。カスタマイズ機能により、データに基づいてマーカーのスタイルを設定できるほか、クリック処理などのインタラクティブ 機能をマーカーに追加できます。具体的には、フリート トラッキングはマーカーが表すオブジェクトのタイプ(車両、停車地、タスク)に関するデータをカスタマイズ関数に渡します。これにより、マーカー要素自体の現在の状態(残りの経由地の数やタスクの種類など)に基づいて、マーカーのスタイルを変化させることができます。Fleet Engine の外部にあるソースのデータと結合し、その情報を基にマーカーのスタイルを設定することもできます。

また、カスタマイズ機能を使用して、マーカーの表示をフィルタすることもできます。 そのためには、マーカーで setVisible(false) を呼び出します。

ただし、パフォーマンス上の理由から、位置情報プロバイダのネイティブ フィルタリング(FleetEngineDeliveryFleetLocationProvider.deliveryVehicleFilter など)でフィルタリングすることをおすすめします。ただし、追加のフィルタリング機能が必要な場合は、カスタマイズ関数を使用してフィルタリングを適用できます。

フリート トラッキング ライブラリには、次のカスタマイズ パラメータが用意されています。

MarkerOptions を使用してマーカーのスタイルを変更する

次の例は、MarkerOptions オブジェクトを使って車両マーカーのスタイルを設定する方法を示しています。上記のマーカーのカスタマイズ パラメータのいずれかを使って、マーカーのスタイルをカスタマイズするには、このパターンに従います。

JavaScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

カスタマイズ機能を使用してマーカーのスタイルを変更する

次の例は、車両マーカーのスタイルを設定する方法を示しています。上記のマーカーのカスタマイズ パラメータのいずれかを使って、マーカーのスタイルをカスタマイズするには、このパターンに従います。

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

マーカーにクリック処理を追加する

次の例は、車両マーカーにクリック処理を追加する方法を示しています。上記のマーカーのカスタマイズ パラメータのいずれかを使って、任意のマーカーにクリック処理を追加するには、以下のパターンに従ってください。

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

表示されるマーカーをフィルタする

次の例は、表示する車両マーカーをフィルタする方法を示しています。上記のマーカー カスタマイズ パラメータのいずれかを使ってマーカーをフィルタするには、このパターンに従います。

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

配送車両を追いかける場合はポリラインのカスタマイズを使用する

JavaScript Fleet Tracking Library を使って、フォローしている車両のルートの地図上での見た目をカスタマイズすることもできます。このライブラリは、 google.maps.Polyline 車両の有効な経路または残りの経路にある 経路内の座標のペアごとにオブジェクトを作成します。 ポリラインのカスタマイズを指定することで、Polyline オブジェクトのスタイルを設定できます。その後、ライブラリは、オブジェクトを地図に追加する前と、オブジェクトに使用されるデータが変更されたときの 2 つの状況で、これらのカスタマイズを適用します。

マーカーのカスタマイズと同様に、PolylineOptions のセットを指定して、一致するすべての Polyline オブジェクトの作成時または更新時にそのオブジェクトに適用できます。

同様に、カスタマイズ関数を指定できます。カスタマイズ関数を使用すると、Fleet Engine から送信されたデータに基づいてオブジェクトのスタイルを個別に設定できます。この関数では、現在の車両の状態に基づいて各オブジェクトのスタイルを変更できます。たとえば、Polyline オブジェクトの色を濃い色にしたり、車両の走行速度が遅いときは厚くしたりできます。Fleet Engine の外部のソースから結合し、その情報に基づいて Polyline オブジェクトのスタイルを設定することもできます。

FleetEngineDeliveryVehicleLocationProviderOptions で提供されるパラメータを使用して、カスタマイズを指定できます。車両の移動におけるさまざまな経路の状態(すでに走行中、走行中、未走行など)をカスタマイズできます。パラメータは次のとおりです。

PolylineOptions を使用して Polyline オブジェクトのスタイルを変更する

次の例は、PolylineOptions を使用して Polyline オブジェクトのスタイルを設定する方法を示しています。このパターンに従って、Polyline オブジェクトのスタイルを、前述のポリラインのカスタマイズを使ってカスタマイズします。

JavaScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

TypeScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

カスタマイズ関数を使用して Polyline オブジェクトのスタイルを変更する

次の例では、カスタマイズ機能を使用してアクティブなポリライン オブジェクトのスタイルを設定しています。このパターンに従って、前述のポリライン カスタマイズ パラメータのいずれかを使って Polyline オブジェクトのスタイルをカスタマイズします。

JavaScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    if (distance < 1000) {

      // params.polylines contains an ordered list of Polyline objects for
      // the path.
      for (const polylineObject of params.polylines) {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

TypeScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params: DeliveryVehiclePolylineCustomizationFunctionParams) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    if (distance < 1000) {

      // params.polylines contains an ordered list of Polyline objects for
      // the path.
      for (const polylineObject of params.polylines) {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

Polyline オブジェクトの表示の制御

デフォルトでは、すべての Polyline オブジェクトが表示されます。Polyline オブジェクトを非表示にするには、その visible プロパティを設定します。

JavaScript

remainingPolylineCustomization = {visible: false};

TypeScript

remainingPolylineCustomization = {visible: false};

車両マーカーまたは場所マーカーの InfoWindow を表示する

InfoWindow を使用すると、車両または場所のマーカーに関する追加情報を表示できます。

次の例は、InfoWindow を作成して車両マーカーにアタッチする方法を示しています。

JavaScript

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

// (Assumes a delivery vehicle location provider.)
locationProvider.addListener('update', e => {
  if (e.deliveryVehicle) {
    const distance = 
           e.deliveryVehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next task.`);

    // 2. Attach the info window to a vehicle marker.   
    // This property can return multiple markers.
    const marker = mapView.vehicleMarkers[0];
    infoWindow.open(mapView.map, marker);
  }
});

// 3. Close the info window.
infoWindow.close();

TypeScript

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

// (Assumes a delivery vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
  if (e.deliveryVehicle) {
    const distance = 
           e.deliveryVehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next task.`);

    // 2. Attach the info window to a vehicle marker.   
    // This property can return multiple markers.
    const marker = mapView.vehicleMarkers[0];
    infoWindow.open(mapView.map, marker);
  }
});

// 3. Close the info window.
infoWindow.close();

自動適合を無効にする

自動適合を無効にすることで、地図がビューポートを車両と予想ルートに自動合わせないようにすることができます。次の例は、乗車経路の共有の地図ビューを設定するときに自動フィッティングを無効にする方法を示しています。

JavaScript

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

TypeScript

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

既存の地図を置き換える

マーカーやその他のカスタマイズを含む既存の地図を、それらのカスタマイズを失うことなく置き換えることができます。

たとえば、マーカーが表示される標準の google.maps.Map エンティティを含むウェブページがあるとします。

<!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 Uluru
  var uluru = {lat: -25.344, lng: 131.036};
  // 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 Uluru
  var marker = new google.maps.Marker({position: uluru, 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.
    -->
    <script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

フリート トラッキングを含む JavaScript Journey 共有ライブラリを追加するには:

  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
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. Use FleetEngineDeliveryVehicleLocationProvider
  // as appropriate.
  locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({
    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
  });

mapView.addListener('ready', () => {
  locationProvider.deliveryVehicleId = DELIVERY_VEHICLE_ID;

    // (4) Add customizations like before.

    // The location of Uluru
    var uluru = {lat: -25.344, lng: 131.036};
    // The map, initially centered at Mountain View, CA.
    var map = mapView.map;
    map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
    // The marker, now positioned at Uluru
    var marker = new google.maps.Marker({position: uluru, 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 journey sharing library to the API loader, which includes Fleet Tracking functionality.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
    </script>
  </body>
</html>

指定された ID の配達用車両をウルル付近で運転すると、地図上にレンダリングされます。