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

JavaScript Fleet Tracking Library を使用すると、フリート内の車両の位置をほぼリアルタイムで可視化できます。ライブラリは On Demand Rides and Deliveries API を使用して、車両とルートを可視化します。JavaScript Fleet Tracking Library には、標準の google.maps.Map エンティティとデータ コンポーネントの代わりに Fleet Engine に接続できる JavaScript 地図コンポーネントが含まれています。

コンポーネント

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

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

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

フリート トラッキングの地図ビューの例

位置情報プロバイダ

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

車両位置情報プロバイダ

車両位置情報プロバイダは、1 つの車両の位置情報を表示します。車両の位置と車両に割り当てられている現在のルートに関する情報が含まれます。

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

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

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

公開設定ルールは、追跡している位置情報オブジェクトを Fleet Engine 位置情報プロバイダの地図に表示するタイミングを決定します。注: カスタムまたは派生の位置情報プロバイダを使用すると、公開設定ルールが変更されることがあります。

乗り物

車両は、Fleet Engine で作成されるとすぐに表示可能になり、vehic_state が Online の場合に表示されます。つまり、車両に現在のルートが割り当てられていなくても、車両を表示できます。

地点の位置マーカー

ウェイポイントの位置マーカーは、出発地から最終目的地まで、車両の移動の途中のポイントを示します。地点の位置マーカーは次のように定義できます。

  • 出発地 - 車両ルートの出発地を示します。
  • 中級 - 車両ルートの停車地点を示します
  • 目的地 - 車両のルートの最終的な場所を示します。

計画された車両のウェイポイントは、出発地、中間地点、目的地のマーカーとして地図上に表示されます。

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

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

ルート ID と車両 ID の申し立てを作成する

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

JWT ペイロードを作成するには、キー tripidvehicleid を使用して承認セクションにクレームを追加し、各キーの value* に設定します。トークンは、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": {
    "tripid": "*",
    "vehicleid": "*",
  }
}

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

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

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

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

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

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

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

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

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/driver/VEHICLE_ID
    • https://SERVER_URL/token/consumer/TRIP_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&v=beta" defer></script>

車両をフォロー

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

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

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

JavaScript

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

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

TypeScript

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

          // Optionally, you may specify
          // vehicleId to immediately start
          // tracking.
          vehicleId: 'your-vehicle-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 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 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.
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

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

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

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

JavaScript

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

TypeScript

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

エラーをリッスンする

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

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.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

車両フリートを表示する

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

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

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

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

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

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

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

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

JavaScript

locationProvider.addListener('update', e => {
  // 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);
    }
  }
});

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

エラーをリッスンする

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

トラッキングを停止

位置情報プロバイダによるフリートのトラッキングを停止するには、位置情報プロバイダの境界を null に設定します。

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

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

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) を呼び出します。

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

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

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

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

JavaScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

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

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

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

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

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

JavaScript

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

TypeScript

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

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

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

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
      if (remainingWaypoints > 10) {
        params.marker.setVisible(false);
      }
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
    if (remainingWaypoints > 10) {
      params.marker.setVisible(false);
    }
  };

車両をフォローする際にポリラインのカスタマイズを使用する

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

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

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

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

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

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

JavaScript

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

TypeScript

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

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

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

JavaScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.vehicle.waypoints[0].distanceMeters;
    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: VehiclePolylineCustomizationFunctionParams) => {
    const distance = params.vehicle.waypoints[0].distanceMeters;
    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};

トラフィック対応 Polyline オブジェクトをレンダリングする

Fleet Engine は、フォローしている車両の有効な経路と残りの経路の交通速度データを返します。この情報を使用して、トラフィック速度に応じて Polyline オブジェクトのスタイルを設定できます。

JavaScript

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineVehicleLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params) => {
    FleetEngineVehicleLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

TypeScript

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineVehicleLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params: VehiclePolylineCustomizationFunctionParams) => {
    FleetEngineVehicleLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

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

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

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

JavaScript

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

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

    // 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 vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off.`);
    // 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 Oracle Park Stadium
        var oraclePark = { lat: 37.780087547237365, lng: -122.38948437884427 };,
        // 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 Oracle Park
        var marker = new google.maps.Marker({ position: oraclePark, 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 FleetEngineVehicleLocationProvider
        // as appropriate.
        locationProvider = new google.maps.journeySharing.FleetEngineVehicleLocationProvider({
          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.vehicleId = VEHICLE_ID;

          // (4) Add customizations like before.

          // The location of Oracle Park
          var oraclePark = {lat: 37.77995187146094, lng: -122.38957020952795};
          // 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 Oracle Park
          var marker = new google.maps.Marker({position: oraclePark, 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&v=beta"
    ></script>
  </body>
</html>

指定した ID の車両を Oracle Park の近くで運転すると、地図上にレンダリングされます。