利用 JavaScript 機群追蹤程式庫追蹤您的車隊

JavaScript 機群追蹤程式庫能以視覺化方式呈現 以近乎即時的方式觀察車隊中的車輛程式庫會使用 On Demand 乘車與運送服務 API 以視覺化方式呈現交通工具和行程。JavaScript 機群 追蹤程式庫包含 取代標準 google.maps.Map 實體和資料元件 與 Fleet Engine 建立連線

元件

JavaScript 機群追蹤程式庫提供元件 車輛和行程路線控點,以及預計到達時間或剩餘時間的原始資料動態饋給 所需距離。

車隊追蹤地圖檢視

「車隊追蹤」地圖檢視元件以視覺化方式呈現車輛位置 包含行程路線控點如果已知車輛的路線,地圖檢視元件 呈現車輛沿著預測路徑移動的動畫。

車隊追蹤地圖檢視
例子

位置提供者

定位服務供應商會使用儲存在 Fleet Engine 中的資訊來傳送位置資訊 將已追蹤的物件資訊匯入旅程分享地圖。

車輛位置供應商

車輛位置資訊服務供應商會顯示單一車輛的位置資訊。 這類圖像包含車輛位置以及目前指派給使用者的行程資訊 。

機群位置提供者

車隊位置提供者會顯示多張車輛的位置資訊。 你可以篩選資料來顯示特定車輛及其位置,或是 顯示整個艦隊的車輛位置。

控管追蹤位置的瀏覽權限

瀏覽權限規則可決定追蹤的位置物件何時可以在地圖上顯示 。注意 - 使用自訂或衍生位置 供應商可能會變更瀏覽權限規則

交通工具

車輛在 Fleet Engine 中製作後,就能立即顯示 Car_state 為 Online 時。也就是說,即使車子多 目前未將任何行程指派給車輛。

路線控點位置標記

路線控點位置標記會指出車輛行駛歷程的起點 開頭,並在結尾與最終目的地結束。路線控點位置 可以定義如下:

  • Origin - 表示車輛行程的起點
  • 中級 - 表示車輛行程的停靠站
  • 目的地 - 表示車輛行程的最終位置

規劃的車輛路線控點在地圖上顯示為起點、中間和 目的地標記。

開始使用 JavaScript 機群追蹤程式庫

使用 JavaScript 機群追蹤程式庫前,請先確認您熟悉 並取得 API 支援,並取得 API 鍵。 然後建立行程 ID 和車輛 ID 聲明。

建立行程 ID 和車輛 ID 聲明

使用車輛位置追蹤車輛位置 provider,請建立包含行程的 JSON Web Token (JWT) 身分證件和車輛 ID 聲明。

如要建立 JWT 酬載,請在授權專區中新增額外憑證附加資訊 使用 tripidvehicleid 鍵,並將每個鍵的 value 設為 *。 權杖應使用 Fleet Engine 服務超級使用者雲端 IAM 角色請注意,這會授予廣泛權限,可建立、讀取及修改機群 引擎實體,建議您只與信任的使用者共用。

下例顯示如何建立車輛追蹤憑證 工作:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "private_key_id_of_consumer_service_account"
}
.
{
  "iss": "superuser@yourgcpproject.iam.gserviceaccount.com",
  "sub": "superuser@yourgcpproject.iam.gserviceaccount.com",
  "aud": "https://fleetengine.googleapis.com/",
  "iat": 1511900000,
  "exp": 1511903600,
  "scope": "https://www.googleapis.com/auth/xapi",
  "authorization": {
    "tripid": "*",
    "vehicleid": "*",
  }
}

建立驗證權杖擷取工具

JavaScript 機群追蹤程式庫要求使用驗證 權杖擷取程式

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

否則,程式庫會使用先前核發且仍然有效的符記, 呼叫擷取程式

您可以建立驗證權杖擷取程式來擷取 取得適當憑證附加資訊 憑證重要的是在 而且絕不會在任何用戶端上分享您的憑證。否則, 系統的安全性狀態

擷取器必須傳回一個資料 結構 包含兩個欄位,包含在 Promise 中:

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

以下範例說明如何建立驗證權杖擷取程式:

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/driver/VEHICLE_ID
    • https://SERVER_URL/token/consumer/TRIP_ID
    • https://SERVER_URL/token/fleet_reader

從 HTML 載入地圖

