開始使用 JavaScript 專用的 Consumer SDK

JavaScript SDK 能讓您用視覺化方式 Fleet Engine 追蹤到的車輛和感興趣的地點。圖書館 包含可直接取代的 JavaScript 地圖元件 標準 google.maps.Map 實體和資料元件 更是如此使用 JavaScript SDK 可以在網頁應用程式中提供可自訂的動畫行程和訂單進度。

元件

JavaScript SDK 提供視覺化的元件 車輛和路線控點,以及司機預計到達時間的原始資料動態饋給 或是剩餘的行駛距離

行程和訂單進度地圖檢視

地圖檢視元件能以視覺化方式呈現車輛位置和路線控點。 如果已知車輛的路線,地圖檢視元件會呈現動畫 它會沿著預測路徑移動

行程地點提供者

JavaScript SDK 包含行程地點 可將已追蹤物件位置資訊提供給供應商 行程和訂單進度圖

您可以使用行程地點提供者追蹤以下項目:

  • 行程的上車或下車地點。
  • 指派給行程的車輛位置和路線。

已追蹤的位置物件

位置提供者會追蹤物件的位置,例如路線控點和車輛。

出發地位置

起點位置是指旅程的起點,標記 取貨地點。

目的地位置

目的地位置是指旅程的終點。 標示下車地點。

路線控點位置

路線控點位置是指所追蹤旅程路線上任何地點。 例如,公車路線上的每個停靠站都是路線控點位置。

車輛位置

車輛位置是指車輛追蹤的地點。可選擇是否使用 包括車輛的路線

驗證權杖擷取工具

如要控管儲存在 Fleet Engine 中的位置資料存取權,您必須 實作 Fleet Engine 適用的 JSON Web Token (JWT) 擷取服務 。然後實作驗證權杖擷取工具做為 導入 JavaScript SDK 來驗證位置資料的存取權。

樣式選項

標記和折線樣式會決定 已追蹤地圖上的 location 物件。別擔心!您可以使用 自訂樣式選項,根據樣式變更預設樣式 做為網頁應用程式

控制追蹤位置的顯示設定

本節說明已追蹤位置物件的顯示規則 看到 Fleet Engine 預先定義的定位提供者自訂或衍生 營業地點供應商可能會變更瀏覽權限規則。

交通工具

乘車服務從獲派行程的時間開始可見 抵達下車地點時如果行程取消,車輛會繼續顯示。

所有其他位置標記

起點、目的地和路線控點的所有其他位置標記 一律顯示在地圖上。例如共乘下車地點 或出貨地點永遠會顯示在地圖上 旅程或交付狀態

開始使用 JavaScript SDK

使用 JavaScript SDK 前,請務必 熟悉 Fleet Engine取得 API 金鑰

如要追蹤共乘行程,請先建立行程 ID 領取資訊。

建立行程 ID 聲明

使用行程地點供應商追蹤行程: 建立含有行程 ID 憑證附加資訊的 JSON Web Token (JWT)。

如要建立 JWT 酬載,請在授權專區中新增額外憑證附加資訊 替換為 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 中:

  • 字串 token
  • 數字 expiresInSeconds。權杖的有效期限為 擷取。

JavaScript Consumer SDK 透過驗證權杖要求權杖 擷取器:

  • 權杖沒有有效的憑證,例如憑證尚未在 載入新的網頁,或是擷取程式未傳回權杖時。
  • 它先前擷取的權杖已過期。
  • 先前擷取的權杖會在到期後的一分鐘內。

否則,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 會因供應商實作項目而異,以下是範例供應商的網址:
    • https://SERVER_URL/token/driver/VEHICLEID
    • https://SERVER_URL/token/consumer/TRIPID

從 HTML 載入地圖

以下範例說明如何載入 JavaScript SDK 所指定的網址。回呼參數會執行 initMap 函式。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 會預先定義位置提供者 。使用您的專案 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 網頁。網頁應包含 包含地圖檢視的 &lt;div&gt; 元素。&lt;div&gt; 元素 名稱為 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);

自訂基本地圖的外觀與風格

如要自訂地圖元件的外觀和風格, 設定地圖樣式 ,或直接在程式碼中設定選項。

使用雲端式地圖樣式設定

雲端式地圖樣式設定 可讓您為使用 Google 地圖的任何應用程式建立及編輯地圖樣式 ,無須變更任何程式碼。 地圖樣式會儲存為地圖 ID,並儲存在 Cloud 專案中。目的地: 為您的 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敬上 這個物件,會套用到所有相同類型標記的標記。異動內容 物件中指定的每個標記都會在建立完成後套用。 覆寫任何預設選項

更進階的選項是指定自訂函式。自訂 函式可讓您根據資料設定標記樣式,以及新增 點擊處理等標記的互動方式。具體而言為 進度會將資料 標記代表:車輛、起點、路線控點或目的地。這樣一來 要根據標記元素目前狀態變更的標記樣式 ;例如車輛完成前剩餘的路線控點數量 行程。您甚至可以彙整來自 Fleet Engine 和 據此設定標記樣式。

JavaScript SDK 在 FleetEngineTripLocationProviderOptions 中提供下列自訂參數:

使用 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敬上 物件狀態 「path」。 您可以指定折線自訂項目來設定 Polyline 物件的樣式。 接著,程式庫會在兩種情況下套用這些自訂項目 物件寫入地圖,以及用於物件的資料已變更時。

與自訂標記類似,您可以指定一組 PolylineOptions敬上 並套用到所有相符的 Polyline 物件

同樣地,您也可以指定自訂函式。自訂函式 可根據 Fleet Engine 傳送的資料,套用個別的物件樣式。 此函式可以根據下列項目的目前狀態,變更每個物件的樣式 車輛;例如為 Polyline 物件加上深層顏色,或 因此在車輛行駛速度較慢時,就會較久。你甚至可以和 並根據 Fleet Engine 以外的來源,設定 Polyline 物件的樣式 可能不準確或不適當

您可以使用 FleetEngineTripLocationProviderOptions。 您可以自訂車輛中不同路徑狀態的自訂設定 旅行 - 已有人旅行、正在積極旅遊或尚未出遊。 參數如下:

使用 PolylineOptions 變更 Polyline 物件的樣式

以下範例說明如何設定 Polyline 物件的樣式 同時 PolylineOptions。 按照這個模式,使用任意 Polyline 物件自訂任何 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();

停用自動合框功能

你可以讓地圖不自動根據車輛調整可視區域 並停用自動合照功能。以下範例 說明如何在設定行程和順序時停用自動合框功能 進度圖檢視。

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:

  1. 新增驗證權杖工廠程式碼。
  2. initMap() 函式中初始化位置提供者。
  3. initMap() 函式中初始化地圖檢視。檢視畫麵包含地圖。
  4. 將自訂內容移至地圖檢視初始化的回呼函式。
  5. 將位置程式庫加入 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,現在就會在地圖上顯示。