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

「JavaScript 運送追蹤程式庫」能以視覺化方式呈現地點 Fleet Engine 追蹤到的車輛和感興趣的地點。圖書館 包含可直接取代的 JavaScript 地圖元件 標準 google.maps.Map 實體和資料元件 更是如此使用 JavaScript 運送追蹤程式庫 可以透過網頁應用程式,提供可自訂的動態運送追蹤服務。

元件

JavaScript 運送追蹤程式庫提供視覺化的元件 車輛和路線推進至目的地的過程,以及原始資料 提供司機的預計到達時間或剩餘的行駛距離。

運送追蹤地圖檢視

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

出貨地點供應商

出貨地點供應商為已追蹤物件提供位置資訊 追蹤運送追蹤和最終里程數的運送情形

你可以使用運送地點供應商追蹤以下資訊:

  • 商品的取貨或送貨地點。
  • 交車的位置和路線。

已追蹤的位置物件

位置提供者可追蹤車輛和車輛等物件的位置

目的地位置

目的地位置是指旅程的終點。寄送 負責規劃的工作地點

車輛位置

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

驗證權杖擷取工具

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

樣式選項

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

控管追蹤位置的瀏覽權限

本節說明地圖上追蹤物件的顯示控制項。 這些規則適用於兩種物件類別:

  • 地點標記
  • 工作資料

位置標記顯示設定

起點和目的地的所有位置標記永遠都會顯示在地圖上。 舉例來說,送貨地點一律會顯示在地圖上。 無論放送狀態為何

工作資料顯示設定

本節說明工作資料適用的預設瀏覽權限規則。 例如車輛位置和剩餘路線你可以自訂許多工作 並非全部:

  • 無法使用的工作 - 您無法自訂這些工作的顯示設定。
  • 進行中的車輛工作 - 您可以自訂這些類型的任務。
  • 非使用中的車輛工作 -- 您無法自訂這些工作的顯示設定。

無法使用的工作

如果有至少一項無法使用的工作 (例如 (例如駕駛休息或收回車輛) 無法看到所追蹤任務的車輛。預計抵達時間 仍可計算時間和預估工作完成時間。

進行中的車輛任務

TaskTrackingInfo敬上 物件提供許多資料元素,而這些資料元素可在 運送追蹤資料庫。根據預設,當工作 且車輛位於車輛停靠站的 5 個停靠站內。 工作完成或取消時,瀏覽權限就會結束。這些欄位包括 如下:

  • 路線折線
  • 預計到達時間
  • 預估工作完成時間
  • 與工作相關的剩餘行車距離
  • 剩餘停靠站數量
  • 車輛位置

您可以分別針對各項任務自訂瀏覽權限設定 這個 TaskTrackingViewConfig敬上 在 Fleet Engine 內建立或更新工作時執行。這會建立 個別資料元素可使用時機的規則 (以下為顯示選項):

  • 剩餘停靠站數量
  • 距離預估抵達時間還有
  • 剩餘行車距離
  • 一律顯示
  • 一律不顯示

請注意,每個資料元素都只能與一個瀏覽權限選項建立關聯。 您無法使用 OR 或 AND 來結合條件。

自訂範例如下:自訂的規則如下:

  • 如果車輛位於 3 站內,顯示路線折線。
  • 如果剩餘行車距離短於 5000 公尺,則顯示預計到達時間。
  • 一律不顯示剩餘的停靠站計數。
  • 其他欄位保留了 車輛與車輛停靠站的 5 個停靠站內。
"taskTrackingViewConfig": {
  "routePolylinePointsVisibility": {
    "remainingStopCountThreshold": 3
  },
  "estimatedArrivalTimeVisibility": {
    "remainingDrivingDistanceMetersThreshold": 5000
  },
  "remainingStopCountVisibility": {
    "never": true
  }
}

您也可以透過下列方式自訂專案的預設瀏覽權限設定: 與支援團隊聯絡

路線折線和車輛位置顯示規則:

顯示路線折線時,必須一併顯示車輛位置, 否則車輛位置則可由折線的結尾表示。沒錯 表示路線折線不能有限制較寬鬆的顯示設定選項。

請務必遵守這些規則,才能提供有效的路線折線 / 車輛 地區瀏覽權限組合:

  • 當路線折線和車輛位置有相同顯示選項時 類型:

    • 如果顯示選項是剩餘的停靠站次數、持續到預計到達時間,或是 剩餘行車距離,路線折線必須提供小於 等於或等於車輛的這個可見度選項設定的值 或 HTTP/HTTPS 位置範例如下:
    "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 運送追蹤」 來自指定網址的程式庫。回呼參數會執行 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 網頁。網頁應包含 包含地圖檢視的 &lt;div&gt; 元素。在以下範例中 &lt;div&gt; 元素的名稱是 &lt;div&gt;

為避免競爭狀況,請為地點供應商設定追蹤 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);
});

處理錯誤

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

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 地圖的任何應用程式建立及編輯地圖樣式 ,無須變更任何程式碼。 地圖樣式會儲存為地圖 ID,並儲存在 Cloud 專案中。如要將樣式套用至 您的 JavaScript 運送追蹤地圖,指定 mapId敬上 建立 JourneySharingMapView 值區無法變更「mapId」欄位 或在 JourneySharingMapView 執行個體化後新增。下列 範例說明如何啟用先前建立且具有地圖 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.
});

使用程式碼式地圖樣式設定

還有一種自訂地圖樣式設定的方式 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 運送追蹤程式庫,您可以自訂外觀和 其風格。方法是指定標記 「運送追蹤程式庫」會在之後 標記到地圖上,並隨著每次標記更新。

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

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

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

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

使用 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.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,現在就會在地圖上顯示。