使用 JavaScript 舰队跟踪库跟踪舰队

利用 JavaScript 舰队跟踪库,您可以直观呈现 在车队中实时监控车辆数量。该库使用 On Demand 乘车和送货 API 实现车辆和行程的可视化JavaScript 舰队 跟踪库包含一个普适性 JavaScript 地图组件 替代了标准 google.maps.Map 实体和数据组件 与 Fleet Engine 建立连接。

组件

JavaScript 舰队跟踪库提供了 车辆和行程航点,以及预计到达时间或剩余行程的原始数据 Feed 距离。

舰队跟踪地图视图

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

舰队跟踪地图视图
示例

位置信息提供程序

位置信息提供程序使用存储在 Fleet Engine 中的信息来发送位置信息 将跟踪对象的信息传输到旅程共享地图中。

车辆位置信息提供程序

车辆位置信息提供程序会显示单辆车的位置信息。 其中包含有关车辆位置和当前行程的信息,这些信息分配给了 。

舰队位置信息提供程序

车队位置信息提供程序会显示多辆车的位置信息。 您可以进行过滤以显示特定车辆及其位置,也可以 显示整个车队的车辆位置。

控制所跟踪位置的可见性

可见性规则决定跟踪的位置对象何时在地图上显示 Fleet Engine 位置信息提供程序。注意 - 使用自定义位置或派生位置 提供商可能会更改公开范围规则。

交通工具

在 Fleet Engine 中创建车辆后立即显示且可见 当 Vehicle_state 为 Online 时。这意味着即使 当尚未为车辆分配当前行程时。

航点位置标记

航点位置标记可指示车辆行程中的点 以最终目的地结束。航点位置 标记的定义如下:

  • Origin - 指示车辆行程的起始位置
  • 中级 - 表示车辆行程中途停留
  • 目的地 - 表示车辆行程的最终位置

计划的车辆航点在地图上显示为起点、中间点和 目的地标记。

JavaScript 舰队跟踪库使用入门

在使用 JavaScript 舰队跟踪库之前,请确保您熟悉 并获取 API 键。 然后创建行程 ID 和车辆 ID 申领。

创建行程 ID 和车辆 ID 申领

使用车辆位置信息跟踪车辆 provider,则创建一个包含行程的 JSON Web 令牌 (JWT) 身份证件和车辆 ID 申请。

要创建 JWT 载荷,请在“授权”部分添加额外的声明 使用 tripidvehicleid 键,并将每个键的 value 设置为 *。 应使用 Fleet Engine Service Super User Cloud 创建令牌 IAM 角色。请注意,这会授予创建、读取和修改舰队的广泛访问权限 引擎实体,只能与可信用户共享。

以下示例展示了如何创建用于按车辆进行跟踪的令牌, 任务:

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

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

JavaScript 舰队跟踪库使用身份验证请求令牌 令牌提取器。

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

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

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

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

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

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

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/driver/VEHICLE_ID
    • https://SERVER_URL/token/consumer/TRIP_ID
    • https://SERVER_URL/token/fleet_reader

从 HTML 加载地图

以下示例展示了如何加载 JavaScript 历程共享库 。callback 参数执行 initMap 函数 在 API 加载之后defer 属性可让浏览器继续呈现 加载网页的其余部分

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

跟随车辆

本部分介绍了如何使用 JavaScript 舰队跟踪库跟踪 。请务必通过 先添加脚本标记,然后再运行代码。

实例化车辆位置信息提供程序

JavaScript 舰队跟踪库为 Demand Rides and Deliveries API。使用您的项目 ID 和 进行实例化。

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

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

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

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

初始化地图视图

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

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 vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId
                        = 'your-vehicle-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('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

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

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId = 'your-vehicle-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('Times Square, New York, NY');
mapView.map.setZoom(14);

监听更改事件

您可以从 vehicle 对象中检索有关车辆的元信息 使用位置信息提供程序。元信息包括预计到达时间和其余时间 距离下一个上车点或下车点。对 Meta 的更改 信息会触发 update 事件。以下示例展示了如何监听 这些更改

JavaScript

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

TypeScript

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

监听错误

因请求车辆信息而异步出现的错误会触发 错误事件。以下示例展示了如何在以下位置监听这些事件: 以便处理错误。

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

停止跟踪

若要让位置信息提供程序停止跟踪车辆,请移除车辆 ID 。

JavaScript

locationProvider.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

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

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

查看车队

本部分介绍了如何使用 JavaScript 历程共享库查看 所有车辆。请务必通过回调函数加载库 在脚本标记中指定的,然后再运行代码。

实例化车队位置信息提供程序

JavaScript 舰队跟踪库预先定义了一个位置信息提供程序, 通过 On Demand Rides and Deliveries API 提取多辆车。使用您的 项目 ID 以及对令牌提取器的引用以对其进行实例化。

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

vehicleFilter 指定用于过滤地图上显示的车辆的查询。 此过滤器会直接传递给 Fleet Engine。请参阅 ListVehiclesRequest 了解支持的格式。

