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

JavaScript フリート トラッキング ライブラリを使用すると、 フリート内の車両をほぼリアルタイムで把握できます。ライブラリは、オンデマンド 配車と配達 API 車両とルートを可視化できるようにしましたJavaScript フリート トラッキング ライブラリには、ドロップイン型の JavaScript 地図コンポーネントが 標準の google.maps.Map エンティティとデータ コンポーネントの置き換え Fleet Engine と接続します

コンポーネント

JavaScript フリート トラッキング ライブラリには、 車両、ルートの地点、到着予定時刻または残りの地点の 特定します

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

Fleet Tracking マップ ビュー コンポーネントは、車両の現在地と 表示できるようになります。車両のルートがわかっている場合は、 は、予測される経路に沿って移動すると車両をアニメーション化します。

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

位置情報プロバイダ

位置情報プロバイダは Fleet Engine に保存された情報を使用して位置情報を送信します 追跡しているオブジェクトの情報を 移動経路共有マップに取り込むことができます

車両位置情報プロバイダ

車両位置情報プロバイダは、1 台の車両の位置情報を表示します。 このテーブルには、車両の位置と現在のルートの情報が あります。

フリート ロケーション プロバイダ

フリート位置情報プロバイダは、複数の車両の位置情報を表示します。 フィルタを使って特定の車両とその場所を表示したり、 フリート全体の車両の位置情報を表示する。

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

公開設定ルールは、トラッキング対象の位置情報オブジェクトを地図上に表示するタイミングを決定します 利用しています注 - カスタム ロケーションまたは派生ロケーションの使用 プロバイダが公開設定ルールを変更できます。

乗り物

車両は Fleet Engine で作成されるとすぐに表示され、 billing_state が Online の場合。つまり 視界が開けないような状態でも 車両に現在ルートが割り当てられていない場合。

地点の位置マーカー

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

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

車両の計画地点は、出発地、中間地点、および中間地点として地図上に表示されます デスティネーション マーカー。

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

JavaScript フリート トラッキング ライブラリを使用する前に、 Fleet Engine によるAPI の取得により、 キーです。 次に、ルート ID と車両 ID の申し立てを作成します。

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

車両の位置情報を使用して車両を追跡するには provider から、trips を含む JSON Web Token(JWT)を作成します。 ID と車両 ID の申し立て。

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

次の例は、車両で追跡するためのトークンを作成する方法と、 タスク:

{
  "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 の例: <ph type="x-smartling-placeholder">
      </ph>
    • https://SERVER_URL/token/driver/VEHICLE_ID
    • https://SERVER_URL/token/consumer/TRIP_ID
    • https://SERVER_URL/token/fleet_reader

HTML から地図を読み込む

次の例は、JavaScript ジャーニー共有ライブラリを読み込む方法を示しています。 アクセスできるようになります。callback パラメータで 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 と、プロジェクト 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 ページに追加しますページに &lt;div&gt; 要素が含まれている マップビューを保持します&lt;div&gt; 要素の名前は、&lt;div&gt; 見てみましょう。

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 から複数の車両を取得します。次を使用: トークン フェッチャーへの参照と、トークン フェッチャーの参照を指定します。

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 マップを使用するすべてのアプリについて、地図のスタイルを作成、編集できます Google Cloud コンソールから利用できます。コードを変更する必要はありません。「 地図のスタイルは、Cloud プロジェクトにマップ ID として保存されます。カスタム絵文字にスタイルを適用するには、 JavaScript フリート トラッキング マップでは、 mapId JourneySharingMapView を作成するときに指定する必要があります。mapId フィールドは変更できません または JourneySharingMapView がインスタンス化された後に追加されます。次の は、以前に作成した地図のスタイルをマップ 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'
  }
});

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

地図のスタイル設定をカスタマイズするもう一つの方法は、 mapOptions JourneySharingMapView を作成するときに指定する必要があります。

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 各座標ペアの 1 対 1 の path を使用します。 ポリラインのカスタマイズを指定することで、Polyline オブジェクトのスタイルを設定できます。「 ライブラリはこれらのカスタマイズを 2 つの状況に適用します。 オブジェクトを地図に追加したり、オブジェクトのデータが変更されたりしたときに通知されます。

マーカーのカスタマイズと同様に、 PolylineOptions すべての一致の Polyline オブジェクトに適用されます。 作成または更新されました。

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

以下のパラメータを使用してカスタマイズを指定できます。 FleetEngineVehicleLocationProviderOptions。 さまざまな経路状態のカスタマイズは車両の すでに旅行した / 積極的に 旅行している / まだ旅行していない「 パラメータは次のとおりです。

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

次の例は、Polyline オブジェクトのスタイル設定を設定する方法を示しています。 PolylineOptions。 このパターンでは、任意の 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 の近くで運転している場合は、 表示されます。