JavaScript 소비자 SDK 설정
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
JavaScript Consumer SDK를 사용하면 소비자 앱이 웹 기반 지도에 Fleet Engine에서 추적되는 차량의 위치와 기타 관심 위치를 표시할 수 있습니다. 이를 통해 소비자 사용자는 배송 진행 상황을 확인할 수 있습니다.
이 가이드에서는 연결된 Google Cloud 프로젝트 및 API 키로 Fleet Engine을 설정했다고 가정합니다. 자세한 내용은 Fleet Engine을 참고하세요.
다음 단계에 따라 JavaScript Consumer SDK를 설정합니다.
- Maps JavaScript API를 사용 설정합니다.
- 승인 설정
Maps JavaScript API 사용 설정
Fleet Engine 인스턴스에 사용하는 Google Cloud 콘솔 프로젝트에서 Maps JavaScript API를 사용 설정합니다. 자세한 내용은 Maps JavaScript API 문서의 API 사용 설정을 참고하세요.
승인 설정하기
Fleet Engine에서는 신뢰도가 낮은 환경(스마트폰 및 브라우저)에서 API 메서드를 호출할 때 JSON 웹 토큰(JWT)을 사용해야 합니다.
JWT는 서버에서 생성되고 서명, 암호화되어 만료되거나 더 이상 유효하지 않을 때까지 후속 서버 상호작용을 위해 클라이언트에 전달됩니다.
주요 세부정보
소비자 앱은 Google Cloud 프로젝트의
delivery_consumer
역할로 최종 사용자를 인증하여 소비자 전용 정보만 반환해야 합니다. 이렇게 하면 Fleet Engine이 응답의 다른 모든 정보를 필터링하고 수정합니다. 예를 들어 사용할 수 없음 작업 중에는 위치 정보가 최종 사용자와 공유되지 않습니다. 예약된 작업의 경우
서비스 계정 역할을 참고하세요.
승인은 어떻게 작동하나요?
Fleet Engine 데이터를 사용한 승인에는 서버 측 및 클라이언트 측 구현이 모두 포함됩니다.
서버 측 승인
웹 기반 애플리케이션에서 인증 및 승인을 설정하기 전에 백엔드 서버가 Fleet Engine에 액세스할 수 있도록 웹 기반 애플리케이션에 JSON 웹 토큰을 발급할 수 있어야 합니다. 웹 기반 애플리케이션은 요청과 함께 이러한 JWT를 전송하므로 Fleet Engine은 요청이 인증되었으며 요청의 데이터에 액세스할 권한이 있음을 인식합니다. 서버 측 JWT 구현에 관한 안내는 Fleet Engine 기본사항의 JSON 웹 토큰 발급을 참고하세요.
특히 배송을 추적하는 JavaScript Consumer SDK의 경우 다음 사항에 유의하세요.
클라이언트 측 승인
JavaScript Consumer SDK를 사용하면 승인 토큰 가져오기를 사용하여 서버에서 토큰을 요청합니다. 다음 중 하나가 참인 경우 이 작업을 실행합니다.
그렇지 않으면 JavaScript Consumer SDK는 이전에 발급된 유효한 토큰을 사용하고 패처를 호출하지 않습니다.
승인 토큰 가져오기 도구 만들기
다음 가이드라인에 따라 승인 토큰 가져오기를 만듭니다.
예 - 인증 토큰 가져오기 프로그램 만들기
다음 예에서는 승인 토큰 가져오기를 만드는 방법을 보여줍니다.
자바스크립트
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,
};
}
다음 단계
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-31(UTC)
[null,null,["최종 업데이트: 2025-08-31(UTC)"],[[["\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)"]]