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

JavaScript Fleet Tracking Library を使用すると、位置情報を可視化できます。 フリート内の車両の数をほぼリアルタイムで把握できます。このライブラリでは、 Deliveries API 配達車両とタスクを可視化できるようにしました。たとえば、 JavaScript 配送トラッキング ライブラリ ドロップイン代替の JavaScript マップコンポーネントを 標準の google.maps.Map エンティティとデータ コンポーネントを接続するために Fleet Engine とも連携します

コンポーネント

JavaScript Fleet Tracking Library は可視化用のコンポーネントを提供 配達車両と停車地の情報に加え、到着予定時刻または 配送までの距離

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

Fleet Tracking マップビュー コンポーネントは 車両とタスクの場所を特定します。車両のルートがわかっている場合は 車両が予測される経路に沿って移動すると、マップビュー コンポーネントは車両をアニメーション化します。

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

位置情報プロバイダ

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

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

配達車両位置情報プロバイダは、1 つの配送車両の位置情報を 位置情報。車両の位置に関する情報だけでなく 完了したタスクの数を表します。

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

配送車両の位置情報プロバイダが、複数の車両の位置情報をロケーション 情報です。特定の車両や場所でフィルタしたり、 フリート全体を保護できます。

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

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

配達車両

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

タスク位置マーカー

予定されている車両の停車地は、車両停止マーカーとして地図上に表示されます。マーカー 車両のものとは異なるスタイルで表示されます。 表示されます。

タスク結果の場所は、タスク結果マーカー付きで表示されます。 [SUCCEEDED] という結果が出たタスクは、成功を示すマーカー付きで表示されます。 それ以外のタスクは失敗したタスクマーカーとともに表示されます。

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

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

タスク ID と配送車両 ID の申し立てを作成する

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

JWT ペイロードを作成するには、Authorization セクションにクレームを追加します。 キー 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 フリート トラッキング ライブラリが認証を通じてトークンをリクエストする トークン フェッチャーは、次のいずれかに該当する場合に使用できます。

  • 有効なトークンがない(フェッチャーを フェッチャーからトークンが返されなかった場合に返されるメッセージです。
  • 以前に取得したトークンの有効期限が切れている。
  • 以前に取得したトークンの有効期限が 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 は次のとおりです。 <ph type="x-smartling-placeholder">
      </ph>
    • https://SERVER_URL/token/delivery_driver/DELIVERY_VEHICLE_ID
    • https://SERVER_URL/token/delivery_consumer/TRACKING_ID
    • https://SERVER_URL/token/fleet_reader

HTML から地図を読み込む

次の例は、JavaScript ジャーニーの共有を読み込む方法を示しています。 取得します。callback パラメータが initMap を実行します。 API がロードされた後に送信されます。defer 属性を使用すると、ブラウザで API の読み込み中にページの残りの部分のレンダリングを続行します。

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

配達車両に従う

このセクションでは、JavaScript フリート トラッキング ライブラリの使用方法について説明します。 配送車両を追いかけるようなものです必ず スクリプトタグで指定されたコールバック関数からライブラリを読み込む 確認する必要があります

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

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 ページに追加します。ページには 地図ビューを保持する &lt;div&gt; 要素。&lt;div&gt; 要素 以下の例では、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。 次を使用: トークン フェッチャーへの参照と、トークン フェッチャーの参照を指定します。

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 API を プロバイダと配達車両位置情報プロバイダの両方を作成し、 地図表示:

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 マップを使用するすべてのアプリについて、地図のスタイルを作成、編集できます 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) クリックします。

ただし、パフォーマンス上の理由から、ネイティブ 位置情報プロバイダでフィルタリングできます 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 各座標ペアの 1 対 1 の path です。 Polyline オブジェクトのスタイルを設定するには、ポリラインのカスタマイズを指定します。「 ライブラリはこれらのカスタマイズを 2 つの状況で適用します。 オブジェクトを地図に追加したり、オブジェクトのデータが変更されたりしたときに通知されます。

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

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

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

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

次の例は、Polyline オブジェクトのスタイル設定を設定する方法を示しています。 PolylineOptions。 このパターンでは、任意の 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 ジャーニー共有ライブラリを追加するには:

  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 がウルルの付近にあれば、地図上にレンダリングされるようになります。