Thiết lập thư viện theo dõi nhóm JavaScript
Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Trước khi sử dụng thư viện theo dõi đội xe JavaScript, hãy đảm bảo rằng bạn đã quen thuộc và thiết lập Fleet Engine. Để biết thông tin chi tiết, hãy xem phần Fleet Engine.
Tài liệu này trình bày cách bật hoạt động uỷ quyền giữa ứng dụng trang web và Fleet Engine. Sau khi thiết lập các yêu cầu đối với Fleet Engine bằng mã thông báo uỷ quyền chính xác, bạn sẽ sẵn sàng theo dõi một chiếc xe trên bản đồ.
Thiết lập lệnh uỷ quyền
Fleet Engine yêu cầu sử dụng Mã thông báo web JSON (JWT) cho các lệnh gọi phương thức API từ môi trường có độ tin cậy thấp: điện thoại thông minh và trình duyệt.
JWT bắt nguồn từ máy chủ của bạn, được ký, mã hoá và chuyển đến máy khách để tương tác với máy chủ sau đó cho đến khi hết hạn hoặc không còn hợp lệ.
Thông tin chi tiết quan trọng
Cơ chế uỷ quyền hoạt động như thế nào?
Việc uỷ quyền bằng dữ liệu Fleet Engine liên quan đến cả việc triển khai phía máy chủ và phía máy khách.
Uỷ quyền phía máy chủ
Trước khi bạn thiết lập quy trình xác thực và uỷ quyền trong ứng dụng Theo dõi đội xe, máy chủ phụ trợ phải có khả năng phát hành Mã thông báo web JSON cho ứng dụng Theo dõi đội xe để truy cập vào Fleet Engine. Ứng dụng Theo dõi đội xe của bạn sẽ gửi các JWT này cùng với yêu cầu để Fleet Engine nhận ra các yêu cầu này là đã được xác thực và được phép truy cập vào dữ liệu trong yêu cầu. Để biết hướng dẫn về cách triển khai JWT phía máy chủ, hãy xem phần Phát hành mã thông báo web JSON trong mục Kiến thức cơ bản về Fleet Engine.
Để tạo mã thông báo từ máy chủ khi triển khai tính năng Theo dõi đội xe, hãy xem phần sau:
Uỷ quyền phía máy khách
Khi bạn sử dụng thư viện Theo dõi đội xe bằng JavaScript, thư viện này sẽ yêu cầu mã thông báo từ máy chủ bằng cách sử dụng một trình tìm nạp mã thông báo uỷ quyền. Điều này xảy ra khi một trong các trường hợp sau đây là đúng:
Không có mã thông báo hợp lệ, chẳng hạn như khi SDK chưa gọi trình tìm nạp khi tải trang mới hoặc khi trình tìm nạp chưa trả về mã thông báo.
Mã thông báo đã hết hạn.
Mã thông báo sắp hết hạn (trong vòng 1 phút).
Nếu không, thư viện Theo dõi đội xe bằng JavaScript sẽ sử dụng mã thông báo hợp lệ đã phát hành trước đó và không gọi trình tìm nạp.
Tạo một trình tìm nạp mã uỷ quyền
Tạo trình tìm nạp mã thông báo uỷ quyền theo các nguyên tắc sau:
Trình tìm nạp phải trả về một cấu trúc dữ liệu có 2 trường, được gói trong một Promise
như sau:
Trình tìm nạp sẽ gọi một URL trên máy chủ của bạn để truy xuất mã thông báo. URL này (SERVER_TOKEN_URL
) tuỳ thuộc vào cách triển khai phụ trợ của bạn. URL ví dụ sau đây dành cho phần phụ trợ của ứng dụng mẫu trên GitHub:
https://SERVER_URL/token/fleet_reader
Ví dụ: Tạo trình tìm nạp mã uỷ quyền
Các ví dụ sau đây minh hoạ cách tạo một trình tìm nạp mã uỷ quyền:
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,
};
}
Bước tiếp theo
Trừ phi có lưu ý khác, nội dung của trang này được cấp phép theo Giấy phép ghi nhận tác giả 4.0 của Creative Commons và các mẫu mã lập trình được cấp phép theo Giấy phép Apache 2.0. Để biết thông tin chi tiết, vui lòng tham khảo Chính sách trang web của Google Developers. Java là nhãn hiệu đã đăng ký của Oracle và/hoặc các đơn vị liên kết với Oracle.
Cập nhật lần gần đây nhất: 2025-09-05 UTC.
[[["Dễ hiểu","easyToUnderstand","thumb-up"],["Giúp tôi giải quyết được vấn đề","solvedMyProblem","thumb-up"],["Khác","otherUp","thumb-up"]],[["Thiếu thông tin tôi cần","missingTheInformationINeed","thumb-down"],["Quá phức tạp/quá nhiều bước","tooComplicatedTooManySteps","thumb-down"],["Đã lỗi thời","outOfDate","thumb-down"],["Vấn đề về bản dịch","translationIssue","thumb-down"],["Vấn đề về mẫu/mã","samplesCodeIssue","thumb-down"],["Khác","otherDown","thumb-down"]],["Cập nhật lần gần đây nhất: 2025-09-05 UTC."],[[["\u003cp\u003eBefore using the JavaScript Fleet tracking library, ensure you have Fleet Engine set up and are familiar with it.\u003c/p\u003e\n"],["\u003cp\u003eFleet Engine requires JSON Web Tokens (JWTs) for API calls from low-trust environments like web browsers.\u003c/p\u003e\n"],["\u003cp\u003eYour backend server should be configured to issue JWTs to your Fleet tracking application for authentication and authorization with Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eThe JavaScript Fleet tracking library utilizes an authorization token fetcher to request and manage JWTs, ensuring secure communication with Fleet Engine.\u003c/p\u003e\n"],["\u003cp\u003eAfter setting up authorization, you can proceed with tracking vehicles and viewing your fleet in real-time.\u003c/p\u003e\n"]]],["Fleet Engine authorization requires JSON Web Tokens (JWTs) for API calls from low-trust environments. Your backend server issues signed, encrypted JWTs to the client. Use Application Default Credentials and service accounts to authenticate. The JavaScript Fleet tracking library uses an authorization token fetcher to get a token from your server. The fetcher must return a token and its expiration time. The library requests a new token if no valid token exists, if it has expired, or if it is near expiring.\n"],null,["Before using the JavaScript fleet tracking library, make sure you are\nfamiliar with and have set up Fleet Engine. For details, see\n[Fleet Engine](/maps/documentation/mobility/fleet-engine).\n\nThis document shows how to enable authorization between the\nweb page app and Fleet Engine. Once your requests to Fleet Engine have\nbeen set up with the correct authorization tokens, you'll be ready to\ntrack a vehicle on a map.\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\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 Fleet tracking\napplication, your backend server must be able to issue JSON Web Tokens to your\nFleet tracking application for access to Fleet Engine. Your Fleet tracking 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**.\nTo generate tokens from your server when implementing Fleet tracking, see the following:\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, including sections for both on-demand trips and scheduled tasks\n- On-demand trips: [Example token for a backend server operation](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#example_token_for_a_backend_server_operation)\n- Scheduled tasks: [Example token to track all tasks and vehicles in the\n fleet](/maps/documentation/mobility/fleet-engine/essentials/set-up-fleet/issue-jwt#example_token_to_track_all_tasks_and_vehicles)\n\nClient-side authorization\n\nWhen you use the JavaScript Fleet tracking library, 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 Fleet tracking library 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/fleet_reader`\n\nExample - Create an authorization 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- [Track a vehicle](/maps/documentation/mobility/operations/fleet-tracking/follow)\n- [View a fleet](/maps/documentation/mobility/operations/fleet-tracking/view-fleet)"]]