JavaScript SDK を使用すると、Fleet Engine で追跡されている車両の位置と関心のある場所を可視化できます。このライブラリには、標準の google.maps.Map
エンティティとデータ コンポーネントを差し替えて Fleet Engine に接続するための JavaScript マップ コンポーネントが含まれています。JavaScript SDK を使用すると、ウェブ アプリケーションから、カスタマイズ可能なアニメーションで移動や注文の進行状況を表示できます。
コンポーネント
JavaScript SDK は、車両と地点を可視化するためのコンポーネントや、ドライバーの到着予定時刻や残りの走行距離の未加工データフィードを提供します。
移動と注文の進行状況マップビュー
地図表示コンポーネントは、車両と地点の位置を可視化します。車両のルートがわかっている場合、地図表示コンポーネントは、その車両が予測された経路に沿って移動するとアニメーション化します。
ルート案内プロバイダ
JavaScript SDK には、追跡対象のオブジェクトの位置情報をルートと注文の進行状況マップにフィードするルート位置情報プロバイダが含まれています。
ルート ロケーション プロバイダを使用すると、次の情報を追跡できます。
- ルートの乗車場所または降車場所。
- ルートに割り当てられている車両の場所とルート。
追跡対象の位置情報オブジェクト
位置情報プロバイダは、地点や車両などのオブジェクトの位置を追跡します。
出発地の場所
出発地は、行程の始点です。乗車場所を示します。
宛先のロケーション
目的地とは、旅程の終点となる場所のことです。降車場所が示されます。
地点の位置
地点の場所は、追跡中の移動経路上の任意の場所です。たとえば、バス路線のそれぞれの停留所はウェイポイントの場所です。
車両の位置情報
車両位置情報は、車両の追跡位置です。必要に応じて車両のルートを含めることができます。
認証トークン取得ツール
Fleet Engine に保存されている位置情報へのアクセスを制御するには、サーバーに Fleet Engine 用の JSON Web Token(JWT)作成サービスを実装する必要があります。次に、JavaScript SDK を使用して位置情報へのアクセスを認証し、ウェブ アプリケーションの一部として認証トークン フェッチャーを実装します。
スタイル オプション
マーカーとポリラインのスタイルは、地図上のトラッキング対象ロケーション オブジェクトの外観を決定します。カスタム スタイル オプションを使用すると、ウェブ アプリケーションのスタイルに合わせてデフォルトのスタイルを変更できます。
追跡中の場所の公開設定を管理する
このセクションでは、Fleet Engine の事前定義済み位置情報プロバイダの地図上で追跡される位置情報オブジェクトに対する公開設定ルールについて説明します。カスタムまたは派生した位置情報プロバイダが公開設定ルールを変更する場合があります。
Vehicles
ライドシェアリング車両は、ルートに割り当てられてから降車するまで表示されます。ルートがキャンセルされると、車両の表示時間は長くなります。
その他すべての位置マーカー
出発地、目的地、ウェイポイントのその他の位置マーカーはすべて、地図に常に表示されます。たとえば、ライドシェアリングの持ち込み場所や配送場所は、ルートや配送の状況に関係なく、常に地図に表示されます。
JavaScript SDK のスタートガイド
JavaScript SDK を使用する前に、Fleet Engine と API キーの取得について理解しておいてください。
ライドシェアリングのルートを追跡するには、まずルート ID の申し立てを作成します。
ルート ID の申し立てを作成する
ルート位置情報プロバイダを使用してルートを追跡するには、旅程 ID クレームを含む JSON Web Token(JWT)を作成します。
JWT ペイロードを作成するには、キー tripid を使用して承認セクションにクレームを追加し、その値をルート 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": {
"tripid": "tid_12345",
}
}
認証トークン フェッチャーを作成する
プロジェクトのサービス アカウント証明書を使用して、サーバー上に適切なクレームで作成されたトークンを取得する認証トークン フェッチャーを作成できます。トークンはサーバーにのみ作成し、クライアント間では共有しないでください。そうしないと、システムのセキュリティが侵害されます。
フェッチャーは、Promise でラップされた 2 つのフィールドを含むデータ構造を返す必要があります。
- 文字列
token
。 - 数値
expiresInSeconds
。トークンは、取得後、ここで指定した時間が経過すると期限切れになります。
次のいずれかに該当する場合、JavaScript Consumer SDK は認証トークン フェッチャーを介してトークンをリクエストします。
- 有効なトークンがない場合(新しいページ読み込みでフェッチャーが呼び出されていない場合や、フェッチャーがトークンを返していない場合など)。
- 以前に取得したトークンの有効期限が切れている。
- 以前に取得したトークンの有効期限が 1 分以内に切れている。
それ以外の場合、SDK は以前に発行された引き続き有効なトークンを使用し、フェッチャーは呼び出しません。
次の例は、認証トークン フェッチャーを作成する方法を示しています。
JavaScript
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
};
}
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.jwt,
expiresInSeconds: data.expirationTimestamp - Date.now(),
};
}
トークンを作成するためにサーバーサイドのエンドポイントを実装する場合は、次の点に注意してください。
- エンドポイントはトークンの有効期限を返す必要があります。上記の例では、
data.ExpiresInSeconds
として指定されています。 - 認証トークン フェッチャーは、次の例に示すように、有効期限(フェッチ時点からの秒数)をライブラリに渡す必要があります。
- SERVER_TOKEN_URL はプロバイダの実装によって異なります。サンプル プロバイダの URL は次のとおりです。
- https://
SERVER_URL
/token/driver/VEHICLEID
- https://
SERVER_URL
/token/consumer/TRIPID
- https://
HTML から地図を読み込む
次の例は、指定された URL から JavaScript SDK を読み込む方法を示しています。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 SDK を使用してライドシェアリングや配達のルートを追跡する方法について説明します。コードを実行する前に、スクリプトタグで指定されたコールバック関数からライブラリを読み込む必要があります。
ルート位置情報プロバイダをインスタンス化する
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,
authTokenFetcher,
// Optionally, you may specify a trip ID to
// immediately start tracking.
tripId: 'your-trip-id',
});
マップビューを初期化する
JavaScript SDK を読み込んだ後、地図表示を初期化して HTML ページに追加します。ページには、地図表示を保持する <div> 要素が含まれている必要があります。以下の例では、<div> 要素に map_canvas と名前を付けます。
競合状態を回避するには、地図の初期化後に呼び出されるコールバックに位置情報プロバイダのルート ID を設定します。
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
// Styling customizations; see below.
vehicleMarkerCustomization: vehicleMarkerCustomization,
activePolylineCustomization: activePolylineCustomization,
// 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 will start 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 wish.
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.
vehicleMarkerCustomization: vehicleMarkerCustomization,
activePolylineCustomization: activePolylineCustomization,
// 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.
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 wish.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);
変更イベントをリッスンする
位置情報プロバイダを使用して、タスク オブジェクトからルートに関するメタ情報を取得できます。メタ情報には、到着予定時刻と乗車または降車前の残りの距離が含まれます。メタ情報が変更されると、update イベントがトリガーされます。次の例は、これらの変更イベントをリッスンする方法を示しています。
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);
});
エラーを処理する
ルート情報のリクエストとは非同期にエラーが発生すると、エラーイベントがトリガーされます。次の例は、エラーを処理するためにこれらのイベントをリッスンする方法を示しています。
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);
});
注: 予期しないエラーを処理できるように、ライブラリ呼び出しを try...catch
ブロックでラップしてください。
トラッキングを停止
位置情報プロバイダによるルートのトラッキングを停止するには、ロケーション プロバイダからルート ID を削除します。
JavaScript
locationProvider.tripId = '';
TypeScript
locationProvider.tripId = '';
地図表示から位置情報プロバイダを削除する
次の例は、地図表示から位置情報プロバイダを削除する方法を示しています。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
基本地図のデザインをカスタマイズする
地図コンポーネントのデザインをカスタマイズするには、クラウドベースのツールを使用するか、コードで直接オプションを設定して、地図のスタイルを設定します。
Cloud ベースのマップのスタイル設定を使用する
Cloud ベースのマップのスタイル設定を使用すると、コードを変更することなく、Google Cloud コンソールから Google マップを使用するすべてのアプリ用の地図のスタイルを作成、編集できます。地図のスタイルは、Cloud プロジェクトにマップ ID として保存されます。JavaScript SDK の地図にスタイルを適用するには、JourneySharingMapView
を作成する際に、mapId
とその他の mapOptions
を指定します。JourneySharingMapView
をインスタンス化した後は、mapId
フィールドを変更または追加できません。次の例は、マップ ID を使用して、以前に作成した地図のスタイルを有効にする方法を示しています。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
// and any other styling options.
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
// and any other styling options.
});
コードベースの地図のスタイル設定を使用する
地図のスタイル設定をカスタマイズするもう 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 SDK を使用すると、地図に追加するマーカーのデザインをカスタマイズできます。これを行うには、マーカーのカスタマイズを指定します。JavaScript SDK は、マーカーを地図に追加する前や、マーカーを更新するたびに、それを適用します。
最も簡単なカスタマイズは、同じタイプのすべてのマーカーに適用される MarkerOptions
オブジェクトを指定することです。オブジェクトで指定した変更は、各マーカーが作成された後に適用され、デフォルトのオプションを上書きします。
より高度なオプションとして、カスタマイズ関数を指定できます。カスタマイズ関数を使うと、データに基づいてマーカーのスタイルを設定できるほか、マーカーにクリック処理などのインタラクティブ アクティビティを追加できます。具体的には、移動と注文の進行状況は、マーカーが表すオブジェクトの種類(車両、出発地、地点、目的地)に関するデータをカスタマイズ関数に渡します。これにより、マーカー要素自体の現在の状態(車両が走行を終えるまでに残っている地点の数など)に基づいて、マーカーのスタイルが変化するようになります。Fleet Engine 外部のソースのデータと結合し、その情報に基づいてマーカーのスタイルを設定することも可能です。
JavaScript SDK の FleetEngineTripLocationProviderOptions
では、次のカスタマイズ パラメータを使用できます。
vehicleMarkerCustomization
originMarkerCustomization
waypointMarkerCustomization
destinationMarkerCustomization
MarkerOptions
を使用してマーカーのスタイルを変更する
次の例は、MarkerOptions
オブジェクトを使って車両マーカーのスタイル設定を設定する方法を示しています。マーカーのスタイルをカスタマイズするには、このパターンに上記のマーカーのカスタマイズ方法を使用します。
JavaScript
vehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
vehicleMarkerCustomization = {
cursor: 'grab'
};
カスタマイズ関数を使用してマーカーのスタイルを変更する
次の例は、車両マーカーのスタイル設定を設定する方法を示しています。上記のマーカーのカスタマイズ パラメータを使用してマーカーのスタイルをカスタマイズするには、このパターンを使用します。
JavaScript
vehicleMarkerCustomization =
(params) => {
var distance = params.trip.remainingWaypoints.length;
params.marker.setLabel(`${distance}`);
};
TypeScript
vehicleMarkerCustomization =
(params: TripMarkerCustomizationFunctionParams) => {
const distance = params.trip.remainingWaypoints.length;
params.marker.setLabel(`${distance}`);
};
マーカーにクリック処理を追加する
次の例は、車両マーカーにクリック処理を追加する方法を示しています。 次のパターンでは、上記のマーカーのカスタマイズ パラメータを使用して、任意のマーカーにクリック処理を追加します。
JavaScript
vehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
vehicleMarkerCustomization =
(params: TripMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
ポリラインのカスタマイズを使用する
JavaScript SDK を使って、地図上のルートのデザインをカスタマイズすることもできます。このライブラリは、車両のアクティブなパスまたは残りのパスの座標ペアごとに google.maps.Polyline
オブジェクトを作成します。ポリラインのカスタマイズを指定することで、Polyline
オブジェクトのスタイルを設定できます。ライブラリは、オブジェクトを地図に追加する前と、オブジェクトに使用されているデータが変更されたという 2 つの状況で、これらのカスタマイズを適用します。
マーカーのカスタマイズと同様に、PolylineOptions
のセットを指定して、それらが作成または更新されたときに、一致したすべての Polyline
オブジェクトに適用できます。
同様に、カスタマイズ関数を指定することもできます。カスタマイズ関数を使用すると、Fleet Engine によって送信されたデータに基づいてオブジェクトのスタイルを個別に設定できます。この関数は、車両の現在の状態に基づいて各オブジェクトのスタイルを変更できます。たとえば、Polyline
オブジェクトを濃い色にしたり、車両の動きが遅いときに色を濃くしたりできます。Fleet Engine の外部のソースと結合し、その情報に基づいて Polyline
オブジェクトのスタイルを設定できます。
FleetEngineTripLocationProviderOptions
で提供されるパラメータを使用してカスタマイズを指定できます。車両の移動経路のさまざまな状態(すでに走行済み、アクティブに走行中、未走行)のカスタマイズを設定できます。パラメータは次のとおりです。
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.trip.remainingWaypoints[0].distanceMeters;
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: TripPolylineCustomizationFunctionParams) => {
const distance = params.trip.remainingWaypoints[0].distanceMeters;
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};
トラフィック対応 Polyline
オブジェクトをレンダリングする
Fleet Engine は、フォローしている車両のアクティブな経路と残りの経路の交通速度データを返します。この情報を使用して、トラフィック速度に応じて Polyline
オブジェクトのスタイルを設定できます。
JavaScript
// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
FleetEngineTripLocationProvider.
TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;
// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
(params) => {
FleetEngineTripLocationProvider.
TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
for (const polylineObject of params.polylines) {
if (polylineObject.get('strokeColor') === '#05f') {
polylineObject.setOptions({strokeColor: 'green'});
}
}
};
TypeScript
// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
FleetEngineTripLocationProvider.
TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;
// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
(params: TripPolylineCustomizationFunctionParams) => {
FleetEngineTripLocationProvider.
TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
for (const polylineObject of params.polylines) {
if (polylineObject.get('strokeColor') === '#05f') {
polylineObject.setOptions({strokeColor: 'green'});
}
}
};
車両または位置マーカーの InfoWindow
を表示する
InfoWindow
を使用すると、車両や位置マーカーに関する追加情報を表示できます。
次の例は、InfoWindow
を作成して車両マーカーに追加する方法を示しています。
JavaScript
// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
{disableAutoPan: true});
locationProvider.addListener('update', e => {
const stopsCount = e.trip.remainingWaypoints.length;
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();
TypeScript
// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
{disableAutoPan: true});
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
const stopsCount = e.trip.remainingWaypoints.length;
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'),
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,
...
});
既存の地図を置き換える
JavaScript SDK を使用すると、マーカーやその他のカスタマイズが含まれている既存の地図を、カスタマイズ内容を失うことなく置き換えることができます。
たとえば、マーカーが表示されている標準の 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, centered at Uluru
var map = new google.maps.Map(document.getElementById('map'));
map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
// The marker, 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 SDK を追加するには:
- 認証トークン ファクトリのコードを追加します。
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
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 Uluru
var uluru = {lat: -25.344, lng: 131.036};
// The map, centered at Uluru
var map = mapView.map;
map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
// The marker, 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 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>
ウルル付近で、指定された ID のルートを運行している場合は、地図上にレンダリングされるようになりました。