JavaScript SDK を使用すると、
Fleet Engine で追跡されている車両と関心のある場所の数。ライブラリ
にドロップイン代替の JavaScript マップ コンポーネントが含まれている
標準の google.maps.Map
エンティティとデータ コンポーネントを接続するために
Fleet Engine とも連携しますJavaScript SDK を使用すると
ウェブ アプリケーションから、カスタマイズ可能な移動と注文の進行状況をアニメーションで表示できます。
コンポーネント
JavaScript SDK には可視化用のコンポーネントが用意されている 車両、地点、ドライバーの到着予定時刻の元データフィード または残りの走行距離を確認できます。
移動と注文の進行状況マップビュー
Map View コンポーネントは、車両と地点の位置を可視化します。 車両のルートがわかっている場合は、地図表示コンポーネントがアニメーション表示される 予測された経路に沿って移動すると予測されます。
ルート案内プロバイダ
JavaScript SDK にルートの位置情報が含まれる 追跡対象のオブジェクトの位置情報を 移動と注文の進行状況マップです
ルート ロケーション プロバイダを使用すると、次の情報を追跡できます。
- ルートの乗車場所または降車場所。
- ルートに割り当てられている車両の場所とルート。
追跡対象の位置情報オブジェクト
位置情報プロバイダは、地点や車両などのオブジェクトの位置を追跡します。
出発地の場所
出発地は、行程の始点です。マーク 受け取り場所が表示されます。
宛先のロケーション
目的地とは、旅程の終点となる場所のことです。 降車場所が示されます。
地点の位置
地点の場所は、追跡中の移動経路上の任意の場所です。 たとえば、バス路線のそれぞれの停留所はウェイポイントの場所です。
車両の位置情報
車両位置情報は、車両の追跡位置です。必要に応じて 車両のルートが含まれます。
認証トークン取得ツール
Fleet Engine に保存されている位置情報へのアクセスを制御するには、 Fleet Engine 用の JSON Web Token(JWT)作成サービスを実装する サーバー上にあります次に、認証トークン フェッチャーを実装します。 JavaScript SDK を使用してウェブ アプリケーションの 位置情報へのアクセスを認証します。
スタイル オプション
マーカーとポリラインのスタイルで、 追跡する位置情報オブジェクト。次を使用: カスタム スタイル オプション。スタイルに合わせてデフォルトのスタイルを変更できます。 ウェブ アプリケーションの機能を提供します。
追跡中の場所の公開設定を管理する
このセクションでは、追跡対象の位置情報オブジェクトの公開設定ルールについて説明します。 Fleet Engine の事前定義済み位置情報プロバイダの マップに表示されますカスタムまたは派生 位置情報プロバイダが公開設定ルールを変更する場合があります。
乗り物
ライドシェアリング車両は、ルートに割り当てられてから表示されます 便利ですルートがキャンセルされると、車両の表示時間は長くなります。
その他すべての位置マーカー
出発地、目的地、ウェイポイントのその他の位置マーカーはすべて 地図上に常に表示されます。例: ライドシェアリングの降車場所 荷物の配達場所を地図上に常に表示している 配送状況を把握できます
JavaScript SDK のスタートガイド
JavaScript SDK を使用する前に、 Fleet Engine に精通している API キーを取得します。
ライドシェアリングのルートを追跡するには、まずルート ID の申し立てを作成します。
ルート ID の申し立てを作成する
ルート ロケーション プロバイダを使用してルートを追跡するには: トリップ ID クレームを含む JSON Web Token(JWT)を作成する。
JWT ペイロードを作成するには、Authorization セクションにクレームを追加します。 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 は次のとおりです。
<ph type="x-smartling-placeholder">
- </ph>
- https://
SERVER_URL
/token/driver/VEHICLEID
- https://
SERVER_URL
/token/consumer/TRIPID
- https://
HTML から地図を読み込む
次の例は、JavaScript SDK を読み込む方法を示しています。
アクセスできるようになります。callback パラメータが initMap
を実行します。
API がロードされた後に送信されます。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 マップを使用するすべてのアプリについて、地図のスタイルを作成、編集できます
Google Cloud コンソールから利用できます。コードを変更する必要はありません。
地図のスタイルは、Cloud プロジェクトにマップ ID として保存されます。宛先
JavaScript SDK 地図にスタイルを適用するには、
mapId
およびその他 mapOptions
これは JourneySharingMapView
を作成するときです。mapId
フィールドは変更できません
または JourneySharingMapView
がインスタンス化された後に追加されます。次の
サンプルは、以前作成した地図のスタイルを
マップ 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.
});
コードベースの地図のスタイル設定を使用する
地図のスタイル設定をカスタマイズするもう一つの方法は、
mapOptions
:
JourneySharingMapView
を作成します。
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
同じタイプのすべてのマーカーに適用されるオブジェクトです。変更点
各マーカーが作成された後に適用されます。
デフォルトのオプションを上書きできます
より高度なオプションとして、カスタマイズ関数を指定できます。カスタマイズ データに基づくマーカーのスタイル設定や、 クリック処理など、マーカーに対するインタラクティブな操作を提供します。具体的には [ルート]と [注文]です Progress は、オブジェクトのタイプに関するデータを マーカーは、車両、出発地、地点、目的地を表します。これにより マーカー要素の現在の状態に応じて変化するマーカーのスタイル あります。たとえば、車両が完結するまでの地点の数、 できます。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
各座標ペアの 1 対 1 の
path です。
Polyline
オブジェクトのスタイルを設定するには、ポリラインのカスタマイズを指定します。「
ライブラリはこれらのカスタマイズを 2 つの状況で適用します。
オブジェクトを地図に追加したり、オブジェクトのデータが変更されたりしたときに通知されます。
マーカーのカスタマイズと同様に、
PolylineOptions
すべての一致の Polyline
オブジェクトに適用されます。
作成または更新されました。
同様に、カスタマイズ関数を指定することもできます。カスタマイズ関数
Fleet Engine によって送信されたデータに基づくオブジェクトの個別のスタイル設定が可能です。
この関数は、オブジェクトの現在の状態に基づいて、各オブジェクトのスタイルを変更できます。
車両たとえば、Polyline
オブジェクトを濃い色合いに設定するなどです。
速度が遅いときは
厚くするとよいでしょう別のデータセットと結合することもできます。
Fleet Engine 外部のソースからエクスポートし、それに基づいて Polyline
オブジェクトのスタイルを設定します。
情報です。
以下のパラメータを使用してカスタマイズを指定できます。
FleetEngineTripLocationProviderOptions
。
さまざまな経路状態のカスタマイズは車両の
すでに旅行した / 積極的に 旅行している / まだ旅行していない「
パラメータは次のとおりです。
takenPolylineCustomization
移動済み経路の場合activePolylineCustomization
移動中の場合remainingPolylineCustomization
未知の経路を表示します
PolylineOptions
を使用して Polyline
オブジェクトのスタイルを変更する
次の例は、Polyline
オブジェクトのスタイル設定を設定する方法を示しています。
PolylineOptions
。
このパターンでは、任意の 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();
自動適合を無効にする
地図が自動的にビューポートを車両にフィットさせないようにすることができます 予測ルートと推定ルートが表示されます次の例をご覧ください。 ルートと注文の設定時に Automatic Fiting を無効にする方法を示します 進行状況を示すマップビューです。
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 がウルルの付近にあれば、地図上にレンダリングされるようになります。