本節說明如何使用 JavaScript 車隊追蹤程式庫查看車隊。這些程序假設您已設定車隊追蹤程式庫並載入地圖。詳情請參閱「設定 JavaScript 車隊追蹤程式庫」。
本文將說明查看車隊時可執行的下列操作:
開始追蹤車隊
如要追蹤車隊,您需要例項化車隊位置資訊提供者,並為地圖檢視區塊設定位置限制,如下列章節所述。
建立車隊位置資訊供應商的例項
JavaScript 車隊追蹤程式庫包含位置資訊供應器,可從 Fleet Engine 擷取多部車輛。
如要例項化,請按照下列步驟操作:
- 使用專案 ID,並參照權杖擷取器。 
- 使用車輛篩選器查詢:車輛篩選器查詢會控管地圖顯示的車輛。篩選條件會傳遞至 Fleet Engine。 - 如為隨選服務,請使用 vehicleFilter,並參閱ListVehiclesRequest.filter
- 如為排定的工作,請使用 deliveryVehicleFilter,並查看ListDeliveryVehiclesRequest.filter
 
- 如為隨選服務,請使用 
- 設定車輛顯示的邊界區域。使用 - locationRestriction限制地圖上顯示車輛的區域。設定完成後,位置資訊供應商才會啟用。您可以在建構函式中或建構函式後設定位置界線。
- 初始化地圖檢視畫面。 
下列範例說明如何針對隨選和排定工作情境,例項化車隊位置資訊供應器。這些範例也說明如何在建構函式中使用 locationRestriction,啟用位置資訊提供工具。
隨選行程
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"',
        });
排定的工作
JavaScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
TypeScript
locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
如要在建構函式後設定 locationRestriction,請在程式碼中稍後加入 locationProvider.locationRestriction,如下列 JavaScript 範例所示。
   // You can choose to not set locationRestriction in the constructor.
   // In this case, the location provider *DOES NOT START* after this line, because
   // no locationRestriction is set.
   locationProvider = new google.maps.journeySharing.DeliveryFleetLocationProvider({
   ... // not setting locationRestriction here
   });
   // You can then set the locationRestriction *after* the constructor.
   // After this line, the location provider is active.
   locationProvider.locationRestriction = {
     north: 1,
     east: 2,
     south: 0,
     west: 1,
   };
使用地圖可視區域設定地點限制
您也可以設定 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;
    }
  });
排定的工作
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 provider 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 provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });
初始化地圖檢視畫面
建構位置資訊供應器後,請以追蹤單一車輛時所用的方式,初始化地圖檢視畫面。
載入 JavaScript 旅程分享程式庫後,請初始化地圖檢視畫面,並將其新增至 HTML 網頁。網頁應包含用於保存地圖檢視區塊的 <div> 元素。在下列範例中,<div> 元素名為 map_canvas。=
隨選行程
JavaScript
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});
// 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 want.
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],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
排定的工作
JavaScript
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});
// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-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 want.
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],
});
// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
監聽事件並處理錯誤
開始追蹤車隊後,您需要監聽事件變更,並處理下列各節所述的任何錯誤。
監聽變更事件
您可以使用位置資訊供應器,從車輛物件擷取車隊的中繼資訊。中繼資訊變更會觸發更新事件。中繼資訊包括車輛屬性,例如導航狀態、剩餘距離和自訂屬性。
詳情請參閱以下說明:
以下範例說明如何監聽這些變更事件。
隨選行程
JavaScript
locationProvider.addListener('update', e => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  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.addListener('update', e => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});
TypeScript
locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});
監聽錯誤
您也想監聽並處理追蹤車輛時發生的錯誤。要求車輛資訊時,非同步發生的錯誤會觸發錯誤事件。
以下範例說明如何監聽這些事件,以便處理錯誤。
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);
});
停止追蹤車隊
如要停止追蹤車隊,請將位置資訊提供工具的邊界設為空值,然後從地圖檢視畫面中移除位置資訊提供工具,如下列章節所述。
將位置資訊提供者界線設為空值
如要停止追蹤車隊,請將位置資訊提供者的界線設為空值。
隨選行程
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
排定的工作
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
從地圖檢視畫面中移除位置資訊供應器
以下範例說明如何從地圖檢視畫面中移除位置資訊供應器。
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
查看車隊時追蹤送貨車輛
如果您使用 Mobility 服務安排工作,可以在同一個地圖檢視畫面中查看車隊,並顯示特定送貨車輛的路線和即將進行的工作。如要這麼做,請同時例項化 Delivery Fleet Location Provider 和 Delivery Vehicle Location Provider,然後將兩者都新增至地圖檢視畫面。例項化後,外送車隊位置資訊供應器就會開始在地圖上顯示外送車輛。以下範例顯示如何例項化兩個位置資訊供應器:
JavaScript
deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery 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 delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});
TypeScript
deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,
          // Optionally, specify location bounds to
          // limit which delivery 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 delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });
deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });
const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});
使用標記自訂功能追蹤送貨車輛
如要啟用運送車輛位置資訊供應器,以便在點選車隊標記時追蹤運送車輛,請按照下列步驟操作:
- 自訂標記並新增點擊動作。 
- 隱藏標記,避免重複標記。 
這些步驟的範例請參閱下列各節。
自訂標記並新增點擊動作
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };
隱藏標記,避免重複標記
從送貨車輛位置資訊提供者隱藏標記,避免為同一部車輛算繪兩個標記:
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params: deliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };