透過 JavaScript 運送追蹤程式庫,您可以透過視覺化方式呈現 Fleet Engine 中追蹤的車輛位置和感興趣的地點。這個程式庫包含 JavaScript 地圖元件,用於直接取代標準 google.maps.Map
實體和資料元件,用於與 Fleet Engine 連結。使用 JavaScript 運送追蹤程式庫,您可以從網頁應用程式提供可自訂的運送追蹤體驗。
元件
JavaScript 運送追蹤程式庫提供用於呈現車輛及行進前往目的地路徑的元件,以及駕駛預計到達時間或剩餘行車距離的原始資料動態饋給。
運送追蹤地圖檢視
地圖檢視元件會以視覺化方式呈現車輛和目的地的位置。如果已知車輛路線,地圖檢視元件會在預測路線上移動時,為車輛建立動畫效果。
貨運地點供應商
貨運地點供應商會將追蹤物品的位置資訊提供給貨物追蹤地圖,以便追蹤第一英里和最後里程運送追蹤資訊。
您可以使用貨運位置供應商追蹤以下項目:
- 貨運的取貨或交貨地點。
- 運輸車輛的位置和路線。
追蹤的位置物件
位置提供者會追蹤車輛和目的地等物件的位置。
目的地位置
目的地位置是指旅程的終點,運送追蹤是預定的工作地點。
車輛位置
車輛位置是指追蹤的車輛位置。您可以視需要加入車輛的路線。
驗證權杖擷取工具
如要控管儲存在 Fleet Engine 中的位置資料存取權,您必須在伺服器上為 Fleet Engine 實作 JSON Web Token (JWT) 挖掘服務。接著,使用 JavaScript 歷程共用資料庫導入驗證權杖擷取器做為網頁應用程式的一部分,使用 JavaScript 歷程共享程式庫驗證位置資料的存取權。
樣式選項
標記和折線樣式可決定地圖上追蹤位置物件的外觀和風格。您可以使用自訂樣式選項,將預設樣式變更為與網頁應用程式的樣式一致。
控制追蹤地點的顯示設定
本節說明地圖上追蹤物件的瀏覽權限控制項。這些規則適用於兩種物件:
- 地點標記
- 任務資料
地點標記顯示設定
地圖一律會顯示起點和目的地的所有地點標記。舉例來說,無論貨品交付狀態為何,地圖上一律會顯示送貨地點。
工作資料瀏覽權限
本節說明套用至工作資料的預設瀏覽權限規則,例如車輛位置和剩餘路線。您可以自訂許多工作,但無法自訂所有工作:
- 無法使用的工作 - 您無法自訂這些工作的顯示設定。
- 使用中的車輛工作 - 你可以自訂這些工作類型。
- 已停用的車輛工作 - 你無法自訂這些工作的顯示設定。
無法使用的工作
如果前往追蹤工作的路線至少有一個無法使用的任務 (例如駕駛故障或車輛改裝),系統就不會顯示車輛。預估抵達時間和預估任務完成時間仍可供使用。
進行中的車輛工作
TaskTrackingInfo
物件提供多項資料元素,可顯示在運送追蹤程式庫中。根據預設,當任務指派給車輛時,以及車輛在工作的 5 個停靠站內時,系統就會顯示這些欄位。工作完成或取消時,瀏覽權限就會結束。欄位如下:
- 路線折線
- 預計抵達時間
- 預估任務完成時間
- 與工作剩餘距離
- 剩餘停靠站數量
- 車輛位置
您可以在 Fleet Engine 中建立或更新工作時,在工作中設定 TaskTrackingViewConfig
,藉此自訂各個工作的瀏覽權限設定。這會建立規則,指出何時可以根據下列條件 (以下稱為瀏覽權限選項) 使用個別資料元素:
- 剩餘停靠站數量
- 距離預估抵達時間還有多少時間
- 剩餘行駛距離
- 一律顯示
- 一律隱藏
請注意,每個資料元素只能與一個瀏覽權限選項建立關聯。您無法使用「或」或「且」來合併條件。
以下提供一個自訂範例。自訂規則如下:
- 如果車輛位於 3 個停靠站內,顯示路線折線。
- 如果剩餘行車距離短於 5000 公尺,則顯示預計到達時間。
- 永不顯示剩餘停靠站計數。
- 當車輛位於任務的 5 個停靠站內時,每個其他欄位會保留預設的顯示設定。
"taskTrackingViewConfig": {
"routePolylinePointsVisibility": {
"remainingStopCountThreshold": 3
},
"estimatedArrivalTimeVisibility": {
"remainingDrivingDistanceMetersThreshold": 5000
},
"remainingStopCountVisibility": {
"never": true
}
}
您也可以與支援團隊聯絡,自訂專案的預設瀏覽權限設定。
路線折線和車輛位置顯示規則:
顯示路線折線時,必須一併顯示車輛位置,否則折線結尾可指出車輛位置。這表示路線折線的瀏覽權限選項不受限。
您必須遵循以下規則,提供有效的路線折線 / 車輛位置顯示設定組合:
當路線折線和車輛位置具有相同的顯示選項類型時:
- 如果顯示選項還有停靠站數量、預計到達時間和剩餘行車距離的時間,則路線折線必須提供小於或等於車輛位置這個瀏覽權限選項的值。範例如下:
"taskTrackingViewConfig": { "routePolylinePointsVisibility": { "remainingStopCountThreshold": 3 }, "vehicleLocationVisibility": { "remainingStopCountThreshold": 5 }, }
- 如果路線折線設有一律可見的顯示選項,車輛位置也必須提供一律可見的顯示選項。
- 如果車輛位置沒有任何可見的顯示選項,路線折線也必須提供永不顯示的選項。
如果路線折線和車輛位置的顯示選項類型具有「不同」顯示選項類型,只有在滿足「同時」兩者的顯示選項時,系統才會顯示車輛位置。
範例如下:
"taskTrackingViewConfig": { "routePolylinePointsVisibility": { "remainingStopCountThreshold": 3 }, "vehicleLocationVisibility": { "remainingDrivingDistanceMetersThreshold": 3000 }, }
在本範例中,只有在剩餘停靠站計數至少為 3 且剩餘行車距離至少 3000 公尺時,才會顯示車輛位置。
開始使用 JavaScript 歷程共用資料庫
使用 JavaScript 歷程共用資料庫之前,請確認您已熟悉 Fleet Engine,以及取得 API 金鑰。
如要追蹤運送狀態,請先建立追蹤 ID 聲明。
建立追蹤 ID 聲明
如要使用出貨位置供應商追蹤運送狀態,請建立含有追蹤 ID 憑證附加資訊的 JSON Web Token (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",
}
}
建立驗證權杖擷取工具
您可以建立驗證權杖擷取工具,以便使用專案的服務帳戶憑證,在伺服器上擷取具有適當憑證附加的權杖。請務必只在伺服器上建立權杖,絕不讓任何用戶端共用您的憑證。否則,系統將破壞系統的安全性。
擷取器必須傳回具有兩個欄位的資料結構,並以 Promise 包裝:
- 字串
token
。 - 一個數字
expiresInSeconds
。符記會在擷取後的指定時間到期。
如果發生下列任一情況,JavaScript 運送追蹤程式庫會透過驗證權杖擷取工具要求權杖:
- 這組權杖沒有有效的權杖,例如在新頁面載入時未呼叫擷取器,或是擷取器尚未傳回權杖時。
- 先前擷取的權杖已過期。
- 先前擷取的權杖會在到期後的一分鐘內。
否則,程式庫會使用先前核發且仍然有效的權杖,且不會呼叫擷取器。
以下範例說明如何建立驗證權杖擷取工具:
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.expiration_timestamp_ms - Date.now(),
};
}
實作建立憑證的伺服器端端點時,請注意下列事項:
- 端點必須傳回符記的到期時間;在上述範例中,它會指定為
data.ExpiresInSeconds
。 - 驗證權杖擷取器必須將到期時間 (從擷取時間開始,以秒為單位) 傳送至程式庫,如範例所示。
- SERVER_TOKEN_URL 取決於您的後端實作,以下是範例應用程式後端的網址:
- https://
SERVER_URL
/token/delivery_driver/DELIVERY_VEHICLE_ID
- https://
SERVER_URL
/token/delivery_consumer/TRACKING_ID
- https://
SERVER_URL
/token/fleet_reader
- https://
從 HTML 載入地圖
以下範例說明如何從指定網址載入 JavaScript 運送追蹤程式庫。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 運送追蹤程式庫追蹤送貨或貨品交付方式。執行程式碼前,請務必從指令碼標記中指定的回呼函式載入程式庫。
將運送地點供應商例項化
JavaScript Shipment Tracking Library 為 Fleet Engine Deliveries API 預先定義位置提供者。使用您的專案 ID 和權杖工廠的參照,將 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
.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',
});
初始化地圖檢視
載入 JavaScript 歷程共享程式庫後,請初始化地圖檢視,並將其新增至 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 可能會對應至多項工作,例如,單一包裹的取貨和貨品交付工作,或是多次傳送失敗。已選取一項要顯示在貨運追蹤地圖上的工作。顯示的工作如下:
- 如果只有一個開啟的上車工作,系統會顯示該工作。如果有多個開啟的取貨工作,就會產生錯誤。
- 如果只有一個開啟中的工作,就會顯示該工作。如有多項開啟中的提交工作,則會產生錯誤。
- 如有已關閉的配送工作:
- 如果只有一項已結案的外送工作,系統會顯示該項工作。
- 如果有多個已結案的提交工作,系統會顯示最近期的到貨時間。
- 如果有多個已結案的提交工作,全都沒有結果時間,就會產生錯誤。
- 如果尚未完成取貨工作:
- 如果只有一個關閉的上車工作,系統會顯示該工作。
- 如果有多個已關閉的上車工作,系統會顯示最近期的上車時間。
- 如果有多個已關閉的取貨工作,全都沒有結果時間,就會產生錯誤。
- 否則,系統不會顯示任何工作。
監聽變更事件
您可以使用位置提供者,從工作追蹤資訊物件擷取工作的中繼資料。中繼資訊包括預計到達時間、剩餘停靠站數,以及取貨或配送前的剩餘距離。變更中繼資訊會觸發 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
區塊納入程式庫呼叫,以處理未預期的錯誤。
自訂基本地圖的外觀和風格
如要自訂地圖元件的外觀和風格,請使用雲端式工具設定地圖樣式,或是直接在程式碼中設定選項。
使用雲端式地圖樣式設定
您可以透過雲端式地圖樣式設定,透過 Google Cloud 控制台為使用 Google 地圖的任何應用程式建立及編輯地圖樣式,無須修改程式碼。地圖樣式會儲存為地圖 ID,並儲存在 Cloud 專案中。如要將樣式套用至 JavaScript 運送追蹤地圖,請在建立 JourneySharingMapView
時指定 mapId
。在 JourneySharingMapView
執行個體化之後,即無法變更或新增 mapId
欄位。以下範例說明如何使用地圖 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.
});
使用程式碼式地圖樣式設定
另一個自訂地圖樣式的方法,是在建立 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 介面。
以下範例說明如何設定預期路線的樣式和顯示設定。如要設定已行路線的樣式和顯示設定,請使用 takenRoutePolylineSetup
,而非 anticipatedRoutePolylineSetup
。
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 運送追蹤程式庫,自訂加入地圖中的標記樣式和外觀。方法是指定標記自訂項目,運送追蹤程式庫會先套用,接著再將標記加入地圖,以及每次更新標記。
最簡單的自訂方式是指定套用至相同類型所有標記的 MarkerOptions
物件。物件中指定的變更會在建立每個標記後套用,並覆寫所有預設選項。
另一個進階選項是指定自訂函式。自訂函式可讓您根據資料設定標記樣式,以及在標記中新增互動 (例如點擊處理)。具體來說,運送追蹤會將資料傳送至自訂函式,以便與標記代表的物件類型有關:車輛或目的地。這樣就能根據標記元素本身的目前狀態變更標記樣式,例如預定的停靠站數到目的地為止。您甚至可以彙整來自 Fleet Engine 外部來源的資料,並根據該資訊設定標記樣式。
運送追蹤程式庫在 FleetEngineShipmentLocationProviderOptions
中提供下列自訂參數:
使用 MarkerOptions
變更標記的樣式
以下範例說明如何使用 MarkerOptions
物件設定車輛標記的樣式。請按照這個模式,使用上述任何標記自訂方式自訂任何標記的樣式。
JavaScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
使用自訂函式變更標記樣式
下例說明如何設定車輛標記的樣式。請按照這個模式,使用上述的任何標記自訂參數自訂任何標記的樣式。
JavaScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.taskTrackingInfo.remainingStopCount;
params.marker.setLabel(`${stopsLeft}`);
};
TypeScript
deliveryVehicleMarkerCustomization =
(params: ShipmentMarkerCustomizationFunctionParams) => {
const stopsLeft = params.taskTrackingInfo.remainingStopCount;
params.marker.setLabel(`${stopsLeft}`);
};
為標記新增點擊處理
以下範例說明如何在車輛標記中新增點擊處理。請按照這個模式,使用上述的任何標記自訂參數,為任何標記新增點擊處理。
JavaScript
deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params: ShipmentMarkerCustomizationFunctionParams) => {
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();
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
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 運送追蹤程式庫取代現有包含標記或其他自訂的地圖,而不會失去這些自訂項目。
舉例來說,假設您的網頁包含標準 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&libraries=journeySharing">
</script>
</body>
</html>
如果您已經有追蹤到 Uluru 附近 ID 的追蹤套件,這個套件就會在地圖上算繪。