使用 JavaScript 跟踪行程

请选择平台Android iOS JavaScript

当您关注行程时,您的消费者应用会向消费者显示相应车辆的位置。为此,您的应用需要开始关注行程、在行程期间更新行程进度,并在行程完成时停止关注行程。

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

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

设置地图

如需在 Web 应用中关注货件取货或送货,您需要加载地图并实例化 Consumer SDK 以开始跟踪行程。您可以加载新地图,也可以使用现有地图。然后,您可以使用初始化函数实例化 Consumer SDK,以便地图视图与被跟踪商品的位置相对应。

使用 Google Maps JavaScript API 加载新地图

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

  • callback 参数会在 API 加载后运行 initMap 函数。
  • defer 属性让浏览器能够在 API 加载期间继续渲染网页的其余部分。

使用 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 具有针对 Fleet Engine 网约车 API 的预定义位置信息提供程序。使用您的项目 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);
});

后续步骤

为地图设置样式