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

JavaScript 機群追蹤程式庫可讓您以近乎即時的方式,呈現車輛車隊的位置。這個程式庫使用 Deliveries API 呈現快遞車輛和任務的視覺化呈現方式。與 JavaScript 運送追蹤程式庫一樣,其中包含的 JavaScript 地圖元件,可用來直接取代標準 google.maps.Map 實體和資料元件,用於與 Fleet Engine 連結。

元件

JavaScript 機群追蹤程式庫提供用來視覺化呈現運送車輛和停靠站的元件,以及用於 ETA 或保持交付狀態的原始資料動態饋給。

機群追蹤地圖檢視

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

機群追蹤地圖檢視範例

位置提供者

位置提供者會使用儲存在 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 旅程共享程式庫。callback 參數會在 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 和權杖工廠的參照,將 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 網頁。您的網頁應包含容納地圖檢視的 <div> 元素。在下例中,<div> 元素的名稱是 map_canvas

JavaScript

const mapView = new 
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'), 
  locationProvider: 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'),
  locationProvider: 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);
});

查看運送機群

本節說明如何使用 JavaScript 歷程共享程式庫查看運送機群。執行程式碼前,請務必從指令碼標記中指定的回呼函式載入程式庫

將運送機群位置提供者執行個體化

JavaScript 機群追蹤程式庫會預先定義位置提供者,該供應商會從 FleetEngine Deliveries API 擷取多輛汽車。請使用您的專案 ID 和權杖擷取工具的參照,將 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);
    }
  }
});

監聽錯誤

要求運送機群資訊以非同步方式引發的錯誤觸發錯誤事件。如需如何監聽這些事件的範例,請參閱「監聽錯誤」。

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

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

使用雲端式地圖樣式設定

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

JavaScript

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

TypeScript

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

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

另一個自訂地圖樣式的方法,是在建立 JourneySharingMapView 時設定 mapOptions

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProvider: locationProvider,
  mapOptions: {
    styles: [
      {
        "featureType": "road.arterial",
        "elementType": "geometry",
        "stylers": [
          { "color": "#CCFFFF" }
        ]
      }
    ]
  }
});

變更路線的樣式和顯示設定

如要設定拍攝路線和預測路線的樣式與顯示設定,請使用自訂樣式選項。詳情請參閱 PolylineOptions 介面

以下範例說明如何設定預期路線的樣式和顯示設定。如要設定已行路線的樣式和顯示設定,請使用 takenRoutePolylineSetup,而非 anticipatedRoutePolylineSetup

JavaScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function anticipatedRoutePolylineSetup({
    defaultPolylineOptions, defaultVisible}) {
  // If this function is not specified, the 
  // PolylineOptions object contained in 
  // defaultPolylineOptions is used to render the
  // anticipated route polyline. visible property sets the
  // polyline's visibility. Modify this object and 
  // pass it back to customize the style of the map.
  defaultPolylineOptions.strokeOpacity = 0.5;
  defaultPolylineOptions.strokeColor = 'red';
  return {
    polylineOptions: defaultPolylineOptions,
    visible: true
  };
}

// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineOptionsSetup = {
  polylineOptions: {
    strokeOpacity: 0.5,
    strokeColor: 'red',
    …
  },
  visible: true,
};

TypeScript

// This function is specified in the 
// JourneySharingMapView constructor's options 
// parameter.
function anticipatedRoutePolylineSetup(options: {
  defaultPolylineOptions: google.maps.PolylineOptions,
  visible: boolean,
}): {
  polylineOptions: google.maps.PolylineOptions,
  visible: boolean,
} {
  // If this function is not specified, the 
  // PolylineOptions object contained in 
  // defaultPolylineOptions is used to render the
  // anticipated route polyline. visible property sets the
  // polyline's visibility. Modify this object and 
  // pass it back to customize the style of the map.
  options.defaultPolylineOptions.strokeOpacity = 0.5;
  options.defaultPolylineOptions.strokeColor = 'red';
  return {
    polylineOptions: options.defaultPolylineOptions,
    visible: true
  };
}

// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineSetup = {
  polylineOptions: {
    strokeOpacity: 0.5,
    strokeColor: 'red',
    …
  },
  visible: true,
};

使用自訂標記功能

您可以使用 JavaScript 機群追蹤程式庫,自訂加入地圖中的標記外觀和風格。方法是指定標記自訂項目 (機群追蹤程式庫接著會套用),再將標記加入地圖,每次更新標記時就會套用。

最簡單的自訂方式是指定套用至相同類型所有標記的 MarkerOptions 物件。物件中指定的變更會在建立每個標記後套用,並覆寫所有預設選項。

另一個進階選項是指定自訂函式。自訂函式可讓您根據資料設定標記樣式,以及在標記中新增互動 (例如點擊處理)。具體來說,機群追蹤功能會將資料傳送給標記代表物件類型的自訂函式,包括車輛、停靠站或工作。這樣就能根據標記元素本身的目前狀態 (例如剩餘停靠站或工作類型) 變更標記樣式。您甚至可以與 Fleet Engine 外部來源的資料進行彙整,並根據該資訊設定標記樣式。

此外,您也可以使用自訂函式來篩選標記顯示設定。方法是在標記上呼叫 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);
    }
  };

顯示車輛或地點標記的 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'), 
  locationProvider: locationProvider,
  automaticViewportMode:
      google.maps.journeySharing
          .AutomaticViewportMode.NONE,
  ...
});

TypeScript

const mapView = new 
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'), 
  locationProvider: 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'), 
    locationProvider: 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>

如果您是採用 Uluru 附近指定 ID 的外送車輛,該車輛現在就會在地圖上顯示。