使用 JavaScript 物流跟踪库跟踪运单

通过 JavaScript 货运跟踪库,您可以直观呈现 Fleet Engine 中跟踪的车辆和感兴趣的位置。图书馆 包含可直接替换的 JavaScript 地图组件 标准 google.maps.Map 实体和数据组件进行连接 Fleet Engine使用 JavaScript 货运跟踪库 您就可以通过自己的 Web 应用提供可自定义的动画式货运跟踪体验。

组件

JavaScript 物流跟踪库提供了实现可视化的组件 以及原始数据 提供司机预计到达时间或剩余行驶距离的 Feed。

货运跟踪地图视图

地图视图组件可直观呈现车辆和目的地的位置。 如果车辆的路线已知,地图视图组件会以动画形式呈现 在车辆沿预测路径移动时,预测该车辆的位置。

发货地点提供商

配送地点提供商为所跟踪对象提供位置信息 添加到物流跟踪地图中,以进行第一公里和最后一公里的物流跟踪。

您可以使用配送地址提供商跟踪以下信息:

  • 货物的自提或送货地点。
  • 送货车辆的位置和路线。

跟踪的位置对象

位置信息提供程序会跟踪车辆和外部物体等物体的位置, 目标。

目标位置

目的地是指旅程的结束地点。配送 计划的位置。

车辆位置

车辆位置是指跟踪的车辆位置。它可能会选择性地 添加车辆的路线。

身份验证令牌提取工具

要控制对存储在 Fleet Engine 中的位置数据的访问权限,您必须 为 Fleet Engine 实现 JSON Web 令牌 (JWT) 创建服务 。然后,实现身份验证令牌提取器(作为 实现自己的 Web 应用,使用 JavaScript 历程共享库 对位置数据的访问权限进行身份验证。

样式选项

标记和多段线样式决定了 在地图上跟踪的地点对象。您可以使用 自定义样式选项,用于更改默认样式以匹配样式 代码。

控制所跟踪位置的可见性

本部分介绍了地图上所跟踪对象的可见性控制。 这些规则适用于两类对象:

  • 地点标记
  • 任务数据

位置标记的可见性

起点和终点的所有位置标记始终显示在地图上。 例如,某个送货地点始终显示在地图上, 而无论投放状态如何

任务数据可见性

本部分介绍了适用于任务数据的默认可见性规则, 例如车辆位置和剩余路线。你可以自定义许多任务 并非全部:

  • 不可用任务 -- 您无法自定义这些任务的可见性。
  • 正在进行的车辆任务 - 您可以自定义这类任务。
  • 无效的车辆任务 - 您无法自定义这些任务的公开范围。

不可用任务

如果至少有一个不可用任务(例如, 例如司机正在路上休息或正在给车辆加油) 并不显示车辆。预计抵达时间 时间和预计任务完成时间仍然可用。

正在进行的车辆任务

通过 TaskTrackingInfo 对象提供了可在 API 属性中 货运跟踪库。默认情况下,当执行任务时, 且车辆距离任务不超过 5 次时。通过 在任务完成或取消时结束可见状态。这些字段如 如下:

  • 路线多段线
  • 预计到达时间
  • 预计任务完成时间
  • 到任务地点的剩余行驶距离
  • 剩余经停点数
  • 车辆位置

您可以通过设置 该 TaskTrackingViewConfig 在 Fleet Engine 中创建或更新任务时。这会创建 具体数据元素何时可用这一规则,这取决于 以下条件(以下称为“显示设置”选项):

  • 剩余经停点数
  • 预计到达时间前的时长
  • 剩余行驶距离
  • 始终显示
  • 一律不显示

请注意,每个数据元素只能与一个可见性选项相关联。 无法使用 OR 或 AND 条件来组合条件。

自定义示例如下所示。该自定义的规则如下:

  • 如果车辆在 3 个经停点范围内,则显示路线多段线。
  • 如果剩余行驶距离不足 5000 米,则显示预计到达时间。
  • 不再显示剩余经停点数。
  • 每个其他字段都将保留默认显示设置, 车辆在任务的 5 个经停点范围内。
"taskTrackingViewConfig": {
  "routePolylinePointsVisibility": {
    "remainingStopCountThreshold": 3
  },
  "estimatedArrivalTimeVisibility": {
    "remainingDrivingDistanceMetersThreshold": 5000
  },
  "remainingStopCountVisibility": {
    "never": true
  }
}

您还可以自定义项目的默认可见性配置,方法是 与支持团队联系

路线多段线和车辆位置可见性规则:

当路线多段线可见时,车辆位置也必须可见。 否则可通过多段线的末端指示车辆的位置。这样 表示路线多段线的可见性选项不能限制较少。

必须遵循这些规则,才能提供有效的路线多段线 / 车辆 位置信息显示设置组合:

  • 当路线多段线和车辆所在位置的可见性选项相同时 类型:

    • 如果显示选项为剩余经停点次数、预计到达时间前持续的时间,或 剩余行驶距离时,路线多段线所提供的值必须小于 大于或等于为该车辆的此可见性选项设置的值 位置。示例如下:
    "taskTrackingViewConfig": {
      "routePolylinePointsVisibility": {
        "remainingStopCountThreshold": 3
      },
      "vehicleLocationVisibility": {
        "remainingStopCountThreshold": 5
      },
    }
    
    • 如果路线多段线具有始终可见的可见性选项,则为:车辆位置 还必须提供始终可见的可见性选项。
    • 如果车辆所在位置的可见性选项一律不显示,则使用路线多段线 还必须提供一律不显示的可见性选项。
  • 当路线多段线和车辆位置具有不同的可见性选项时 车辆的位置信息,只有在同时同时显示位置信息时才会显示车辆位置信息 选项。

    示例如下:

    "taskTrackingViewConfig": {
      "routePolylinePointsVisibility": {
        "remainingStopCountThreshold": 3
      },
      "vehicleLocationVisibility": {
        "remainingDrivingDistanceMetersThreshold": 3000
      },
    }
    

    在此示例中,只有在剩余经停点时,车辆位置才会显示 计数至少为 3,剩余行驶距离至少为 3000 米。

开始使用 JavaScript 历程共享库

在使用 JavaScript 历程共享库之前,请确保您已经 熟悉 Fleet Engine 以及获取 API 密钥

如需跟踪送货情况,请先创建跟踪 ID 声明。

创建跟踪 ID 声明

如需使用送货地点提供商跟踪运单,请执行以下操作: 创建带有跟踪 ID 声明的 JSON 网络令牌 (JWT)。

要创建 JWT 载荷,请在“授权”部分添加额外的声明 包含键 trackingid。将其值设置为配送跟踪 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": {
     "trackingid": "tid_54321",
   }
}

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

您可以创建身份验证令牌提取程序,以检索创建的令牌 使用服务在你的服务器上存储相应的声明 为您的项目提供此证书请务必仅创建令牌 并且绝不会在任何客户端上共享您的证书。否则 就会危及系统的安全性。

抓取工具必须返回数据结构 两个字段,封装在一个 Promise 中:

  • 一个字符串 token
  • 数字 expiresInSeconds。令牌的到期时间是 提取。

JavaScript 物流跟踪库通过身份验证请求令牌 令牌提取器。

  • 它没有有效的令牌,例如尚未在 或者提取器未返回令牌时抛出该异常。
  • 之前提取的令牌已过期。
  • 之前提取的令牌将在过期后的 1 分钟内完成。

否则,库会使用之前发放的仍然有效的令牌,并 不会调用提取程序。

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

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_网址 取决于您的后端实现,以下是示例应用后端的网址:
    • 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 参数执行 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 和对令牌工厂的引用来对其进行实例化。

JavaScript

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

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

TypeScript

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

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

初始化地图视图

加载 JavaScript 历程共享库后,初始化 地图视图并将其添加到 HTML 页面中。您的网页应包含 用于存储地图视图的 &lt;div&gt; 元素。在以下示例中, &lt;div&gt; 元素名为 &lt;div&gt;

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

JavaScript

const mapView = new 
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'), 
  locationProviders: [locationProvider],
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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({
  document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
 // Any undefined styling options will use defaults.
});

// If you did not specify a tracking ID in the location
// provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.trackingId = 'your-tracking-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);

跟踪 ID

向位置信息提供程序提供的跟踪 ID 可能与多个 任务;例如,同一包裹的自提和配送任务,或者 多次失败的传送尝试。已选择一项任务显示在 货运跟踪地图。要显示的任务按如下方式确定:

  1. 如果只有一个待处理的自提任务,系统会显示该任务。生成了错误 。
  2. 如果只有一个待处理的传送任务,系统会显示该任务。错误为 如果存在多个待处理的提交任务,则会生成并提交任务。
  3. 如果有已关闭的配送任务:
    • 如果只有一个已关闭的配送任务,则会显示。
    • 如果有多项已关闭的配送任务,则用时间越近的那个 结果时间。
    • 如果有多项已关闭的交付任务,但都没有结果 都会生成错误。
  4. 如果有已关闭的自提任务:
    • 如果只有一个已关闭的自提任务,系统会显示该任务。
    • 如果有多项已关闭的自提任务,则用时间越近的那个 结果时间。
    • 如果有多项已关闭的自提任务,但都没有结果 都会生成错误。
  5. 否则,系统不会显示任何任务。

监听更改事件

您可以从任务跟踪信息中检索有关任务的元信息 对象使用位置信息提供程序。元信息包括预计到达时间、 剩余经停次数以及自提或送餐前的剩余距离。 对元信息的更改会触发 update 事件。以下示例 显示了如何监听这些更改事件。

JavaScript

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

TypeScript

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

处理错误

因请求送货信息而异步出现的错误 error 事件。以下示例展示了如何监听这些事件 以便处理错误

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

注意:请确保将库调用封装在 try...catch 块中 处理意料之外的错误。

停止跟踪

若要让营业地点提供商停止跟踪物流信息,请移除跟踪 ID 。

JavaScript

locationProvider.trackingId = '';

TypeScript

