JavaScript 版 Consumer SDK 使用入门

借助 JavaScript SDK,您可以直观呈现在 Fleet Engine 中跟踪的车辆位置和感兴趣的位置。该库包含一个 JavaScript 地图组件,可直接替换标准 google.maps.Map 实体和数据组件,以便与 Fleet Engine 连接。借助 JavaScript SDK,您可以通过 Web 应用提供可自定义的行程和订单进度体验。

组件

JavaScript SDK 提供了用于直观呈现车辆和航点的组件,以及司机预计到达时间或剩余行驶距离的原始数据 Feed。

行程和订单进度地图视图

地图视图组件可直观呈现车辆和航点的位置。如果车辆的路线已知,地图视图组件会在该车辆沿预测路径移动时为其添加动画效果。

行程位置信息提供程序

JavaScript SDK 包含一个行程位置信息提供程序,该提供程序会将所跟踪对象的位置信息馈送到行程和订单进度图中。

您可以使用行程位置信息提供程序跟踪以下信息:

  • 行程的上车点或下车点。
  • 分配给行程的车辆的位置和路线。

跟踪的位置对象

位置提供程序会跟踪对象(如航点和车辆)的位置。

出发地

出发地是旅程的起点。它标记了上车地点。

目标位置

目的地是指旅程的结束地点。它标记着下车点。

航点位置

航点位置是指所跟踪的行程路线上的任意位置。例如,公交路线上的每个经停点都是一个航点位置。

车辆位置

车辆位置是指跟踪的车辆位置。可以选择包含车辆的路线。

身份验证令牌提取工具

如需控制对存储在 Fleet Engine 中的位置数据的访问权限,您必须在服务器上为 Fleet Engine 实现 JSON Web 令牌 (JWT) 创建服务。然后,使用 JavaScript SDK 对对位置数据的访问进行身份验证,并在您的 Web 应用中实现身份验证令牌提取器

样式选项

标记和多段线样式决定了地图上跟踪的地点对象的外观和风格。您可以使用自定义样式选项来更改默认样式,使其与 Web 应用的样式相匹配。

控制所跟踪位置的可见性

本部分介绍了针对 Fleet Engine 预定义位置信息提供程序在地图上跟踪的位置对象的可见性规则。自定义或派生的位置信息提供程序可能会更改可见性规则。

车辆

从分配给行程到下车这段时间,共享车辆始终可见。如果行程已取消,车辆将不再可见。

所有其他地点标记

出发地、目的地和航点的所有其他位置标记始终显示在地图上。例如,无论行程或送货的状态如何,拼车下车点或货物送货地点都始终显示在地图上。

JavaScript SDK 使用入门

在使用 JavaScript SDK 之前,请确保您已熟悉 Fleet Engine获取 API 密钥

如需跟踪拼车行程,请先创建行程 ID 版权主张。

创建行程 ID 申领

如需使用行程位置信息提供程序跟踪行程,请创建带有行程 ID 声明的 JSON Web 令牌 (JWT)。

要创建 JWT 载荷,请使用键 tripid 在“授权”部分添加额外的声明,并将其值设置为行程 ID。

以下示例展示了如何创建用于按行程 ID 跟踪的令牌:

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "private_key_id_of_consumer_service_account"
}
.
{
  "iss": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "sub": "consumer@yourgcpproject.iam.gserviceaccount.com",
  "aud": "https://fleetengine.googleapis.com/",
  "iat": 1511900000,
  "exp": 1511903600,
  "scope": "https://www.googleapis.com/auth/xapi",
  "authorization": {
     "tripid": "tid_12345",
   }
}

创建身份验证令牌提取程序

您可以创建身份验证令牌提取程序,以使用项目的服务帐号证书检索服务器上使用适当声明创建的令牌。请务必在您的服务器上创建令牌,切勿在任何客户端上共享您的证书。否则,会危及系统的安全性。

提取程序必须返回包含两个字段的数据结构,并封装在 Promise 中:

  • 一个字符串 token
  • 数字 expiresInSeconds。令牌在提取后在这段时间内过期。

满足以下任一条件时,JavaScript 使用方 SDK 会通过身份验证令牌提取程序请求令牌:

  • 它没有有效的令牌,例如,当它在新的网页加载时未调用提取器,或者提取器未返回令牌时。
  • 之前提取的令牌已过期。
  • 之前提取的令牌将在过期后的 1 分钟内完成。

否则,SDK 会使用之前签发的仍然有效的令牌,并且不会调用提取器。

以下示例展示了如何创建身份验证令牌提取程序:

JavaScript

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

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.jwt,
    expiresInSeconds: data.expirationTimestamp - Date.now(),
  };
}

