JavaScript フリート トラッキング ライブラリを使用すると、車両の現在地をほぼリアルタイムで可視化できます。このライブラリでは、Deliveries API を使用して、配達車両とタスクを可視化できます。JavaScript Shipment Tracking Library と同様に、Fleet Engine に接続するための標準の google.maps.Map
エンティティとデータ コンポーネントを差し替える JavaScript マップ コンポーネントが含まれています。
コンポーネント
JavaScript Fleet Tracking Library は、配達車両と停車地を可視化するためのコンポーネントや、到着予定時刻や配達までの残りの距離に関する元データフィードを提供します。
フリート トラッキングの地図表示
Fleet Tracking 地図表示コンポーネントは、車両とタスクの位置を可視化します。車両のルートがわかっている場合は、地図表示コンポーネントによって、その車両が予測された経路に沿って移動するとアニメーション化されます。
位置情報プロバイダ
位置情報プロバイダは、Fleet Engine に保存された情報を使用して、追跡対象オブジェクトの位置情報を経路共有マップに送信します。
配達車両位置情報プロバイダ
配達車両位置情報プロバイダが、単一の配達車両の位置情報を表示します。車両の位置情報と、配送車両が完了したタスクの情報が含まれています。
配達フリート ロケーション プロバイダ
配達車両の位置情報プロバイダは、複数の車両の位置情報を表示します。特定の車両やロケーションでフィルタすることも、フリート全体を表示することもできます。
追跡中の場所の公開設定を管理します
このセクションでは、Fleet Engine の事前定義済み位置情報プロバイダの地図上に追跡対象の位置情報オブジェクトを表示する公開設定ルールについて説明します。カスタムまたは派生した位置情報プロバイダが公開設定ルールを変更する場合があります。
配達車両
配達車両は、Fleet Engine で作成されるとすぐに表示され、タスクに関係なくルート全体に表示されます。
タスク位置マーカー
予定されている車両の停車地は、車両停止マーカーとして地図上に表示されます。完了したタスクのマーカーは、車両が予定している停車地とは異なるスタイルで表示されます。
タスク結果の場所は、タスク結果マーカー付きで表示されます。結果が SUCCEEDED のタスクは成功のタスクマーカーで表示され、他のすべてのタスクは失敗したタスクのマーカーとともに表示されます。
JavaScript フリート トラッキング ライブラリを使ってみる
JavaScript フリート トラッキング ライブラリを使用する前に、Fleet Engine と API キーの取得について理解しておいてください。次に、タスク ID と配送車両 ID の申し立てを作成します。
タスク ID と配送車両 ID の申し立てを作成する
配達車両位置情報プロバイダを使用して配達車両を追跡するには、タスク ID と配達車両 ID クレームを含む JSON Web Token(JWT)を作成します。
JWT ペイロードを作成するには、キー taskid と deliveryvehicleid を含むクレームを認証セクションに追加し、各キーの値を * に設定します。トークンは、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 は次のとおりです。
- https://
SERVER_URL
/token/delivery_driver/DELIVERY_VEHICLE_ID
- https://
SERVER_URL
/token/delivery_consumer/TRACKING_ID
- https://
SERVER_URL
/token/fleet_reader
- https://
HTML から地図を読み込む
次の例は、指定された URL から JavaScript 移動経路共有ライブラリを読み込む方法を示しています。callback パラメータは、API の読み込み後に initMap
関数を実行します。defer 属性を使用すると、ブラウザは API の読み込み中、ページの残りの部分をレンダリングし続けます。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
配達車両に従う
このセクションでは、JavaScript フリート トラッキング ライブラリを使用して配達車両を追跡する方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込む必要があります。
配達車両位置情報プロバイダをインスタンス化する
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 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 delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
= 'your-delivery-vehicle-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they wish.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
= 'your-delivery-vehicle-id';
// Give the map an initial viewport to allow it to
// initialize; otherwise the 'ready' event above may
// not fire. The user also has access to the mapView
// object to customize as they wish.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
変更イベントをリッスンする
タスクに関するメタ情報は、位置情報プロバイダを使用して deliveryVehicle
オブジェクトから取得できます。メタ情報には、車両が次の乗車または降車までの到着予定時刻と残りの距離が含まれます。メタ情報が変更されると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('update', e => {
// e.deliveryVehicle contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicle) {
console.log(e.deliveryVehicle.remainingDuration);
}
});
TypeScript
locationProvider.addListener('update',
(e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
// e.deliveryVehicle contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicle) {
console.log(e.deliveryVehicle.remainingDuration);
}
});
エラーのリッスン
配達車両情報のリクエストから非同期に発生するエラーにより、エラーイベントがトリガーされます。次の例は、エラーを処理するためにこれらのイベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('error', e => {
// e.error is the error that triggered the event.
console.error(e.error);
});
TypeScript
locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
// e.error is the error that triggered the event.
console.error(e.error);
});
トラッキングを停止
位置情報プロバイダによる配達車両の追跡を停止するには、位置情報プロバイダから配達車両 ID を削除します。
JavaScript
locationProvider.deliveryVehicleId = '';
TypeScript
locationProvider.deliveryVehicleId = '';
地図表示から位置情報プロバイダを削除する
次の例は、地図表示から位置情報プロバイダを削除する方法を示しています。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
配送フリートを表示する
このセクションでは、JavaScript ジャーニー共有ライブラリを使用して配送フリートを表示する方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込む必要があります。
配達フリート位置情報プロバイダをインスタンス化する
JavaScript Fleet Tracking Library では、FleetEngine Deliveries API から複数の車両を取得する位置情報プロバイダが事前定義されています。プロジェクト ID とトークン フェッチャーへの参照を使用して、トークン フェッチャーをインスタンス化します。
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery vehicles are
// retrieved and immediately start tracking.
locationRestriction: {
north: 37.3,
east: -121.8,
south: 37.1,
west: -122,
},
// Optionally, specify a filter to limit
// which delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery vehicles are
// retrieved and immediately start tracking.
locationRestriction: {
north: 37.3,
east: -121.8,
south: 37.1,
west: -122,
},
// Optionally, specify a filter to limit
// which delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
deliveryVehicleFilter
は、地図に表示される車両をフィルタするクエリを指定します。このフィルタは Fleet Engine に直接渡されます。サポートされている形式については、ListDeliveryVehiclesRequest.filter
をご覧ください。
locationRestriction
は、地図上で車両を表示する領域を制限します。また、位置情報追跡を有効にするかどうかも管理します。設定されるまで位置情報追跡は開始されません。
位置情報プロバイダの作成が完了したら、地図ビューを初期化します。
地図のビューポートを使用して場所の制限を設定する
locationRestriction
境界は、地図表示で現在表示されている領域に合わせて設定できます。
JavaScript
google.maps.event.addListenerOnce(
mapView.map, 'bounds_changed', () => {
const bounds = mapView.map.getBounds();
if (bounds) {
// If you did not specify a location restriction in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.locationRestriction = bounds;
}
});
TypeScript
google.maps.event.addListenerOnce(
mapView.map, 'bounds_changed', () => {
const bounds = mapView.map.getBounds();
if (bounds) {
// If you did not specify a location restriction in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.locationRestriction = bounds;
}
});
変更イベントをリッスンする
フリートに関するメタ情報は、位置情報プロバイダを使用して deliveryVehicles
オブジェクトから取得できます。メタ情報には、ナビゲーション状態、残りの距離、カスタム属性などの車両プロパティが含まれます。詳しくは、リファレンス ドキュメントをご覧ください。メタ情報を変更すると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('update', e => {
// e.deliveryVehicles contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicles) {
for (vehicle of e.deliveryVehicles) {
console.log(vehicle.remainingDistanceMeters);
}
}
});
TypeScript
locationProvider.addListener('update',
(e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
// e.deliveryVehicles contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicles) {
for (vehicle of e.deliveryVehicles) {
console.log(vehicle.remainingDistanceMeters);
}
}
});
エラーのリッスン
配信フリート情報のリクエストから非同期に発生するエラーにより、エラーイベントがトリガーされます。これらのイベントをリッスンする方法を示す例については、エラーをリッスンするをご覧ください。
トラッキングを停止
位置情報プロバイダによる配達フリートの追跡を停止するには、位置情報プロバイダの境界を null に設定します。
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
地図表示から位置情報プロバイダを削除する
次の例は、地図表示から位置情報プロバイダを削除する方法を示しています。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
配達車両を追跡して配達車両を確認できます
フリートの表示中に、特定の配達車両のルートと今後のタスクを表示できます。これを行うには、Delivery Fleet Location Provider と Delivery Vehicle Location Provider の両方をインスタンス化し、両方を地図ビューに追加します。
JavaScript
deliveryFleetLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery vehicles are
// retrieved and immediately start tracking.
locationRestriction: {
north: 37.3,
east: -121.8,
south: 37.1,
west: -122,
},
// Optionally, specify a filter to limit
// which delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
deliveryVehicleLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher
});
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [
deliveryFleetLocationProvider,
deliveryVehicleLocationProvider,
],
// Any other options
});
TypeScript
deliveryFleetLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery vehicles are
// retrieved and immediately start tracking.
locationRestriction: {
north: 37.3,
east: -121.8,
south: 37.1,
west: -122,
},
// Optionally, specify a filter to limit
// which delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
deliveryVehicleLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher
});
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [
deliveryFleetLocationProvider,
deliveryVehicleLocationProvider,
],
// Any other options
});
配達車両の位置情報プロバイダが地図上に配達車両の表示を開始します。マーカーのカスタマイズを使用すると、車両のマーカーがクリックされたときに配送車両位置情報プロバイダが配送車両を追跡できるようになります。
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// params.vehicle.name follows the format
// "providers/{provider}/deliveryVehicles/{vehicleId}".
// Only the vehicleId portion is used for the delivery vehicle
// location provider.
deliveryVehicleLocationProvider.deliveryVehicleId =
params.vehicle.name.split('/').pop();
});
}
};
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
(params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// params.vehicle.name follows the format
// "providers/{provider}/deliveryVehicles/{vehicleId}".
// Only the vehicleId portion is used for the delivery vehicle
// location provider.
deliveryVehicleLocationProvider.deliveryVehicleId =
params.vehicle.name.split('/').pop();
});
}
};
同じ車両に 2 つのマーカーがレンダリングされないように、配達車両位置情報プロバイダに対してマーカーを非表示にします。
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.setVisible(false);
}
};
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
(params: deliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.setVisible(false);
}
};
基本地図のデザインをカスタマイズする
地図コンポーネントのデザインをカスタマイズするには、クラウドベースのツールを使用するか、コードで直接オプションを設定して、地図のスタイルを設定します。
Cloud ベースのマップのスタイル設定を使用する
Cloud ベースのマップのスタイル設定を使用すると、コードを変更することなく、Google Cloud コンソールから Google マップを使用するすべてのアプリ用の地図のスタイルを作成、編集できます。地図のスタイルは、Cloud プロジェクトにマップ ID として保存されます。JavaScript のフリート トラッキング地図にスタイルを適用するには、JourneySharingMapView
の作成時に mapId
を指定します。JourneySharingMapView
をインスタンス化した後は、mapId
フィールドを変更または追加できません。次の例は、マップ ID を使用して、以前に作成した地図のスタイルを有効にする方法を示しています。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
コードベースの地図のスタイル設定を使用する
地図のスタイル設定をカスタマイズするもう 1 つの方法は、JourneySharingMapView
の作成時に mapOptions
を設定することです。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
マーカーのカスタマイズ機能を使用する
JavaScript Fleet Tracking Library を使用すると、地図に追加するマーカーのデザインをカスタマイズできます。これを行うには、マーカーのカスタマイズを指定します。これにより、地図にマーカーを追加する前に、またマーカーを更新するたびに、Fleet Tracking Library によってそれが適用されます。
最も簡単なカスタマイズは、同じタイプのすべてのマーカーに適用される MarkerOptions
オブジェクトを指定することです。オブジェクトで指定した変更は、各マーカーが作成された後に適用され、デフォルトのオプションを上書きします。
より高度なオプションとして、カスタマイズ関数を指定できます。カスタマイズ関数を使うと、データに基づいてマーカーのスタイルを設定できるほか、マーカーにクリック処理などのインタラクティブ アクティビティを追加できます。具体的には、マーカーが表すオブジェクトのタイプ(車両、停車地、タスク)に関するデータをカスタマイズ関数に渡します。これにより、マーカー要素自体の現在の状態(残りの停車地の数やタスクの種類など)に基づいて、マーカーのスタイル設定が変化します。Fleet Engine 外部のソースのデータと結合し、その情報に基づいてマーカーのスタイルを設定することも可能です。
また、カスタマイズ関数を使用してマーカーの表示設定をフィルタすることもできます。
そのためには、マーカーで setVisible(false)
を呼び出します。
ただし、パフォーマンス上の理由から、位置情報プロバイダのネイティブ フィルタリング(FleetEngineDeliveryFleetLocationProvider.deliveryVehicleFilter
など)を使ってフィルタリングすることをおすすめします。ただし、追加のフィルタリング機能が必要な場合は、カスタマイズ関数を使用してフィルタリングを適用できます。
フリート トラッキング ライブラリには、次のカスタマイズ パラメータが用意されています。
MarkerOptions
を使用してマーカーのスタイルを変更する
次の例は、MarkerOptions
オブジェクトを使って車両マーカーのスタイル設定を設定する方法を示しています。上記のマーカーのカスタマイズ パラメータを使用してマーカーのスタイルをカスタマイズするには、このパターンを使用します。
JavaScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
カスタマイズ関数を使用してマーカーのスタイルを変更する
次の例は、車両マーカーのスタイル設定を設定する方法を示しています。上記のマーカーのカスタマイズ パラメータを使ってマーカーのスタイルをカスタマイズするには、このパターンを使用します。
JavaScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
TypeScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
マーカーにクリック処理を追加する
次の例は、車両マーカーにクリック処理を追加する方法を示しています。 このパターンでは、上記のマーカーのカスタマイズ パラメータを使用して、任意のマーカーにクリック処理を追加します。
JavaScript
deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
表示されるマーカーをフィルタする
次の例は、どの車両マーカーを表示するかをフィルタする方法を示しています。このパターンでは、上記のいずれかのマーカーのカスタマイズ パラメータを使用してマーカーをフィルタリングします。
JavaScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(false);
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(false);
}
};
配送車両に追従する際にポリラインのカスタマイズを使用
JavaScript Fleet Tracking Library を使用すると、地図上で追跡している車両のルートの外観をカスタマイズすることもできます。このライブラリは、車両のアクティブなパスまたは残りのパスの座標ペアごとに google.maps.Polyline
オブジェクトを作成します。ポリラインのカスタマイズを指定することで、Polyline
オブジェクトのスタイルを設定できます。ライブラリは、オブジェクトを地図に追加する前と、オブジェクトに使用されているデータが変更されたという 2 つの状況で、これらのカスタマイズを適用します。
マーカーのカスタマイズと同様に、PolylineOptions
のセットを指定して、それらが作成または更新されたときに、一致したすべての Polyline
オブジェクトに適用できます。
同様に、カスタマイズ関数を指定することもできます。カスタマイズ関数を使用すると、Fleet Engine によって送信されたデータに基づいてオブジェクトのスタイルを個別に設定できます。この関数は、現在の車両の状態に基づいて各オブジェクトのスタイルを変更できます。たとえば、Polyline
オブジェクトを濃い色にしたり、車両の動きが遅いときに色を濃くしたりできます。Fleet Engine 以外のソースから結合し、その情報に基づいて Polyline
オブジェクトのスタイルを設定できます。
FleetEngineDeliveryVehicleLocationProviderOptions
で提供されるパラメータを使用してカスタマイズを指定できます。車両の移動経路のさまざまな状態(すでに走行済み、アクティブに走行中、未走行)のカスタマイズを設定できます。パラメータは次のとおりです。
takenPolylineCustomization
: すでに移動しているパスの場合。activePolylineCustomization
: アクティブに移動する経路。remainingPolylineCustomization
: まだ移動していないパス。
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.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 ジャーニー共有ライブラリを追加するには:
- 認証トークン ファクトリのコードを追加します。
initMap()
関数で位置情報プロバイダを初期化します。initMap()
関数でマップビューを初期化します。ビューには地図が含まれます。- カスタマイズをマップビューの初期化用のコールバック関数に移動します。
- 位置情報ライブラリを 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 の配達車両を運転している場合は、地図上にレンダリングされるようになりました。