在 JavaScript 中追蹤行程

選取平台: Android iOS JavaScript

分享歷程時,消費者應用程式會顯示 適合供消費者使用若要這麼做,您的應用程式必須開始分享 也可在行程期間更新歷程進度,並停止分享 旅程中的點。

本文件說明此程序中的下列重要步驟:

  1. 設定地圖
  2. 初始化地圖並顯示分享的旅程
  3. 更新及追蹤行程進度
  4. 停止分享旅程
  5. 處理歷程共用錯誤

設定地圖

如要在網頁應用程式中追蹤取貨或取貨地點,請載入地圖 並將 Consumer SDK 例項化,即可開始追蹤歷程。您可以載入 建立新的地圖或使用現有地圖接著使用初始化 函式,將 Consumer SDK 執行個體化,讓地圖檢視與 所追蹤項目的位置。

使用 Google Maps JavaScript API 載入新地圖

如要建立新地圖,請在網頁應用程式中載入 Google Maps JavaScript API。 以下範例說明如何載入 Google Maps JavaScript API、啟用 並觸發初始化檢查。

  • callback 參數會在 API 載入後執行 initMap 函式。
  • defer 屬性可讓瀏覽器繼續轉譯其餘內容的 頁面。

使用 initMap 函式將 Consumer SDK 執行個體化。例如:

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

載入現有地圖

您也可以載入透過 Google Maps JavaScript API 建立的現有地圖, 例如您已使用的資源

舉例來說,假設您的網頁含有標準 google.maps.Map 標記顯示於下列 HTML 程式碼中定義的實體。這個 會在結尾的回呼中使用相同的 initMap 函式,顯示地圖:

    <!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 Pier 39 in San Francisco
          var pier39 = {lat: 37.809326, lng: -122.409981};
          // 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 Pier 39
          var marker = new google.maps.Marker({position: pier39, map: map});
        }
        </script>
        <!-- Load the API from the specified URL.
           * The defer attribute allows the browser to render the page while the API loads.
           * The key parameter contains your own API key.
           * 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>

取代現有地圖

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

舉例來說,如果您的網頁含有標準 google.maps.Map 實體,可以取代地圖並保持 來標記物件本節將說明相關步驟。

如要取代地圖並維護自訂功能,請將旅程分享至 定義 HTML 網頁,且在網頁的 如下:

  1. 新增驗證權杖工廠程式碼。

  2. initMap() 函式中初始化位置提供者。

  3. initMap() 函式中初始化地圖檢視。檢視表包含 。

  4. 將自訂項目移至地圖檢視的回呼函式中 和初始化。

  5. 將位置程式庫加入 API 載入器。

以下範例顯示要進行變更。如果您使用 現在指定的 ID 會顯示在烏魯魯附近:

    <!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
    async function authTokenFetcher(options) {
      // options is a record containing two keys called
      // serviceType and context. The developer should
      // generate the correct SERVER_TOKEN_URL and request
      // based on the values of these fields.
      const response = await fetch(SERVER_TOKEN_URL);
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          const data = await response.json();
          return {
            token: data.Token,
            expiresInSeconds: data.ExpiresInSeconds
          };
    }

    // Initialize and add the map
    function initMap() {
      // (2) Initialize location provider.
      locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
        projectId: "YOUR_PROVIDER_ID",
        authTokenFetcher,
      });

      // (3) Initialize map view (which contains the map).
      const mapView = new google.maps.journeySharing.JourneySharingMapView({
        element: document.getElementById('map'),
        locationProviders: [locationProvider],
        // any styling options
      });

      locationProvider.tripId = TRIP_ID;

        // (4) Add customizations like before.

        // The location of Pier 39 in San Francisco
        var pier39 = {lat: 37.809326, lng: -122.409981};
        // 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 Pier 39
        var marker = new google.maps.Marker({position: pier39, 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 SDK to the API loader.
        -->
        <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
        </script>
      </body>
    </html>

初始化地圖並顯示分享的旅程

當行程開始時,應用程式需要將行程地點提供者例項化 然後初始化地圖以開始分享旅程。請參閱下列各節 。

將行程地點提供者例項化

JavaScript SDK 有預先定義的位置提供者 。使用您的專案 ID 和 對權杖工廠的參照,以對其執行個體化。

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

初始化地圖檢視

載入 JavaScript SDK 後,請初始化 地圖檢視並加進 HTML 網頁。網頁應包含 包含地圖檢視的 <div> 元素。<div> 元素 在以下範例中名為 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 trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
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 trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

更新及追蹤行程進度

應用程式應監聽事件並更新行程進度,做為旅程 。您可以從工作物件擷取行程的相關中繼資訊 使用這個位置提供建議中繼資訊包括預計到達時間及 在上車或下車前剩餘距離。中繼資訊變更 觸發 update 事件。以下範例說明如何監聽這些程式 變更事件。

JavaScript

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

TypeScript

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

停止分享旅程

行程結束時,您必須讓定位服務供應商停止追蹤行程 行程。如要這麼做,請移除行程 ID 以及位置供應商請參閱以下各節中的範例。

從地點提供者中移除行程 ID

以下範例說明如何從地點提供者移除行程 ID。

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

處理歷程共用錯誤

要求行程資訊觸發時,以非同步方式發生的錯誤 錯誤事件。以下範例說明如何監聽這些事件 處理錯誤。

JavaScript

locationProvider.addListener('error', e => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

後續步驟

設定地圖樣式