在实现用于创建令牌的服务器端端点时,请注意以下几点:

  • 端点必须返回令牌的过期时间;在上面的示例中,它被指定为 data.ExpiresInSeconds
  • 如示例中所示,身份验证令牌提取程序必须将过期时间(从提取之时算起,以秒为单位)传递给库。
  • SERVER_TOKEN_网址 取决于您的提供程序实现,以下是示例提供程序的网址:
    • https://SERVER_URL/token/driver/VEHICLEID
    • https://SERVER_URL/token/consumer/TRIPID

从 HTML 加载地图

以下示例展示了如何从指定网址加载 JavaScript SDK。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 SDK 跟踪拼车或送餐行程。请务必先从脚本标记中指定的回调函数加载库,然后再运行代码。

实例化行程位置信息提供程序

JavaScript SDK 为 Fleet Engine Ridesharing 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,
          authTokenFetcher,

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

初始化地图视图

加载 JavaScript SDK 后,初始化地图视图并将其添加到 HTML 页面中。您的网页应包含用于存储地图视图的 <div> 元素。在以下示例中,<div> 元素名为 map_canvas

为避免出现竞态条件,请在地图初始化后调用的回调中设置位置信息提供程序的行程 ID。

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerCustomization: vehicleMarkerCustomization,
  activePolylineCustomization: activePolylineCustomization,
  // 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 will start 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 wish.
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.
  vehicleMarkerCustomization: vehicleMarkerCustomization,
  activePolylineCustomization: activePolylineCustomization,
  // 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.
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 wish.
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);
});

处理错误

因请求行程信息而异步出现的错误会触发错误事件。以下示例展示了如何监听这些事件以处理错误。

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

注意:请务必将库调用封装在 try...catch 块中,以处理意外错误。

停止跟踪

如需让位置信息提供程序停止跟踪行程,请从位置信息提供程序中移除该行程 ID。

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

从地图视图中移除位置信息提供程序

以下示例展示了如何从地图视图中移除位置信息提供程序。

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

自定义基本地图的外观和风格

如需自定义地图组件的外观和风格,请使用云端工具或直接在代码中设置选项,以设置地图样式

使用云端地图样式设置

借助云端地图样式设置功能,您可以通过 Google Cloud 控制台为使用 Google 地图的所有应用创建和修改地图样式,而无需对代码进行任何更改。地图样式会以地图 ID 的形式保存到您的 Cloud 项目中。如需向您的 JavaScript SDK 地图应用样式,请在创建 JourneySharingMapView 时指定 mapId 和任何其他 mapOptions。在 JourneySharingMapView 实例化后,无法更改或添加 mapId 字段。以下示例展示了如何使用地图 ID 启用之前创建的地图样式。

JavaScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // and any other styling options.
});

TypeScript

const mapView = new google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  mapOptions: {
    mapId: 'YOUR_MAP_ID'
  }
  // and any other styling options.
});

使用基于代码的地图样式设置

自定义地图样式的另一种方法是,在创建 JourneySharingMapView 时设置 mapOptions

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 SDK,您可以自定义添加到地图的标记的外观和风格。为此,您可以指定标记自定义,然后 JavaScript SDK 会在将标记添加到地图和每次更新标记之前应用这些自定义设置。

最简单的自定义方法是指定一个 MarkerOptions 对象,该对象将应用于相同类型的所有标记。对象中指定的更改会在创建每个标记后应用,覆盖所有默认选项。

更高级的选项是指定自定义函数。借助自定义函数,您可以根据数据设置标记的样式,以及为标记添加互动性,例如点击处理。具体而言,行程和订单进度功能会将与标记所代表的对象类型(车辆、出发地、航点或目的地)相关的数据传递给自定义函数。这样一来,标记样式可以根据标记元素本身的当前状态而变化;例如,车辆完成行程前剩余的航点数量。您甚至可以联接来自 Fleet Engine 外部来源的数据,并根据该信息设置标记样式。

JavaScript SDK 在 FleetEngineTripLocationProviderOptions 中提供以下自定义参数:

使用 MarkerOptions 更改标记的样式

以下示例展示了如何使用 MarkerOptions 对象配置车辆标记的样式设置。遵循此模式,使用前面列出的任何标记自定义设置来自定义任何标记的样式。

JavaScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

使用自定义函数更改标记的样式

以下示例展示了如何配置车辆标记的样式设置。您可以按照此模式使用前面列出的任意标记自定义参数来自定义任何标记的样式。

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var distance = params.trip.remainingWaypoints.length;
    params.marker.setLabel(`${distance}`);
  };

TypeScript

