JavaScript Shipment Tracking Library を使用すると、車両の位置と、Fleet Engine で追跡される対象位置を可視化できます。このライブラリには、標準の google.maps.Map
エンティティと Fleet Engine に接続するためのデータ コンポーネントの代わりに使用できる JavaScript マップ コンポーネントが含まれています。JavaScript Shipment Tracking Library を使用すると、ウェブ アプリケーションからカスタマイズ可能なアニメーションの配送追跡を提供できます。
コンポーネント
JavaScript Shipment Tracking Library は、車両が目的地に進展する過程で車両とルートを可視化するコンポーネントと、運転手の到着予定時刻または運転距離の距離を示す未加工のデータフィードを提供します。
配送追跡マップビュー
地図表示コンポーネントは、車両と目的地の位置情報を可視化します。車両のルートがわかっている場合、地図ビュー コンポーネントは、車両が予測された経路に沿って移動する際にアニメーション化します。
発送元プロバイダ
配送場所プロバイダは、最初と最後のマイルの配送追跡のために、追跡対象オブジェクトの位置情報を配送追跡マップにフィードします。
配送元プロバイダは、次の情報を追跡するために使用できます。
- 配送の集配場所。
- 配達する車両の所在地とルート。
トラッキング対象オブジェクト
位置情報プロバイダは、車両や目的地などのオブジェクトの位置を追跡します。
宛先のロケーション
目的地とは、ジャーニーが終了する場所です。配送追跡の場合は、計画されたタスクの場所です。
車両の位置情報
車両の位置情報は、車両の現在地を追跡したものです。場合によっては、車両のルートが含まれる場合があります。
認証トークンの取得
Fleet Engine に保存されている位置情報データへのアクセスを制御するには、Fleet Engine 用の JSON Web Token 作成サービスをサーバーに実装する必要があります。次に、JavaScript ジャーニー共有ライブラリを使用してウェブ アプリケーションの一部として認証トークン取得ツールを実装し、位置情報データへのアクセスを認証します。
スタイル設定オプション
マーカーとポリラインのスタイルにより、地図上でトラッキングされる位置情報オブジェクトの外観が決まります。カスタム スタイル設定を使用すると、ウェブ アプリケーションのスタイル設定に合わせてデフォルトのスタイルを変更できます。
トラッキングする場所の表示を制御する
このセクションでは、地図上のトラッキング対象オブジェクトのデフォルトの公開設定コントロールについて説明します。これらは、事前定義済みのルールとして Fleet Engine に存在します。これらのルールを変更するには、サポートチームにご連絡ください。
これらのルールは、次の 2 つのカテゴリのオブジェクトに適用されます。
- 位置マーカー
- 車両の位置情報
位置マーカーの表示
出発地、目的地、車両停車地のすべての位置マーカーが常に地図に表示されます。たとえば、配送の状態に関係なく、配送場所は常に地図上に表示されます。
車両の位置情報の公開設定
このセクションでは、アクティブなタスクの管理中に車両の位置情報に適用されるデフォルトの公開設定ルールについて説明します。多くのタスクをカスタマイズできますが、すべてではありません。
- 利用できないタスク -- これらのタスクの表示はカスタマイズできません。
- アクティブな車両のタスク -- このタイプのタスクをカスタマイズできます。
- 無効な車両タスク -- これらのタスクの表示はカスタマイズできません。
利用できないタスク
追跡しているタスクへのルートに、利用できないタスクが 1 つ以上ある場合(たとえば運転手が休憩中の場合や車両の給油している場合など)、車両は表示されません。予定到着時刻と完了予定時刻は引き続き表示されます。
車両のアクティブなタスク
デフォルトでは、TaskTrackingInfo
proto には Shipment Tracking Library 内に表示できる多くのデータ要素が用意されています。これらのフィールドは、車両にタスクが割り当てられているとき、および車両がタスクから 5 段階以内にあるときに表示されます。タスクは、タスクが完了またはキャンセルされると終了します。各フィールドについて説明します。
- ポリラインをルーティングする
- 到着予定時刻
- 推定タスク完了時間
- タスクまでの残りの走行距離
- 残りの停車地の数
- 車両の位置情報
プロジェクトの公開設定をカスタマイズするには、サポートチームにご連絡ください。その前に、構成のリストと構成のリストを用意しておくと便利です。カスタマイズできるデータ要素は次のとおりです。
- 残りの停車地の数
- 予定到着時刻までの時間
- 残りの走行距離
- 常に表示
- 非表示
カスタマイズの例: 車両が 3 ストップ以内の場合はルート ポリラインを表示し、残りの走行距離が 5, 000 メートル未満の場合は到着予定時刻を表示する場合などです。各データ要素は、1 つの公開設定オプションにのみ関連付けることができます。
JavaScript Journey 共有ライブラリの使用
JavaScript Journey 共有ライブラリを使用する前に、Fleet Engine と API キーの取得に精通していることを確認してください。
配達を追跡するには、まずトラッキング ID 要求を作成します。
トラッキング ID クレームを作成する
配送場所プロバイダを使用して配送を追跡するには、トラッキング ID クレームを含む JSON ウェブトークン(JWT)を作成します。
JWT ペイロードを作成するには、認証セクションにキー trackingid を使用してクレームを追加します。その値を配送追跡 ID に設定します。
次の例は、トラッキング ID によってトラッキングするトークンの作成方法を示しています。
{
"alg": "RS256",
"typ": "JWT",
"kid": "private_key_id_of_consumer_service_account"
}
.
{
"iss": "consumer@yourgcpproject.iam.gserviceaccount.com",
"sub": "consumer@yourgcpproject.iam.gserviceaccount.com",
"aud": "https://fleetengine.googleapis.com/",
"iat": 1511900000,
"exp": 1511903600,
"scope": "https://www.googleapis.com/auth/xapi",
"authorization": {
"trackingid": "tid_54321",
}
}
認証トークンを取得する
認証トークンを取得するため、プロジェクトのサービス アカウント証明書を使用して、サーバー上で適切なクレームで生成されたトークンを取得します。サーバー上のトークンのみを作成し、クライアント間で証明書を共有しないようにすることが重要です。そうしないと、システムのセキュリティが侵害されます。
次の例は、認証トークン フェッチャーを作成する方法を示しています。
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
となっています。 - 認証トークンの取得は、次の例に示すように、有効期限(発行時から秒単位)をライブラリに渡す必要があります。
- SERVER_TOKEN_URL はバックエンドの実装によって異なります。サンプルアプリのバックエンドの URL は次のとおりです。
- https://
SERVER_URL
/token/delivery_driver/DELIVERY_VEHICLE_ID
- https://
SERVER_URL
/token/delivery_consumer/TRACKING_ID
- https://token/fleet_reader/
SERVER_URL
- https://
HTML から地図を読み込む
次の例は、指定した URL から JavaScript Shipment Tracking Library を読み込む方法を示しています。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 の配送トラッキング ライブラリを使用して配送の集荷や配送を行う方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込むようにしてください。
配送場所プロバイダをインスタンス化する
JavaScript Shipment Tracking Library では、Fleet Engine Deliveries API の位置情報プロバイダが事前定義されています。プロジェクト ID とトークン ファクトリへの参照を使用して、インスタンスをインスタンス化します。
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineShipmentLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify tracking ID to
// immediately start tracking.
trackingId: 'your-tracking-id',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTaskLocationProvider({
projectId,
authTokenFetcher,
// Optionally, you may specify tracking ID to
// immediately start tracking.
trackingId: 'your-tracking-id',
});
地図表示を初期化する
JavaScript Journey 共有ライブラリを読み込んだ後、地図ビューを初期化して HTML ページに追加します。ページに、地図ビューを保持する <div> 要素が含まれている必要があります。次の例では、<div> 要素の名前は map_Canvas です。
競合状態を回避するには、地図の初期化後に呼び出されるコールバックで位置情報プロバイダのトラッキング ID を設定します。
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
document.getElementById('map_canvas'),
locationProvider: locationProvider,
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
トラッキング ID
位置情報プロバイダに提供されるトラッキング ID は、複数のタスク(同じ荷物の集荷と配達のタスク、何度かの配達の失敗など)に対応している場合があります。配送追跡地図に表示するタスクを 1 つ選択します。表示するタスクは次のように決定されます。
- 受け取りタスクが 1 つだけある場合は、そのタスクが表示されます。複数のオープン集荷タスクがあると、エラーが発生します。
- 未完了のデリバリー タスクが 1 つだけの場合は、そのタスクが表示されます。未解決の配信タスクが複数ある場合、エラーが生成されます。
- 配送タスクが終わっている場合:
- 完了しているデリバリー タスクが 1 つだけの場合は、そのタスクが表示されます。
- 完了しているデリバリー タスクが複数ある場合は、最も遅い結果を持つタスクが表示されます。
- 終了時刻が複数あり、どれも終了時刻を設定していない場合、エラーが生成されます。
- 受け取りタスクがクローズしている場合:
- ピックアップ タスクが 1 つしかない場合は、そのタスクが表示されます。
- クローズ済みの受け取りタスクが複数ある場合は、最も遅い時間のタスクが表示されます。
- 結果に時間が存在しないクローズアップ受け取りタスクが複数ある場合、エラーが生成されます。
- それ以外の場合、タスクは表示されません。
変更イベントをリッスンする
タスクのメタ情報は、位置情報プロバイダを使用してタスク トラッキング情報オブジェクトから取得できます。メタ情報には、到着予定時刻、到着予定時刻、到着または配達までの距離などがあります。 メタ情報を変更すると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('update', e => {
// e.task contains data that may be useful
// to the rest of the UI.
console.log(e.taskTrackingInfo.remainingStopCount);
});
TypeScript
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
// e.task contains data that may be useful
// to the rest of the UI.
console.log(e.taskTrackingInfo.remainingStopCount);
});
エラーを処理する
配送情報のリクエストにより非同期的にエラーが発生すると、error イベントがトリガーされます。次の例は、エラーを処理するためにこれらのイベントをリッスンする方法を示しています。
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);
});
注: 予期しないエラーを処理するには、ライブラリ呼び出しを try...catch
ブロックでラップしてください。
基本地図の外観をカスタマイズする
地図コンポーネントの外観をカスタマイズするには、クラウドベースのツールを使用するか、コード内でオプションを直接設定して、地図のスタイルを設定します。
クラウドベースの地図のスタイル機能を使用する
Cloud ベースのマップのスタイル設定を使用すると、コードを変更することなく、Google Cloud Console から Google マップを使用するすべてのアプリの地図のスタイルを作成、編集できます。地図のスタイルはマップ ID として Cloud プロジェクトに保存されます。JavaScript Shipment Tracking の地図にスタイルを適用するには、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'
}
// Any other styling options.
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
// Any other styling options.
});
コードベースの地図のスタイル設定を使用する
地図のスタイルをカスタマイズするもう 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 a 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 a static PolylineOptions to
// use for the anticipated route:
const anticipatedRoutePolylineSetup = {
polylineOptions: {
strokeOpacity: 0.5,
strokeColor: 'red',
…
},
visible: true,
};
マーカーのカスタマイズを使用する
JavaScript Shipment Tracking Library を使用すると、地図に追加されるマーカーの外観をカスタマイズできます。これを行うには、マーカーのカスタマイズを指定します。これにより、配送トラッキング ライブラリにより、マーカーを地図に追加する前とマーカーを更新するたびに、マーカー トラッキングのカスタマイズが適用されます。
最も単純なカスタマイズは、同じタイプのすべてのマーカーに適用される MarkerOptions
オブジェクトを指定することです。オブジェクトで指定された変更は、各マーカーの作成後に適用され、デフォルトのオプションを上書きします。
さらに高度な方法として、カスタマイズ関数を指定することもできます。カスタマイズ機能を使用すると、データに基づいたマーカーのスタイルを設定したり、クリック操作などのマーカーにインタラクティビティを追加したりできます。具体的には、配送トラッキングは、マーカーが表すオブジェクトのタイプ(車両または目的地)をカスタマイズ関数に渡します。これにより、マーカー要素自体の現在の状態に基づいてマーカーのスタイルを変更できるようになります(たとえば、予定していた停車地の数が目的地まで残ります)。また、Fleet Engine 以外のソースからデータを結合して、その情報に基づいてマーカーのスタイルを設定することもできます。
Shipment Tracking ライブラリには、FleetEngineShipmentLocationProviderOptions
の次のカスタマイズ パラメータが用意されています。
MarkerOptions
を使用してマーカーのスタイルを変更する
次の例は、MarkerOptions
オブジェクトを使用して車両マーカーのスタイルを設定する方法を示しています。このパターンに沿って、上記のマーカーのカスタマイズのいずれかを使用して、マーカーのスタイルをカスタマイズします。
JavaScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
カスタマイズ機能を使用してマーカーのスタイルを変更する
次の例は、車両マーカーのスタイルを設定する方法を示しています。このパターンに沿って、上記のマーカー カスタマイズ パラメータを使用して、マーカーのスタイルをカスタマイズします。
JavaScript
deliveryVehicleMarkerCustomization =
(params: ShipmentMarkerCustomizationFunctionParams) => {
const stopsLeft = params.taskTrackingInfo.remainingStopCount;
params.marker.setLabel(`${stopsLeft}`);
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.taskTrackingInfo.remainingStopCount;
params.marker.setLabel(`${stopsLeft}`);
};
マーカーにクリック処理を追加する
次の例は、車両マーカーにクリック処理を追加する方法を示しています。上記のマーカー カスタマイズ パラメータのいずれかを使用して、マーカーにクリック処理を追加するには、このパターンに従います。
JavaScript
deliveryVehicleMarkerCustomization =
(params: ShipmentMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
車両または場所のマーカーの InfoWindow
を表示する
InfoWindow
を使用すると、車両または場所マーカーに関する追加情報を表示できます。
次の例は、InfoWindow
を作成して車両マーカーに接続する方法を示しています。
JavaScript
// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
{disableAutoPan: true});
locationProvider.addListener('update', e => {
const stopsCount =
e.taskTrackingInfo.remainingStopCount;
infoWindow.setContent(
`Your vehicle is ${stopsCount} stops away.`);
// 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
// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
{disableAutoPan: true});
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
const stopsCount =
e.taskTrackingInfo.remainingStopCount;
infoWindow.setContent(
`Your vehicle is ${stopsCount} stops away.`);
// 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 Shipment Tracking Library を使用すると、マーカーや他のカスタマイズを含む既存の地図を、それらのカスタマイズを失うことなく置き換えることができます。
たとえば、マーカーを表示する標準的な 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.
locationProvider = new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
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
});
locationProvider.trackingId = TRACKING_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.
-->
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=beta&libraries=journeySharing">
</script>
</body>
</html>
Uluru の近くに指定された ID を持つトラッキングされたパッケージがある場合、地図上にレンダリングされます。