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

JavaScript 機群追蹤程式庫能以視覺化方式呈現地點 以近乎即時的方式觀察車隊程式庫會使用 Deliveries API 以視覺化方式呈現運送車輛和工作例如 JavaScript Shipment Tracking Library 其中含有一個直接取代的 JavaScript 地圖元件 標準 google.maps.Map 實體和資料元件 更是如此

元件

JavaScript 機群追蹤程式庫提供視覺化效果的元件 ,以及預計到達時間或所剩時間的 到貨物之間的距離

車隊追蹤地圖檢視

以視覺化方式呈現機群追蹤地圖元件 車輛和工作的位置。如果已知車輛的路線 地圖檢視元件會在車輛沿著預測路徑移動時,以動畫呈現該車輛。

機群追蹤地圖檢視範例

位置提供者

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

交車地點供應商

交車地點供應商顯示了一輛交車的 位置資訊。其中包含車輛位置的資訊 輕鬆完成任務

推送機群位置提供者

貨運車地點提供者顯示多張車輛地點 可能不準確或不適當你可以篩選特定車輛或地點,也可以顯示 整個艦隊

控管追蹤位置的瀏覽權限

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

交車

在 Fleet Engine 中建立送貨車後,就會顯示 而且無論其任務為何,都能在路徑中看見這些資訊

工作位置標記

預定的車輛停靠站會在地圖上顯示為車輛停靠站標記。標記 已完成的任務會以與車輛不同的樣式顯示 。

工作結果的位置會與工作結果標記一起顯示。 顯示結果為成功 (SUCCEEDED) 的工作,一併顯示成功的工作標記 而所有其他工作則會以失敗的工作標記顯示

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

使用 JavaScript 機群追蹤程式庫前,請確認您 熟悉 Fleet Engine 並取得 API 金鑰 接著建立工作 ID 和交車 ID 聲明。

建立工作 ID 與交車 ID 聲明

使用交車地點供應商追蹤貨運車輛: 建立使用工作 ID 和送貨車 ID 憑證附加資訊的 JSON Web Token (JWT)。

如要建立 JWT 酬載,請在授權專區中新增額外憑證附加資訊 同時將 taskiddeliveryvehicleid 設為索引鍵,並設定適當的值 改為 *。使用 Fleet Engine 時建立權杖 服務超級使用者 Cloud IAM 角色。請注意,這會授予廣泛存取權 建立、讀取及修改 Fleet Engine 實體,且僅供共用 與信任的使用者分享資訊

以下範例說明如何建立用於車輛追蹤的權杖 和工作:

{
  "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": {
     "taskid": "*",
     "deliveryvehicleid": "*",
   }
}

建立驗證權杖擷取工具

您可以建立驗證權杖擷取程式,以擷取已取得的權杖 並對伺服器使用服務提出適當聲明 帳戶憑證唯一重要的是 而且絕對不會在任何用戶端上分享您的憑證。否則 將導致系統安全性降低

擷取器必須傳回資料結構 包含兩個欄位,包含在 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
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher,

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

TypeScript

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

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

初始化地圖檢視

載入 JavaScript 歷程共用資料庫後,請初始化 地圖檢視並加進 HTML 網頁。網頁應包含 包含地圖檢視的 &lt;div&gt; 元素。&lt;div&gt; 元素 名稱為 map_canvas

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 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 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.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// 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 wish.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

監聽變更事件

您可以從 deliveryVehicle 物件擷取工作的中繼資訊 使用這個位置提供建議中繼資訊包括預計到達時間及 下一個上車地點或下車地點之前的剩餘距離。變更內容 觸發 update 事件。以下範例 ,顯示如何監聽這些變更事件。

JavaScript

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

TypeScript

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

監聽錯誤

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

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.deliveryVehicleId = '';

TypeScript

locationProvider.deliveryVehicleId = '';

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

查看推送機群

本節說明如何使用 JavaScript 歷程共用功能程式庫 即可查看資產包請務必 從指令碼標記中指定的回呼函式載入程式庫 再執行程式碼

將推送機群位置提供者例項化

JavaScript 機群追蹤程式庫會預先定義位置提供者 從 FleetEngine Deliveries API。 使用 專案 ID 以及權杖擷取工具的參照,藉此將權杖化。

JavaScript

locationProvider =
    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"',
        });

TypeScript

locationProvider =
    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"',
        });

deliveryVehicleFilter 會指定用來篩選顯示該車輛的查詢 即可。這個篩選器會直接傳送至 Fleet Engine。詳情請見 ListDeliveryVehiclesRequest.filter敬上 。

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

監聽變更事件

您可以從 deliveryVehicles 擷取機群的相關中繼資訊 同一個物件中繼資訊包括車輛 ,例如導覽狀態、剩餘距離和自訂屬性; 看 參考說明文件 ,掌握更多詳細資訊。變更中繼資訊會觸發 update 事件。 以下範例說明如何監聽這些變更事件。

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.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

查看貨運車追蹤情形,追蹤貨運車輛

查看機群時,可顯示特定路徑和近期工作 交車。如要這麼做,請將送貨機群位置執行個體化 供應商和送貨車地點供應商,並將這些供應商加入 地圖檢視:

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

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

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

使用雲端式地圖樣式設定

雲端式地圖樣式設定 可讓您為使用 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'
  }
});

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)敬上 標記上。

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

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

使用 MarkerOptions 變更標記樣式

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

JavaScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

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

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

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    params.marker.setLabel(`${stopsLeft}`);
  };

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

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

JavaScript

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

TypeScript

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

篩選可見標記

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

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
    var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
    if (stopsLeft > 10) {
      params.marker.setVisible(false);
    }
  };

跟隨外送車輛時使用折線自訂功能

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

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

同樣地,您也可以指定自訂函式。自訂函式 可根據 Fleet Engine 傳送的資料,套用個別的物件樣式。 這個函式可以根據目前的車輛變更每個物件的樣式 州;例如為 Polyline 物件加上深層顏色或 車輛移動速度較慢時就會較強。你甚至可以透過 並依據 Fleet Engine 以外的來源設定 Polyline 物件樣式 可能不準確或不適當

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

使用 PolylineOptions 變更 Polyline 物件的樣式

以下範例說明如何設定 Polyline 物件的樣式 同時 PolylineOptions。 按照這個模式,使用任意 Polyline 物件自訂任何 Polyline 物件的樣式 折線自訂功能

JavaScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

TypeScript

activePolylineCustomization = {
  strokeWidth: 5,
  strokeColor: 'black',
};

使用自訂函式變更 Polyline 物件的樣式

以下範例說明如何設定有效折線的樣式 可以建構用於自訂元件的物件請按照此模式自訂 使用任何折線自訂設定任何 Polyline 物件的樣式 參數。

JavaScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    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: DeliveryVehiclePolylineCustomizationFunctionParams) => {
    const distance = params.deliveryVehicle.remainingDistanceMeters;
    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});

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

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

    // 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 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. Use FleetEngineDeliveryVehicleLocationProvider
  // as appropriate.
  locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({
    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.deliveryVehicleId = DELIVERY_VEHICLE_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, which includes Fleet Tracking functionality.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
    </script>
  </body>
</html>

如果你是透過 烏魯魯附近的指定的 ID,現在就會在地圖上顯示。