以下範例說明如何載入 JavaScript 歷程共用程式庫 所指定的網址。「回呼」參數會執行 initMap 函式 API 載入後defer 屬性可讓瀏覽器繼續轉譯 網頁的其他部分。

 <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing&v=beta" defer></script>

追蹤車輛

本節說明如何使用 JavaScript 機群追蹤程式庫執行 。請務必從 安插指令碼,再執行程式碼

將車輛定位服務供應商例項化

JavaScript 機群追蹤程式庫會為 Demand Rides API 和 Deliveries API。請使用專案 ID 和 進行執行個體化

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // vehicleId to immediately start
          // tracking.
          vehicleId: 'your-vehicle-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // vehicleId to immediately start
          // tracking.
          vehicleId: 'your-vehicle-id',
});

初始化地圖檢視

載入 JavaScript 歷程分享程式庫後,請初始化地圖檢視 並將其加入 HTML 網頁您的網頁應包含 &lt;div&gt; 元素 包含地圖檢視的容器&lt;div&gt; 元素在&lt;div&gt; 範例。

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId
                        = 'your-vehicle-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('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId = 'your-vehicle-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('Times Square, New York, NY');
mapView.map.setZoom(14);

監聽變更事件

您可以從 vehicle 物件擷取車輛的相關中繼資訊 使用這個位置提供建議中繼資訊包括預計到達時間以及剩餘時間 距離下一個上車地點或下車地點之前的距離。變更中繼 資訊就會觸發 update 事件。以下範例說明如何監聽 這些變更

JavaScript

locationProvider.addListener('update', e => {
  // e.vehicle contains data that may be
  // useful to the rest of the UI.
  if (e.vehicle) {
    console.log(e.vehicle.vehicleState);
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  // e.vehicle contains data that may be useful to the rest of the UI.
  if (e.vehicle) {
    console.log(e.vehicle.vehicleState);
  }
});

監聽錯誤

要求車輛資訊觸發事件因非同步而產生的錯誤 錯誤事件。以下範例說明如何在 來處理錯誤。

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);
});

停止追蹤

如要讓地點服務供應商停止追蹤車輛,請移除車輛 ID 向定位服務供應商提供

JavaScript

locationProvider.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

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

下例說明如何從地圖檢視中移除地點提供者。

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

查看車隊

本節說明如何使用 JavaScript 歷程共用功能程式庫查看 車隊請務必透過回呼函式載入程式庫 再執行程式碼

將車輛車隊定位服務供應商例項化

JavaScript 機群追蹤程式庫會預先定義一個位置提供者, 從 On Demand Rides and Deliveries API 中擷取多輛車。使用 專案 ID 以及權杖擷取工具的參照,以便將權杖擷取作業。

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

vehicleFilter 會指定用來篩選地圖上顯示的車輛的查詢。 這個篩選器會直接傳送至 Fleet Engine。詳情請見 ListVehiclesRequest

locationRestriction 會限制地圖中車輛的顯示區域, 也會控制是否啟用位置追蹤功能。定位追蹤 才會開始執行

建構位置提供器後,初始化地圖 檢視畫面

使用地圖可視區域設定位置限制

locationRestriction 邊界可設定為與 顯示地圖檢視

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

監聽變更事件

您可以從 vehicles 物件擷取機群的中繼資訊 使用這個位置提供建議中繼資訊包括車輛屬性 例如導航狀態、前往下一個路線控點的距離和自訂屬性看 參考資料 說明文件 ,掌握更多詳細資訊。變更中繼資訊會觸發更新事件。 以下範例說明如何監聽這些變更事件。

JavaScript

locationProvider.addListener('update', e => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
  // e.vehicles contains data that may be useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});

監聽錯誤

要求車輛車隊資訊時因非同步方式產生的錯誤 觸發錯誤事件如需瞭解如何監聽這些事件的範例,請參閱 監聽錯誤

停止追蹤

如要讓位置提供者停止追蹤機群,請設定 將位置提供者設為空值。

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

下例說明如何從地圖檢視中移除地點提供者。

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

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

使用雲端式地圖樣式設定

雲端式地圖樣式設定 可讓您為使用 Google 地圖的任何應用程式建立及編輯地圖樣式 ,無須變更任何程式碼。 地圖樣式會儲存在 Cloud 專案中,做為地圖 ID。如果要將樣式套用到 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'
  }
});

