使用 JavaScript 跟踪行程

请选择平台: Android iOS JavaScript

当您分享旅程时,您的消费者应用会显示 向消费者展示合适的车辆。为此,您的应用需要开始分享 行程,在行程中更新行程进度,以及停止分享 。

本文档介绍了此流程中的以下关键步骤:

  1. 设置地图
  2. 初始化地图并显示共享旅程
  3. 更新并跟踪行程进度
  4. 停止分享行程
  5. 处理旅程分享错误

设置地图

要在您的 Web 应用中跟踪货物取货或送货情况,您需要加载地图 并实例化消费者 SDK,以开始跟踪您的历程。您可以加载 新地图或使用现有地图。然后使用初始化 函数来实例化 Consumer SDK,以便地图视图对应于 所跟踪商品的位置。

使用 Google Maps JavaScript API 加载新地图

要创建新地图,请在您的 Web 应用中加载 Google Maps JavaScript API。通过 下例显示了如何加载 Google Maps JavaScript API、启用 SDK,并触发初始化检查。

  • callback 参数会在 API 加载后运行 initMap 函数。
  • defer 属性可让浏览器继续呈现 页面。

使用 initMap 函数实例化使用方 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);
});

后续步骤

设置地图样式