locationRestriction 用于限制在地图上显示车辆的区域。 它还用于控制是否启用位置跟踪功能。位置跟踪 在完成这一设置之前,不会启动。

构建好位置提供程序后,将地图初始化 视图

使用地图视口设置位置限制

您可以配置 locationRestriction 边界,以匹配以下位置的可见区域: 地图视图。

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

监听更改事件

您可以从 vehicles 对象中检索有关舰队的元信息 使用位置信息提供程序。元信息包括车辆属性 例如导航状态、到下一个航点的距离和自定义属性;请参阅 参考信息 文档 了解详情。对元信息的更改会触发更新事件。通过 以下示例展示了如何监听这些更改事件。

JavaScript

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

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
  // e.vehicles contains data that may be useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});

监听错误

因请求车队信息而异步出现的错误 触发错误事件。如需查看有关如何监听这些事件的示例,请参阅 监听错误

停止跟踪

要阻止位置信息提供程序跟踪车队,请设置 位置信息提供程序设为 null。

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

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

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

TypeScript

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

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

自定义地图样式的另一种方法是 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 跟踪功能会将与 标记表示:车辆、停车点或任务。这样一来,标记样式设置便可 根据标记元素本身的当前状态而调整;例如, 剩余停靠站数量或任务类型。您甚至可以将 Fleet Engine 以外的来源,并根据该信息设置标记的样式。

此外,您还可以使用自定义函数来过滤标记的可见性。 为此,请调用 setVisible(false) 标记上。

不过,出于性能方面的考虑, 位置提供程序中的过滤功能,例如 FleetEngineFleetLocationProvider.vehicleFilter。 也就是说,如果您需要额外的过滤功能 使用自定义功能进行过滤

舰队跟踪库提供了以下自定义参数:

使用 MarkerOptions 更改标记的样式

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

JavaScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

TypeScript

vehicleMarkerCustomization = {
  cursor: 'grab'
};

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

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

JavaScript

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

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.waypoints.length;
    params.marker.setLabel(`${remainingWaypoints}`);
  };

向标记添加点击处理

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

JavaScript

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

TypeScript

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

过滤可见标记

以下示例展示了如何过滤可见的车辆标记。 按照此格式过滤使用任何自定义标记设置的所有标记 参数。

JavaScript

vehicleMarkerCustomization =
  (params) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
      if (remainingWaypoints > 10) {
        params.marker.setVisible(false);
      }
  };

TypeScript

vehicleMarkerCustomization =
  (params: VehicleMarkerCustomizationFunctionParams) => {
    var remainingWaypoints = params.vehicle.remainingWaypoints.length;
    if (remainingWaypoints > 10) {
      params.marker.setVisible(false);
    }
  };

跟随车辆时使用自定义多段线

通过舰队跟踪库,您还可以自定义 地图上所跟踪车辆的路线。该库会创建一个 google.maps.Polyline 对象(针对车辆的有效或剩余位置中的每对坐标) path。 您可以指定多段线自定义项,以设置 Polyline 对象的样式。通过 库随后会在两种情况下应用这些自定义: 对象传递给地图,以及这些对象所用的数据发生更改的时间。

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

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

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

使用 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.vehicle.waypoints[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: VehiclePolylineCustomizationFunctionParams) => {
    const distance = params.vehicle.waypoints[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 =
  FleetEngineVehicleLocationProvider.
      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) => {
    FleetEngineVehicleLocationProvider.
        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 =
  FleetEngineVehicleLocationProvider.
      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: VehiclePolylineCustomizationFunctionParams) => {
    FleetEngineVehicleLocationProvider.
        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});

// (Assumes a vehicle location provider.)
locationProvider.addListener('update', e => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off point.`);

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

// (Assumes a vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  if (e.vehicle) {
    const distance =
          e.vehicle.remainingDistanceMeters;
    infoWindow.setContent(
        `Your vehicle is ${distance}m away from the next drop-off.`);
    // 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,
  ...
});

替换现有地图

您可以替换包含标记或其他自定义设置的现有地图 而不会丢失这些自定义设置

例如,假设您有一个包含标准 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 Oracle Park Stadium
        var oraclePark = { lat: 37.780087547237365, lng: -122.38948437884427 };,
        // 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 Oracle Park
        var marker = new google.maps.Marker({ position: oraclePark, 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. Use FleetEngineVehicleLocationProvider
        // as appropriate.
        locationProvider = new google.maps.journeySharing.FleetEngineVehicleLocationProvider({
          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
        });

      mapView.addListener('ready', () => {
        locationProvider.vehicleId = VEHICLE_ID;

          // (4) Add customizations like before.

          // The location of Oracle Park
          var oraclePark = {lat: 37.77995187146094, lng: -122.38957020952795};
          // 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 Oracle Park
          var marker = new google.maps.Marker({position: oraclePark, 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, which includes Fleet Tracking functionality.
    -->
    <script
      defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing&v=beta"
    ></script>
  </body>
</html>

如果您在 Oracle 公园附近使用指定 ID 驾驶车辆,该车辆将在 地图。