TypeScript

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

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

還有一種自訂地圖樣式設定的方式 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敬上 物件這個物件會套用到所有相同類型標記。在 物件會在每個標記建立後套用,覆寫任何預設值 只要設定成「自動重新啟動」 和「在主機維護期間」選項即可

如要採用更進階的選項,您可以指定自訂函式。 自訂函式還可讓您根據資料設定標記樣式, 例如在標記中加入互動元素,例如點擊處理。具體來說,機群 追蹤會將資料傳送至自訂函式 標記代表:車輛、停靠站或工作如此一來,標記樣式就會 根據標記元素本身的目前狀態變更;舉例來說 剩餘的停靠站數量或任務類型。您甚至可以彙整來自下列來源的資料: ,並根據該資訊設定標記樣式。

此外,您也可以使用自訂函式來篩選標記的顯示設定。 方法是呼叫 setVisible(false)敬上 標記上。

不過,基於效能考量,建議您使用原生廣告進行篩選 位置提供者篩選功能,例如 FleetEngineFleetLocationProvider.vehicleFilter。 也就是說,如果需要其他篩選功能 以便自訂篩選

機群追蹤程式庫提供下列自訂參數:

使用 MarkerOptions 變更標記樣式

以下範例說明如何透過 MarkerOptions 物件。請按照此模式自訂任一樣式的樣式 標記,使用上述任一標記自訂參數。

JavaScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

使用自訂函式變更標記樣式

以下範例說明如何設定車輛標記樣式。追蹤 這個模式會使用任何標記自訂任何標記的樣式 剛才提到的自訂參數

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

在標記中加入點擊處理方式

以下範例說明如何在車輛標記中新增點擊處理方式。 依照這個模式,在任何使用標記的標記中加入點擊處理方式 剛才提到的自訂參數

JavaScript

vehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // Perform desired action.
      });
    }
  };

篩選可見標記

以下範例說明如何篩選可見的車輛標記。 請按照這個模式,使用任何自訂標記篩選任何標記 參數。

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
      if (remainingWaypoints > 10) {
        params.marker.setVisible(false);
      }
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
    if (remainingWaypoints > 10) {
      params.marker.setVisible(false);
    }
  };

行經車輛時使用折線自訂功能

還能透過機群追蹤程式庫自訂 地圖上追蹤車輛的路線。程式庫會建立一個 google.maps.Polyline 物件狀態 「path」。 您可以指定折線自訂項目來設定 Polyline 物件的樣式。 接著,程式庫會在兩種情況下套用這些自訂項目 物件寫入地圖,以及用於物件的資料已變更時。

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

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

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

使用 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.vehicle.waypoints[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: VehiclePolylineCustomizationFunctionParams) => {
    const distance = params.vehicle.waypoints[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 =
  FleetEngineVehicleLocationProvider.
      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) => {
    FleetEngineVehicleLocationProvider.
        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 =
  FleetEngineVehicleLocationProvider.
      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: VehiclePolylineCustomizationFunctionParams) => {
    FleetEngineVehicleLocationProvider.
        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});

// (Assumes a vehicle location provider.)
locationProvider.addListener('update', e => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off point.`);

    // 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});

// (Assumes a vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off.`);
    // 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,
  ...
});

取代現有地圖

您可以取代含有標記或其他自訂項目的現有地圖 而不會失去這些自訂設定

舉例來說,假設您的網頁含有標準 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 Oracle Park Stadium
        var oraclePark = { lat: 37.780087547237365, lng: -122.38948437884427 };,
        // 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 Oracle Park
        var marker = new google.maps.Marker({ position: oraclePark, 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. Use FleetEngineVehicleLocationProvider
        // as appropriate.
        locationProvider = new google.maps.journeySharing.FleetEngineVehicleLocationProvider({
          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
        });

      mapView.addListener('ready', () => {
        locationProvider.vehicleId = VEHICLE_ID;

          // (4) Add customizations like before.

          // The location of Oracle Park
          var oraclePark = {lat: 37.77995187146094, lng: -122.38957020952795};
          // 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 Oracle Park
          var marker = new google.maps.Marker({position: oraclePark, 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, which includes Fleet Tracking functionality.
    -->
    <script
      defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing&v=beta"
    ></script>
  </body>
</html>

如果你在 Oracle Park 附近操作含有指定 ID 的車輛,該車輛會在 。