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

JavaScript フリート トラッキング ライブラリを使用すると、車両の現在地をほぼリアルタイムで可視化できます。このライブラリは、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 位置情報プロバイダの地図に追跡中の位置情報オブジェクトを表示するタイミングを決定します。注 - カスタムまたは派生位置情報プロバイダを使用すると、公開設定ルールが変更される場合があります。

Vehicles

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

地点の位置マーカー

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

  • Origin - 車両のルートの出発地
  • Intermediate(中間)- 車両ルートの停車地を示します
  • 目的地 - 車両での移動の最終的な場所を示します

車両の予定地点は、出発地、中間、目的地のマーカーとして地図上に表示されます。

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

JavaScript フリート トラッキング ライブラリを使用する前に、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 フリート トラッキング ライブラリは、認証トークン フェッチャーを使用してトークンをリクエストします。

  • 有効なトークンがない場合(新しいページ読み込みでフェッチャーが呼び出されていない場合や、フェッチャーがトークンを返していない場合など)。
  • 以前に取得したトークンの有効期限が切れている。
  • 以前に取得したトークンの有効期限が 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 フリート トラッキング ライブラリを使用して車両を追跡する方法を説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込む必要があります。

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

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 Journey Sharing ライブラリを読み込んだ後、地図ビューを初期化して 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 マップを使用するすべてのアプリ用の地図のスタイルを作成、編集できます。地図のスタイルは、マップ ID として Cloud プロジェクトに保存されます。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 を使用すると、地図に追加するマーカーのデザインをカスタマイズできます。これを行うには、マーカーのカスタマイズを指定します。これにより、地図にマーカーを追加する前に、またマーカーを更新するたびに、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);
    }
  };

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

フリート トラッキング ライブラリを使用すると、地図上で追跡している車両のルートのデザインもカスタマイズできます。このライブラリは、車両のアクティブなパスまたは残りのパスの座標ペアごとに 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 ジャーニー共有ライブラリを追加するには:

  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 の近くで運転している場合は、地図にレンダリングされます。