vehicleMarkerCustomization =
  (params: TripMarkerCustomizationFunctionParams) => {
    const distance = params.trip.remainingWaypoints.length;
    params.marker.setLabel(`${distance}`);
};

向标记添加点击处理

以下示例展示了如何向车辆标记添加点击处理。按照此模式使用前面列出的任意标记自定义参数,向任意标记添加点击处理方式。

JavaScript

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

TypeScript

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

使用自定义多段线

借助 JavaScript SDK,您还可以自定义地图上行程路线的外观和风格。该库会为车辆的有效或剩余路径中的每对坐标创建一个 google.maps.Polyline 对象。您可以指定多段线自定义项,以设置 Polyline 对象的样式。然后,该库会在两种情况下应用这些自定义设置:将对象添加到地图之前,以及用于对象的数据发生更改时。

与标记自定义类似,您可以指定一组 PolylineOptions,以便在创建或更新时应用于所有匹配的 Polyline 对象。

同样,您可以指定自定义函数。借助自定义函数,您可以根据 Fleet Engine 发送的数据对对象进行单独的样式设置。该函数可以根据车辆的当前状态更改每个对象的样式;例如,将 Polyline 对象的颜色设置为更深的阴影,或者在车辆行驶速度较慢时加深对象的样式。您甚至可以从 Fleet Engine 外部的来源进行联接,并根据该信息设置 Polyline 对象的样式。

您可以使用 FleetEngineTripLocationProviderOptions 中提供的参数指定自定义设置。您可以为车辆行程中的不同路径状态(已行驶、正在行驶或尚未行驶)设置自定义设置。具体参数如下所示:

使用 PolylineOptions 更改 Polyline 对象的样式

以下示例展示了如何使用 PolylineOptions 配置 Polyline 对象的样式。遵循此模式,使用前面列出的多段线自定义设置来自定义任何 Polyline 对象的样式。

JavaScript

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

TypeScript

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

使用自定义函数更改 Polyline 对象的样式

以下示例展示了如何配置活跃 Polyline 对象的样式设置。遵循此模式,使用前面列出的多段线自定义参数来自定义任何 Polyline 对象的样式。

JavaScript

// Color the Polyline objects in green if the vehicle is nearby.
activePolylineCustomization =
  (params) => {
    const distance = params.trip.remainingWaypoints[0].distanceMeters;
    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: TripPolylineCustomizationFunctionParams) => {
    const distance = params.trip.remainingWaypoints[0].distanceMeters;
    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};

渲染可感知流量的 Polyline 对象

Fleet Engine 会返回后续车辆的有效路径和剩余路径的交通速度数据。您可以使用此信息,根据 Polyline 对象的车流速度为其设置样式:

JavaScript

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineTripLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params) => {
    FleetEngineTripLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

TypeScript

// Color the Polyline objects according to their real-time traffic levels
// using '#05f' for normal, '#fa0' for slow, and '#f33' for traffic jam.
activePolylineCustomization =
  FleetEngineTripLocationProvider.
      TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION;

// Or alter the objects further after the customization function has been
// run -- in this example, change the blue for normal to green:
activePolylineCustomization =
  (params: TripPolylineCustomizationFunctionParams) => {
    FleetEngineTripLocationProvider.
        TRAFFIC_AWARE_ACTIVE_POLYLINE_CUSTOMIZATION_FUNCTION(params);
    for (const polylineObject of params.polylines) {
      if (polylineObject.get('strokeColor') === '#05f') {
        polylineObject.setOptions({strokeColor: 'green'});
      }
    }
  };

为车辆或位置标记显示 InfoWindow

您可以使用 InfoWindow 显示有关车辆或位置标记的更多信息。

以下示例展示了如何创建 InfoWindow 并将其附加到车辆标记:

JavaScript

// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
    {disableAutoPan: true});

locationProvider.addListener('update', e => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

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

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineTripLocationProviderUpdateEvent) => {
  const stopsCount = e.trip.remainingWaypoints.length;
  infoWindow.setContent(
      `Your vehicle is ${stopsCount} stops away.`);

  // 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,
  ...
});

替换现有地图

您可以使用 JavaScript SDK 替换包含标记或其他自定义设置的现有地图,而不丢失这些自定义内容。

例如,假设您有一个网页,其中包含一个显示标记的标准 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, centered at Uluru
  var map = new google.maps.Map(document.getElementById('map'));
  map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

  // The marker, 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 SDK,请执行以下操作:

  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
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 Uluru
    var uluru = {lat: -25.344, lng: 131.036};
    // The map, centered at Uluru
    var map = mapView.map;
    map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});
    // The marker, 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 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>

如果您使用指定 ID 在乌鲁鲁附近运营行程,则该行程现在将渲染在地图上。