透過 JavaScript 運送追蹤程式庫追蹤運送進度

JavaScript 運送追蹤程式庫可讓您以視覺化方式呈現在 Fleet Engine 中追蹤的車輛位置和感興趣的地點。程式庫包含 JavaScript 地圖元件,可取代標準 google.maps.Map 實體和資料元件,以便與 Fleet Engine 連結。您可以使用 JavaScript 運送追蹤資料庫,在網頁應用程式中提供可自訂的動畫運送追蹤體驗。

元件

JavaScript 運送追蹤程式庫提供元件,可在車輛抵達目的地時以視覺化方式呈現車輛和路線,以及供駕駛人預計到達時間或剩餘行駛距離的原始資料動態饋給。

運送追蹤地圖檢視

地圖檢視元件會以視覺化方式呈現車輛和目的地的位置。如果知道車輛路線,地圖檢視元件就會在車輛沿著預測路徑移動時,建立動畫效果。

出貨地點供應商

貨運地點供應商會在運送追蹤地圖中提供追蹤物件的位置資訊,用於追蹤第一英里和最後里程的運送追蹤。

你可以透過運送地點供應商追蹤下列項目:

  • 貨物的上車或交貨地點。
  • 運送車輛的位置和路徑。

追蹤的地點物件

位置提供者會追蹤物件 (例如車輛和目的地) 的位置。

目的地位置

終點位置是指旅程的終點。至於運送追蹤,這就是預定的工作位置。

車輛位置

車輛位置是指車輛追蹤的位置。您可以選擇加入車輛的路線。

驗證權杖擷取工具

如要控管儲存在 Fleet Engine 中位置資料的存取權,您必須在伺服器上導入 Fleet Engine 適用的 JSON Web Token (JWT) 挖礦服務。接著,在網頁應用程式中,使用 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 剩餘行車距離至少為 3, 000 公尺時,系統才會顯示車輛位置。

開始使用 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

從 HTML 載入地圖

以下範例說明如何從指定的網址載入 JavaScript 運送追蹤資料庫。回呼參數會在 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 運送追蹤程式庫預先定義了 Fleet Engine Deliveries API 的定位服務供應商。使用專案 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'), 
  locationProviders: [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'),
  locationProviders: [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 可能會對應多項工作,例如同一包裹的取貨和貨品交付工作,或是多次傳送失敗。選取一個工作會顯示在運送追蹤地圖中。實際顯示的工作如下:

  1. 如果只有一個開啟的取貨工作,系統會顯示該項工作。如有多項開放式取貨工作,則會產生錯誤。
  2. 如果只有一個開放式運送工作,系統會顯示該項工作。如有多項未完成的提交工作,就會產生錯誤。
  3. 如果有已關閉的外送工作:
    • 如果只有一項已關閉的配送工作,系統會顯示該項工作。
    • 如有多項已關閉的提交工作,系統會顯示最近通話時間最近的工作。
    • 如有多個已關閉的交付工作,則沒有結果時間,則會產生錯誤。
  4. 如有已關閉的取貨工作:
    • 如果只有一個已停業的取貨工作,系統會顯示該項工作。
    • 如有多項已關閉的取貨工作,系統會顯示最近通話時間最近的工作。
    • 如有多個已關閉的取貨工作,但沒有結果時間,則會產生錯誤。
  5. 否則,系統不會顯示任何工作。

監聽變更事件

您可以使用位置提供工具,從工作追蹤資訊物件中擷取工作的相關中繼資訊。中繼資訊包括預計到達時間、剩餘停靠站數量,以及上車或外送前的剩餘距離。變更中繼資訊會觸發 update 事件。以下範例說明如何監聽這些變更事件。

JavaScript

locationProvider.addListener('update', e => {
  // e.taskTrackingInfo 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.taskTrackingInfo contains data that may be useful
  // to the rest of the UI.
  console.log(e.taskTrackingInfo.remainingStopCount);
});

處理錯誤

因要求運送資訊而非同步產生的錯誤會觸發「錯誤」事件。以下範例說明如何監聽這些事件,以處理錯誤。

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 區塊中,以處理非預期的錯誤。

停止追蹤

如要讓位置提供者停止追蹤運送狀態,請從地點提供者中移除追蹤 ID。

JavaScript

locationProvider.trackingId = '';

TypeScript

locationProvider.trackingId = '';

從地圖檢視中移除位置提供者

下例顯示如何從地圖檢視中移除位置提供者。

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

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

使用雲端式地圖樣式設定

雲端式地圖樣式設定可讓您透過 Google Cloud 控制台,為使用 Google 地圖的任何應用程式建立及編輯地圖樣式,無須修改程式碼。地圖樣式會在 Cloud 專案中以地圖 ID 的形式儲存。如要將樣式套用至 JavaScript 運送追蹤地圖,請在建立 JourneySharingMapView 時指定 mapId。在 JourneySharingMapView 例項化後,就無法變更或新增 mapId 欄位。以下範例說明如何使用地圖 ID 啟用先前建立的地圖樣式。

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // Any other styling options.
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [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'),
  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 運送追蹤程式庫,自訂加入地圖的標記外觀與風格。方法是指定自訂標記,然後套用運送追蹤程式庫,接著再新增標記至地圖和每次標記更新。

最簡單的自訂方式,是指定 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.
      });
    }
  };

使用折線自訂功能

您也可以使用運送追蹤資料庫,在地圖上自訂運送路線的外觀及風格。程式庫會為運送有效或其餘路徑中的每個座標組建立 google.maps.Polyline 物件。指定折線自訂項目,即可設定 Polyline 物件的樣式。接著,程式庫會在以下兩種情況套用這些自訂項目:將物件加入地圖之前,以及用於物件的資料有所變更。

與標記自訂功能類似,您可以指定一組PolylineOptions 在建立或更新時套用至所有相符 Polyline 物件。

同樣地,您也可以指定自訂函式。自訂函式可以根據 Fleet Engine 傳送的資料,設定物件個別樣式。此函式可根據目前的運送狀態變更每個物件的樣式,例如將 Polyline 物件的顏色加深,或在車輛移動速度較慢時加粗。您甚至可以根據 Fleet Engine 外部的來源進行彙整,並根據該資訊設定 Polyline 物件的樣式。

您可以使用 FleetEngineShipmentLocationProviderOptions 中提供的參數指定自訂項目。您可以針對車輛旅程中的不同路徑狀態 (已旅行、正在旅行或尚未外出) 設定自訂項目。參數如下:

使用 PolylineOptions 變更 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.taskTrackingInfo.remainingDrivingDistanceMeters;
    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: ShipmentPolylineCustomizationFunctionParams) => {
    const distance = params.taskTrackingInfo.remainingDrivingDistanceMeters;
    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};

顯示車輛或地點標記的 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'),
  locationProviders: [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 歷程共用資料庫:

  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
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'),
    locationProviders: [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>

如有追蹤的包裹,且指定的 ID 位於 Uluru 附近,地圖現在會顯示該包裹。