locationProvider.trackingId = '';

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

要自定义地图组件的外观和风格,请执行以下操作: 设置地图样式 使用云端工具或直接在代码中设置选项。

使用云端地图样式设置

云端地图样式设置 允许您为使用 Google 地图的任何应用创建和修改地图样式 而无需更改任何代码。 地图样式会以地图 ID 的形式保存到您的 Cloud 项目中。要将样式应用到 您的 JavaScript 货运跟踪地图,请指定 mapId JourneySharingMapView.mapId 字段无法更改 或者在实例化 JourneySharingMapView 之后添加。以下 示例展示了如何使用地图 ID 启用之前创建的地图样式。

JavaScript

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

TypeScript

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

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

自定义地图样式的另一种方法是 mapOptions 创建 JourneySharingMapView

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 货运跟踪库,您可以自定义商品外观和 给地图添加的标记为此,您可以指定标记 自定义设置,供货运跟踪库应用,然后再添加 每次标记更新时都会将标记添加到地图中。

最简单的自定义方法是指定 MarkerOptions 对象,该对象将应用于所有同类型标记。变更 对象中指定的所有标记。 覆盖所有默认选项。

更高级的选项是指定自定义函数。自定义 函数支持根据数据设置标记样式, 标记互动,例如点击处理。具体来说,装运 跟踪功能会将与 标记表示:车辆或目的地。这样一来,标记样式设置便可 根据标记元素本身的当前状态而调整;例如, 到达目的地的剩余计划内经停次数。您甚至可以加入 并根据来自 Fleet Engine 外部来源的数据调整标记样式, 这些信息。

发货跟踪库在 FleetEngineShipmentLocationProviderOptions

使用 MarkerOptions 更改标记的样式

以下示例展示了如何使用 一个 MarkerOptions 对象。遵循此模式可自定义任何图片的样式 标记。

JavaScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

deliveryVehicleMarkerCustomization = {
  cursor: 'grab'
};

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

以下示例展示了如何配置车辆标记的样式设置。关注 使用该模式,您可以使用任意标记来自定义 自定义参数。

JavaScript

deliveryVehicleMarkerCustomization =
  (params) => {
    var stopsLeft = params.taskTrackingInfo.remainingStopCount;
    params.marker.setLabel(`${stopsLeft}`);
  };

TypeScript

deliveryVehicleMarkerCustomization =
  (params: ShipmentMarkerCustomizationFunctionParams) => {
    const stopsLeft = params.taskTrackingInfo.remainingStopCount;
    params.marker.setLabel(`${stopsLeft}`);
  };

向标记添加点击处理

以下示例展示了如何向车辆标记添加点击处理。 遵照此格式向使用任意标记的任意标记添加点击处理 自定义参数。

JavaScript

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

TypeScript

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

使用自定义多段线

利用物流跟踪库,您还可以自定义 地图上显示该运单的配送路线。该库会创建一个 google.maps.Polyline 对象,为运单的有效或剩余的 path。 您可以指定多段线自定义项,以设置 Polyline 对象的样式。通过 库随后会在两种情况下应用这些自定义: 对象传递给地图,以及这些对象所用的数据发生更改的时间。

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

同样,您可以指定自定义函数。自定义函数 允许根据 Fleet Engine 发送的数据对对象进行单独的样式设置。 该函数可以根据该对象的当前状态更改每个对象的样式, 运单;例如,为 Polyline 对象着色更深;或者 使它变厚。你甚至可以加入 来自 Fleet Engine 以外的来源,并根据此设置 Polyline 对象的样式。 信息。

您可以使用 FleetEngineShipmentLocationProviderOptions。 您可以在车辆的 “旅程”-已经旅行过、正在旅行或尚未旅行过。通过 参数如下:

使用 PolylineOptions 更改 Polyline 对象的样式

以下示例展示了如何配置 Polyline 对象的样式 替换为 PolylineOptions。 遵循此模式可使用任意属性自定义任何 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.taskTrackingInfo.remainingDrivingDistanceMeters;
    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: ShipmentPolylineCustomizationFunctionParams) => {
    const distance = params.taskTrackingInfo.remainingDrivingDistanceMeters;
    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};

为车辆或位置标记显示 InfoWindow

您可以使用 InfoWindow 来显示关于车辆或位置标记的其他信息。

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

JavaScript

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

locationProvider.addListener('update', e => {
  const stopsCount =
      e.taskTrackingInfo.remainingStopCount;
  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.FleetEngineShipmentLocationProviderUpdateEvent) => {
  const stopsCount =
      e.taskTrackingInfo.remainingStopCount;
  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

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

locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
  const stopsCount =
      e.taskTrackingInfo.remainingStopCount;
  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 货运跟踪库来替换 包含标记或其他自定义项的现有地图 而不会丢失这些自定义设置

例如,假设您有一个包含标准 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.
  locationProvider = new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
    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.trackingId = TRACKING_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.
    -->
    <script defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
    </script>
  </body>
</html>

如果您跟踪的包裹是 指定 ID 位于乌鲁鲁附近,现在地图上就会呈现该 ID。