乗車をフォローすると、適切な車両の位置情報がユーザー向けアプリに表示されます。そのためには、アプリでルートの追跡を開始し、ルートの進行状況を更新し、ルートが完了したら追跡を停止する必要があります。
このドキュメントでは、このプロセスの次の主な手順について説明します。
- 地図を設定する
- 地図を初期化して共有された経路を表示する
- ルートを更新して進捗状況を確認する
- 旅行のフォローを停止する
- 乗車エラーを処理する
地図を設定する
ウェブアプリで荷物の集荷や配達を追跡するには、マップを読み込んで Consumer SDK をインスタンス化し、ルートの追跡を開始する必要があります。新しい地図を読み込むことも、既存の地図を使用することもできます。次に、初期化関数を使用して Consumer SDK をインスタンス化し、地図ビューが追跡対象アイテムの位置に対応するようにします。
Google Maps JavaScript API を使用して新しい地図を読み込む
新しい地図を作成するには、ウェブアプリで Google Maps JavaScript API を読み込みます。次の例は、Google Maps JavaScript API を読み込み、SDK を有効にして、初期化チェックをトリガーする方法を示しています。
callback
パラメータは、API の読み込み後にinitMap
関数を実行します。defer
属性によって、ブラウザで、API の読み込み中もページの他の部分のレンダリングを続行できます。
initMap
関数を使用して Consumer SDK をインスタンス化します。次に例を示します。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
既存の地図を読み込む
Google Maps JavaScript API で作成された既存の地図(すでに使用している地図など)を読み込むこともできます。
たとえば、次の HTML コードで定義されているマーカーが表示される標準の google.maps.Map
エンティティを含むウェブページがあるとします。これにより、最後にコールバックで同じ initMap
関数を使用して地図が表示されます。
<!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 Pier 39 in San Francisco
var pier39 = {lat: 37.809326, lng: -122.409981};
// 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 Pier 39
var marker = new google.maps.Marker({position: pier39, map: map});
}
</script>
<!-- Load the API from the specified URL.
* The defer attribute allows the browser to render the page while the API loads.
* The key parameter contains your own API key.
* 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>
既存の地図を置き換える
マーカーやその他のカスタマイズを含む既存の地図を、カスタマイズを失うことなく置き換えることができます。
たとえば、標準の google.maps.Map
エンティティを含むウェブページにマーカーが表示されている場合、地図を置き換えてマーカーを維持できます。このセクションでは、その手順について説明します。
地図を置き換えてカスタマイズを維持するには、次の手順で HTML ページにジャーニー共有を追加します。この手順は、次の例でも番号付きで示されています。
認証トークン ファクトリのコードを追加します。
initMap()
関数で位置情報プロバイダを初期化します。initMap()
関数でマップビューを初期化します。ビューには地図が含まれています。カスタマイズを地図ビューの初期化のコールバック関数に移動します。
API ローダーに位置情報ライブラリを追加します。
次の例は、変更内容を示しています。ウルル付近で指定された ID の旅程を運行すると、地図に表示されるようになります。
<!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
async 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.FleetEngineTripLocationProvider({
projectId: "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
});
locationProvider.tripId = TRIP_ID;
// (4) Add customizations like before.
// The location of Pier 39 in San Francisco
var pier39 = {lat: 37.809326, lng: -122.409981};
// 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 Pier 39
var marker = new google.maps.Marker({position: pier39, 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 SDK to the API loader.
-->
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
</script>
</body>
</html>
地図を初期化して乗車中の進行状況を表示する
アプリは、旅行が開始されたら、旅行の位置情報プロバイダをインスタンス化し、地図を初期化して、旅行の進捗状況の共有を開始する必要があります。例については、次のセクションをご覧ください。
乗車位置情報プロバイダをインスタンス化する
JavaScript SDK には、Fleet Engine Ridesharing API 用の事前定義された位置情報プロバイダがあります。プロジェクト ID とトークン ファクトリへの参照を使用して、トークン ファクトリをインスタンス化します。
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineTripLocationProvider({
projectId: 'your-project-id',
authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
マップビューを初期化する
JavaScript SDK を読み込んだら、地図ビューを初期化して 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 trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
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 trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
ルートを更新して進捗状況を確認する
アプリはイベントをリッスンし、乗車が進むにつれて乗車状況を更新する必要があります。位置情報プロバイダを使用して、タスク オブジェクトからルートに関するメタ情報を取得できます。メタ情報には、乗車または降車までの到着予定時刻と残りの距離が含まれます。メタ情報の変更は、更新イベントをトリガーします。次の例は、これらの変更イベントをリッスンする方法を示しています。
JavaScript
locationProvider.addListener('update', e => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
TypeScript
locationProvider.addListener('update', (e:
google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
// e.trip contains data that may be useful
// to the rest of the UI.
console.log(e.trip.dropOffTime);
});
旅行のフォローを停止する
乗車が終了したら、位置情報プロバイダによる乗車の追跡を停止する必要があります。これを行うには、乗車 ID と位置情報プロバイダを削除します。例については、以降のセクションをご覧ください。
位置情報プロバイダから乗車 ID を削除する
次の例は、位置情報プロバイダから乗車 ID を削除する方法を示しています。
JavaScript
locationProvider.tripId = '';
TypeScript
locationProvider.tripId = '';
マップビューから位置情報プロバイダを削除する
次の例は、地図ビューから位置情報プロバイダを削除する方法を示しています。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
乗車エラーを処理する
乗車情報のリクエストから非同期で発生するエラーは、エラー イベントをトリガーします。次の例は、これらのイベントをリッスンしてエラーを処理する方法を示しています。
JavaScript
locationProvider.addListener('error', e => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});
TypeScript
locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
// e.error contains the error that triggered the
// event
console.error(e.error);
});