JavaScript フリート トラッキング ライブラリを使用すると、フリート内の車両の位置をほぼリアルタイムで可視化できます。このライブラリは、Deliveries API を使用して、配達車両とタスクの可視化を可能にします。JavaScript Shipment Tracking Library と同様に、標準の google.maps.Map
エンティティとデータ コンポーネントを Fleet Engine と接続するための JavaScript マップ コンポーネントが含まれています。
コンポーネント
JavaScript Fleet Tracking Library には、配達車両と停車地を可視化するためのコンポーネントと、ETA や配達までの距離を示す未加工のフィードが用意されています。
フリート追跡の地図表示
フリート追跡の地図表示コンポーネントは、車両とタスクの位置を可視化します。車両のルートがわかっている場合、地図ビュー コンポーネントは、車両が予測されたルートに沿って移動する際にアニメーション化します。
位置情報プロバイダ
位置情報プロバイダは、Fleet Engine に保存されている情報を利用して、追跡対象オブジェクトの位置情報をルート共有マップに送信します。
配達車両の位置情報プロバイダ
配送車両の位置情報プロバイダは、1 台の配送車両の位置情報を表示します。これには、車両の位置情報と配送車両によって完了したタスクに関する情報が含まれます。
配送フリートの位置情報プロバイダ
配送車両の位置情報プロバイダは、複数の車両の位置情報を表示します。特定の車両や場所を除外することも、フリート全体を表示することもできます。
トラッキングする場所の表示を制御する
このセクションでは、Fleet Engine の事前定義された位置情報プロバイダが地図上で追跡する位置情報オブジェクトの公開設定ルールについて説明します。カスタムまたは派生的な位置情報プロバイダは、公開設定ルールを変更できます。
配達手段
配達車両は、Fleet Engine で作成されるとすぐに表示され、タスクに関係なくルート全体に表示されます。
タスクの場所マーカー
車両の停車地が地図上に車両停止マーカーとして表示されます。完了したタスクのマーカーは、車両の計画停留所とは異なるスタイルで表示されます。
タスクの結果を示す場所がタスクの結果マーカーとともに表示されます。結果が SUCCEEDED であるタスクは成功したタスク マーカーとともに表示され、それ以外のタスクはすべて失敗したタスク マーカーとともに表示されます。
JavaScript フリート トラッキング ライブラリを使ってみる
JavaScript フリート トラッキング ライブラリを使用する前に、Fleet Engine と API キーの取得に精通していることを確認してください。次に、タスク ID と配送車両 ID のクレームを作成します。
タスク ID と配送車両 ID のクレームを作成する
配送車両の位置情報プロバイダを使用して配送車両を追跡するには、タスク ID と配送車両 ID クレームを含む JSON ウェブトークン(JWT)を作成します。
JWT ペイロードを作成するには、認証セクションに taskid と deliveryvehicleid のキーを追加してクレームを追加し、各キーの値を * に設定します。トークンは、Fleet Engine Service Super User の 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": "*",
}
}
認証トークンを取得する
認証トークンを取得するため、プロジェクトのサービス アカウント証明書を使用して、サーバー上で適切なクレームで生成されたトークンを取得します。サーバー上のトークンのみを作成し、クライアント間で証明書を共有しないようにすることが重要です。そうしないと、システムのセキュリティが侵害されます。
次の例は、認証トークン フェッチャーを作成する方法を示しています。
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.ExpiresInSeconds
};
}
トークンを作成するサーバー側エンドポイントを実装する場合は、次の点に注意してください。
- エンドポイントはトークンの有効期限を返す必要があります。上記の例では、
data.ExpiresInSeconds
となっています。- 認証トークンの取得は、次の例に示すように、有効期限(発行時から秒単位)をライブラリに渡す必要があります。
HTML から地図を読み込む
次の例は、指定した URL から JavaScript ジャーニー共有ライブラリを読み込む方法を示しています。callback パラメータは、API の読み込み後に initMap
関数を実行します。defer 属性を使用すると、API の読み込み中もページの残りの部分を表示し続けることができます。v=beta パラメータは指定する必要があります。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&callback=initMap&libraries=journeySharing" defer></script>
配達用の車両をフォローする
このセクションでは、JavaScript Fleet Tracking Library を使用して車両をトラックする方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込むようにしてください。
配送車両の位置情報プロバイダをインスタンス化する
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 共有ライブラリを読み込んだ後、地図ビューを初期化して HTML ページに追加します。ページに、地図ビューを保持する <div> 要素が含まれている必要があります。以下の例では、<div> 要素の名前は map_Canvas です。
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: 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'),
locationProvider: 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);
});
配送フリートを表示
このセクションでは、JavaScript Journey 共有ライブラリを使用して配信フリートを表示する方法を説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込むようにしてください。
配送フリートの位置情報プロバイダをインスタンス化する
JavaScript フリート トラッキング ライブラリは、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);
}
}
});
エラーをリッスンする
配信フリート情報のリクエストにより非同期的に発生するエラーによって、エラーイベントがトリガーされます。これらのイベントをリッスンする方法を示す例については、エラーをリッスンするをご覧ください。
基本地図の外観をカスタマイズする
地図コンポーネントの外観をカスタマイズするには、クラウドベースのツールを使用するか、コード内でオプションを直接設定して、地図のスタイルを設定します。
クラウドベースの地図のスタイル機能を使用する
Cloud ベースのマップのスタイル設定を使用すると、コードを変更することなく、Google Cloud Console から Google マップを使用するすべてのアプリの地図のスタイルを作成、編集できます。地図のスタイルはマップ ID として Cloud プロジェクトに保存されます。JavaScript フリート トラッキング マップにスタイルを適用するには、JourneySharingMapView
の作成時に mapId
を指定します。mapId
フィールドは、JourneySharingMapView
のインスタンス化後に変更または追加できません。次の例は、マップ ID を使用して以前に作成した地図のスタイルを有効にする方法を示しています。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
コードベースの地図のスタイル設定を使用する
地図のスタイルをカスタマイズするもう 1 つの方法は、JourneySharingMapView
の作成時に mapOptions
を設定することです。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
ルートのスタイル設定と表示設定を変更する
取得したルートと想定されるルートのスタイル設定と可視性を構成するには、カスタムのスタイル設定オプションを使用します。詳細については、PolylineOptions インターフェースをご覧ください。
次の例は、想定されるルートのスタイルと表示設定を設定する方法を示しています。取得したルートのスタイル設定と表示設定を設定するには、anticipatedRoutePolylineSetup
ではなく takenRoutePolylineSetup
を使用します。
JavaScript
// This function is specified in the
// JourneySharingMapView constructor's options
// parameter.
function anticipatedRoutePolylineSetup({
defaultPolylineOptions, defaultVisible}) {
// If this function is not specified, the
// PolylineOptions object contained in
// defaultPolylineOptions is used to render the
// anticipated route polyline. visible property sets the
// polyline's visibility. Modify this object and
// pass it back to customize the style of the map.
defaultPolylineOptions.strokeOpacity = 0.5;
defaultPolylineOptions.strokeColor = 'red';
return {
polylineOptions: defaultPolylineOptions,
visible: true
};
}
// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineOptionsSetup = {
polylineOptions: {
strokeOpacity: 0.5,
strokeColor: 'red',
…
},
visible: true,
};
TypeScript
// This function is specified in the
// JourneySharingMapView constructor's options
// parameter.
function anticipatedRoutePolylineSetup(options: {
defaultPolylineOptions: google.maps.PolylineOptions,
visible: boolean,
}): {
polylineOptions: google.maps.PolylineOptions,
visible: boolean,
} {
// If this function is not specified, the
// PolylineOptions object contained in
// defaultPolylineOptions is used to render the
// anticipated route polyline. visible property sets the
// polyline's visibility. Modify this object and
// pass it back to customize the style of the map.
options.defaultPolylineOptions.strokeOpacity = 0.5;
options.defaultPolylineOptions.strokeColor = 'red';
return {
polylineOptions: options.defaultPolylineOptions,
visible: true
};
}
// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineSetup = {
polylineOptions: {
strokeOpacity: 0.5,
strokeColor: 'red',
…
},
visible: true,
};
マーカーのカスタマイズを使用する
JavaScript フリート トラッキング ライブラリを使用すると、地図に追加されたマーカーの外観をカスタマイズできます。これを行うには、マーカーのカスタマイズを指定します。これにより、マーカーを地図に追加する前と更新する前に、フリート トラッキング ライブラリが適用されます。
最も単純なカスタマイズは、同じタイプのすべてのマーカーに適用される MarkerOptions
オブジェクトを指定することです。オブジェクトで指定された変更は、各マーカーの作成後に適用され、デフォルトのオプションを上書きします。
さらに高度な方法として、カスタマイズ関数を指定することもできます。カスタマイズ機能を使用すると、データに基づいたマーカーのスタイルを設定したり、クリック操作などのマーカーにインタラクティビティを追加したりできます。具体的には、フリート トラッキングにより、マーカーが表しているオブジェクトの種類(車両、停留所、タスク)のカスタマイズ関数にデータが渡されます。これにより、残りのマーカーの数やタスクの種類など、マーカー要素の現在の状態に基づいてマーカーのスタイルを変更できるようになります。また、Fleet Engine 以外のソースからデータを結合して、その情報に基づいてマーカーのスタイルを設定することもできます。
また、カスタマイズ機能を使用して、マーカーの表示をフィルタすることもできます。それには、マーカーで setVisible(false)
を呼び出します。
ただし、パフォーマンス上の理由から、FleetEngineDeliveryFleetLocationProvider.deliveryVehicleFilter
など、ロケーション プロバイダのネイティブ フィルタリングでフィルタリングすることをおすすめします。ただし、追加のフィルタリング機能が必要な場合は、カスタマイズ関数を使用してフィルタリングを適用できます。
Fleet Tracking ライブラリには、次のカスタマイズ パラメータが用意されています。
MarkerOptions
を使用してマーカーのスタイルを変更する
次の例は、MarkerOptions
オブジェクトを使用して車両マーカーのスタイルを設定する方法を示しています。このパターンに沿って、上記のマーカーのカスタマイズ パラメータを使用して、マーカーのスタイルをカスタマイズします。
JavaScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
カスタマイズ機能を使用してマーカーのスタイルを変更する
次の例は、車両マーカーのスタイルを設定する方法を示しています。このパターンに沿って、上記のマーカー カスタマイズ パラメータを使用して、マーカーのスタイルをカスタマイズします。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
マーカーにクリック処理を追加する
次の例は、車両マーカーにクリック処理を追加する方法を示しています。上記のマーカー カスタマイズ パラメータのいずれかを使用して、マーカーにクリック処理を追加するには、このパターンに従います。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
表示可能なマーカーをフィルタする
次の例は、表示される車両マーカーをフィルタする方法を示しています。上記のマーカー カスタマイズ パラメータを使用してマーカーをフィルタするには、このパターンに従います。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(false);
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(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'),
locationProvider: locationProvider,
automaticViewportMode:
google.maps.journeySharing
.AutomaticViewportMode.NONE,
...
});
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: 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'),
locationProvider: 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 で配送車両をウルル付近で運行している場合、地図上にレンダリングされるようになりました。