設定 JavaScript Consumer SDK
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
透過 JavaScript Consumer SDK,您的消費者應用程式可以在網頁地圖上顯示車輛位置,以及 Fleet Engine 追蹤的其他感興趣位置。讓消費者使用者查看貨件運送進度。
本指南假設您已設定 Fleet Engine 及其相關聯的 Google Cloud 專案和 API 金鑰。詳情請參閱 Fleet Engine。
請按照下列步驟設定 JavaScript Consumer SDK:
- 啟用 Maps JavaScript API。
- 設定授權。
啟用 Maps JavaScript API
在您用於 Fleet Engine 執行個體的 Google Cloud 控制台專案中,啟用 Maps JavaScript API。詳情請參閱 Maps JavaScript API 說明文件中的「啟用 API」。
設定授權
從低信任度環境 (智慧型手機和瀏覽器) 呼叫 API 方法時,Fleet Engine 必須使用 JSON Web Token (JWT)。
JWT 會在伺服器上產生、簽署、加密,並傳遞至用戶端,供後續伺服器互動使用,直到 JWT 過期或失效為止。
重要詳細資料
您的消費者應用程式應使用 Google Cloud 專案中的
delivery_consumer
角色驗證使用者,只傳回消費者專屬資訊。這樣一來,Fleet Engine 就會篩選並遮蓋回應中的所有其他資訊。舉例來說,在無法提供服務期間,系統不會與使用者分享位置資訊。如要瞭解排定工作適用的服務帳戶角色,請參閱
這篇文章。
授權的運作方式
授權使用 Fleet Engine 資料時,需要同時實作伺服器端和用戶端。
伺服器端授權
在網頁應用程式中設定驗證和授權之前,後端伺服器必須能向網頁應用程式核發 JSON Web Token,以存取 Fleet Engine。網路應用程式會隨要求傳送這些 JWT,讓 Fleet Engine 將要求視為經過驗證,並授權存取要求中的資料。如需伺服器端 JWT 實作的操作說明,請參閱「Fleet Engine 基礎知識」下的「核發 JSON Web Token」。
具體來說,請注意以下事項,以便使用 JavaScript Consumer SDK 追蹤貨運:
用戶端授權
使用 JavaScript Consumer SDK 時,系統會透過授權權杖擷取器向伺服器要求權杖。在符合下列任一條件時,系統就會執行這項操作:
否則,JavaScript Consumer 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.token,
expiresInSeconds: data.ExpiresInSeconds,
};
}
後續步驟
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-31 (世界標準時間)。
[null,null,["上次更新時間:2025-08-31 (世界標準時間)。"],[[["\u003cp\u003eThe JavaScript Consumer SDK enables your web application to display the real-time location of vehicles and other points of interest tracked within Fleet Engine, enhancing shipment visibility for consumers.\u003c/p\u003e\n"],["\u003cp\u003ePrior to implementation, ensure you have a Google Cloud project configured with Fleet Engine, including necessary API keys and the Maps JavaScript API enabled.\u003c/p\u003e\n"],["\u003cp\u003eSecure your application by setting up authorization using JSON Web Tokens (JWTs) issued by your backend server, enabling authenticated access to Fleet Engine data.\u003c/p\u003e\n"],["\u003cp\u003eDevelop an authorization token fetcher on the client-side to retrieve and manage JWTs, ensuring seamless communication between your web application and Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eRemember to adhere to the provided guidelines for generating JWTs and implementing the authorization token fetcher to maintain security and data integrity.\u003c/p\u003e\n"]]],[],null,["With the JavaScript Consumer SDK, your consumer app can show the location of\nvehicles and other locations of interest tracked in Fleet Engine on a web-based\nmap. This allows your consumer users to see the progress of their shipments.\nThis guide assumes you have set up Fleet Engine with its associated\nGoogle Cloud project and API keys. See [Fleet Engine](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/create-project) for details.\n\nYou set up the JavaScript Consumer SDK following these steps:\n\n1. [Enable the Maps JavaScript API](#enable).\n2. [Set up authorization](#set-up-auth).\n\nEnable the Maps JavaScript API\n\nEnable the Maps JavaScript API in the Google Cloud Console project that you use\nfor your Fleet Engine instance. For more details, see [Enable APIs](/maps/documentation/javascript/cloud-setup#enabling-apis) in the\nMaps JavaScript API documentation.\n\nSet up authorization\n\nFleet Engine requires the use of **JSON Web Tokens** (JWTs) for API method calls\nfrom **low-trust environments**: smartphones and browsers.\n\nA JWT originates on your server, is signed, encrypted, and passed to the client\nfor subsequent server interactions until it expires or is no longer valid.\n\n**Key details**\n\n- Use [Application Default Credentials](https://google.aip.dev/auth/4110) to authenticate and authorize against Fleet Engine.\n- Use an appropriate service account to sign JWTs. See [Fleet Engine serviceaccount](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts#fleet_engine_service_account_roles) roles in **Fleet Engine Basics**.\n\nYour consumer app should authenticate your end users with the `delivery_consumer` role from your Google Cloud project to return only consumer-specific information. In this way, Fleet Engine filters and redacts all other information in the responses. For example, during an unavailability task, no location information is shared with an end user. See [Service account\nroles](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/service-accounts#scheduled-tasks) for scheduled tasks.\n\nHow does authorization work?\n\nAuthorization with Fleet Engine data involves both server-side and client-side\nimplementation.\n\nServer-side authorization\n\nBefore you set up authentication and authorization in your web-based\napplication, your backend server must be able to issue JSON Web Tokens to your\nweb-based application for access to Fleet Engine. Your web-based application\nsends these JWTs with its requests so Fleet Engine recognizes the requests as\nauthenticated and authorized to access the data in the\nrequest. For instructions on server-side JWT implementation, see [Issue JSON Web\nTokens](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt) under **Fleet Engine Essentials**.\nSpecifically, keep in mind the following for the JavaScript Consumer SDK for tracking shipments:\n\n\u003cbr /\u003e\n\n- [General guidelines](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#general_guidelines) for issuing JSON Web Tokens\n- [Scheduled tasks JWT guidelines](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#for_scheduled_tasks)\n- [Example token for a consumer app](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#example_token_for_a_consumer_app)\n\nClient-side authorization\n\nWhen you use the JavaScript Consumer SDK, it requests a token from the server using an\nauthorization token fetcher. It does this when any of the following is true:\n\n- No valid token exists, such as when the SDK hasn't called the fetcher on a\n fresh page load, or when the fetcher hasn't returned with a token.\n\n- The token has expired.\n\n- The token is within one minute of expiring.\n\nOtherwise, the JavaScript Consumer SDK uses the previously-issued, valid token and does not\ncall the fetcher.\n\nCreate an authorization token fetcher\n\nCreate your authorization token fetcher using these guidelines:\n\n- **The fetcher must return a data structure with two fields** , wrapped in a\n `Promise` as follows:\n\n - A string `token`.\n\n - A number `expiresInSeconds`. A token expires in this amount of time\n after fetching. The authentication token fetcher must pass the expiry\n time in seconds, from the time of fetching to the library as shown in\n the example.\n\n- **The fetcher should call a URL on your server** to retrieve a token. This\n URL--the `SERVER_TOKEN_URL`--depends on your backend implementation. The\n following example URL is for the [sample app backend on GitHub](https://github.com/googlemaps/last-mile-fleet-solution-samples/tree/main/backend):\n\n - `https://SERVER_URL/token/delivery_consumer/TRACKING_ID`\n\nExample - Create an authentication token fetcher\n\nThe following examples show how to create an authorization token fetcher: \n\nJavaScript \n\n async function authTokenFetcher(options) {\n // options is a record containing two keys called\n // serviceType and context. The developer should\n // generate the correct SERVER_TOKEN_URL and request\n // based on the values of these fields.\n const response = await fetch(SERVER_TOKEN_URL);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n const data = await response.json();\n return {\n token: data.Token,\n expiresInSeconds: data.ExpiresInSeconds\n };\n }\n\nTypeScript \n\n function authTokenFetcher(options: {\n serviceType: google.maps.journeySharing.FleetEngineServiceType,\n context: google.maps.journeySharing.AuthTokenContext,\n }): Promise\u003cgoogle.maps.journeySharing.AuthToken\u003e {\n // The developer should generate the correct\n // SERVER_TOKEN_URL based on options.\n const response = await fetch(SERVER_TOKEN_URL);\n if (!response.ok) {\n throw new Error(response.statusText);\n }\n const data = await response.json();\n return {\n token: data.token,\n expiresInSeconds: data.ExpiresInSeconds,\n };\n }\n\nWhat's next\n\n- [Follow a shipment](/maps/documentation/mobility/journey-sharing/scheduled/shipment-tracking/follow)"]]