借助 JavaScript 舰队跟踪库,您可以近乎实时地查看车辆在车队中的位置。该库使用 Delivery Delivery API 来直观呈现送货车辆和任务。与 JavaScript 装运跟踪库一样,它包含一个 JavaScript 地图组件,该组件可直接取代标准 google.maps.Map
实体和数据组件,以便与 Fleet Engine 连接。
组件
JavaScript 舰队跟踪库提供了一些组件,可用于直观呈现送货车辆和停靠站,以及原始数据 Feed 的预计到达时间 (ETA) 或与目的地的距离。
舰队跟踪地图视图
舰队跟踪地图视图组件可直观呈现车辆和任务的位置。如果已知车辆的路线,则地图视图组件会为该车辆沿其预测路径移动添加动画。
位置信息提供程序
位置信息提供程序会使用存储在 Fleet Engine 中的信息将所跟踪对象的位置信息发送到历程共享地图。
车辆运输地点提供商
送货车辆位置信息提供程序会显示单个送货车辆的位置信息。其中包含有关车辆位置以及投递车辆已完成的任务的信息。
配送车队地点提供商
配送车队位置信息提供程序会显示多辆车的位置信息。您可以过滤出特定车辆或位置,也可以显示整个车队。
控制所跟踪地点的公开范围
本部分介绍 Fleet Engine 预定义的位置信息提供程序在地图上所跟踪的位置对象的可见性规则。自定义或派生位置信息提供程序可能会更改可见性规则。
交车
送货车辆在 Fleet Engine 中创建后立即显示,无论其任务执行情况如何,都能在路线中查看。
任务位置标记
计划的车辆停靠点在地图上显示为车辆停靠标记。已完成任务的标记会以不同于车辆计划停止的样式显示。
任务结果的位置会与任务结果标记一起显示。 结果为 SUCCEEDED 的任务会显示成功的任务标记,而所有其他任务都会显示失败的任务标记。
JavaScript 舰队跟踪库使用入门
在使用 JavaScript 舰队跟踪库之前,请确保您已熟悉 Fleet Engine 以及获取 API 密钥。然后,创建任务 ID 和送货车辆 ID 声明。
创建任务 ID 和提交车辆 ID 声明
如需使用车辆运输位置信息提供程序跟踪送货车辆,请创建一个包含任务 ID 和送货车辆 ID 声明的 JSON 网络令牌 (JWT)。
如需创建 JWT 载荷,请在授权部分中添加具有键 taskid 和 deliveryvehicleid 的附加声明,并将每个密钥的值设置为 *。令牌应使用 Fleet Engine Service Super User Cloud IAM 角色来创建。请注意,这会授予创建、读取和修改 Fleet Engine 实体广泛的访问权限,并且只应与可信用户共享。
以下示例展示了如何创建按车辆和任务进行跟踪的令牌:
{
"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": {
"taskid": "*",
"deliveryvehicleid": "*",
}
}
创建身份验证令牌提取器
您可以创建身份验证令牌提取器,以使用您项目的服务帐号证书检索服务器上使用相应声明创建的令牌。务必只在服务器上创建令牌并且绝不在任何客户端上共享证书。否则,系统会破坏系统的安全性。
以下示例展示了如何创建身份验证令牌提取器:
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.ExpiresInSeconds
};
}
在实现用于创建令牌的服务器端端点时,请注意以下几点:
- 端点必须返回令牌的到期时间;在上面的示例中,它被指定为
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
- https://
从 HTML 加载地图
以下示例展示了如何从指定网址加载 JavaScript 历程共享库。callback 参数会在 API 加载后执行 initMap
函数。defer 属性可让浏览器在 API 加载期间继续呈现网页的其余部分。请注意,必须指定 v=beta 参数。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&v=beta&callback=initMap&libraries=journeySharing" defer></script>
跟随送货车辆
本部分介绍如何使用 JavaScript 舰队跟踪库跟踪送货车辆。在运行代码之前,请务必从脚本代码中指定的回调函数加载库。
实例化送货车辆位置信息提供程序
JavaScript 舰队跟踪库会为 Fleet Engine Deliveryies API 预定义位置信息提供程序。使用您的项目 ID 和对令牌工厂的引用对其进行实例化。
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher,
// Optionally, you may specify
// deliveryVehicleId to immediately start
// tracking.
deliveryVehicleId: 'your-delivery-id',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher,
// Optionally, you may specify
// deliveryVehicleId to immediately start
// tracking.
deliveryVehicleId: 'your-delivery-id',
});
初始化地图视图
加载 JavaScript 旅程分享库后,初始化地图视图并将其添加到 HTML 页面。您的网页应包含存放地图视图的 <div> 元素。在以下示例中,<div> 元素被命名为 map_Canvas。
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
= 'your-delivery-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'),
locationProvider: locationProvider,
// Styling customizations; see below.
vehicleMarkerSetup: vehicleMarkerSetup,
anticipatedRoutePolylineSetup:
anticipatedRoutePolylineSetup,
// Any undefined styling options will use defaults.
});
// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
= 'your-delivery-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);
监听更改事件
您可以使用位置信息提供程序从 deliveryVehicle
对象中检索与任务相关的元信息。元信息包括预计到达时间以及车辆下次自提或下车前的剩余距离。对元信息所做的更改会触发 update 事件。以下示例展示了如何监听这些更改事件。
JavaScript
locationProvider.addListener('update', e => {
// e.deliveryVehicle contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicle) {
console.log(e.deliveryVehicle.remainingDuration);
}
});
TypeScript
locationProvider.addListener('update',
(e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
// e.deliveryVehicle contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicle) {
console.log(e.deliveryVehicle.remainingDuration);
}
});
监听错误
由于请求送货车辆信息而异步产生的错误会触发错误事件。以下示例展示了如何监听这些事件以处理错误。
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);
});
查看交付舰队
本部分介绍如何使用 JavaScript 历程共享库查看交付舰队。在运行代码之前,请务必从脚本代码中指定的回调函数加载库。
实例化交付舰队位置提供程序
JavaScript 舰队跟踪库预定义了一个位置提供程序,用于从 FleetEngine Deliveryies API 提取多辆车。使用您的项目 ID 以及对令牌提取器的引用来将其实例化。
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery 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 delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery 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 delivery vehicles are retrieved.
deliveryVehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
deliveryVehicleFilter
,用于指定用于过滤地图上显示的车辆的查询。此过滤器直接传递给 Fleet Engine。如需了解支持的格式,请参阅 ListDeliveryVehiclesRequest.filter
。
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;
}
});
监听更改事件
您可以使用位置信息提供程序从 deliveryVehicles
对象中检索有关舰队的元信息。元信息包括导航状态、剩余距离和自定义属性等车辆属性;如需了解详情,请参阅参考文档。更改元信息会触发 update 事件。以下示例展示了如何监听这些更改事件。
JavaScript
locationProvider.addListener('update', e => {
// e.deliveryVehicles contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicles) {
for (vehicle of e.deliveryVehicles) {
console.log(vehicle.remainingDistanceMeters);
}
}
});
TypeScript
locationProvider.addListener('update',
(e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
// e.deliveryVehicles contains data that may be
// useful to the rest of the UI.
if (e.deliveryVehicles) {
for (vehicle of e.deliveryVehicles) {
console.log(vehicle.remainingDistanceMeters);
}
}
});
监听错误
由于请求传送队列信息而异步发生的错误会触发错误事件。如需查看有关如何监听这些事件的示例,请参阅监听错误。
自定义基本地图的外观和风格
如需自定义地图组件的外观和风格,您可以使用云端工具或直接在代码中设置选项来设置地图样式。
使用云端地图样式设置
借助云端地图样式设置,您可以为任何通过 Google Cloud 控制台使用 Google 地图的应用创建和修改地图样式,而无需对代码进行任何更改。地图样式会以地图 ID 的形式保存在 Cloud 项目中。如需将样式应用于 JavaScript 舰队跟踪地图,请在创建 JourneySharingMapView
时指定 mapId
。在 JourneySharingMapView
实例化之后,无法更改或添加 mapId
字段。以下示例展示了如何使用地图 ID 启用之前创建的地图样式。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
mapId: 'YOUR_MAP_ID'
}
});
使用基于代码的地图样式
自定义地图样式的另一种方法是在创建 JourneySharingMapView
时设置 mapOptions
。
JavaScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
TypeScript
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: locationProvider,
mapOptions: {
styles: [
{
"featureType": "road.arterial",
"elementType": "geometry",
"stylers": [
{ "color": "#CCFFFF" }
]
}
]
}
});
更改路线的样式和可见性
如需配置已提取和预期路线的样式和可见性,请使用自定义样式选项。如需了解详情,请参阅 polylineOptions 接口。
以下示例展示了如何配置预期路线的样式和可见性。如需配置所提取路线的样式和可见性,请使用 takenRoutePolylineSetup
,而非 anticipatedRoutePolylineSetup
。
JavaScript
// This function is specified in the
// JourneySharingMapView constructor's options
// parameter.
function anticipatedRoutePolylineSetup({
defaultPolylineOptions, defaultVisible}) {
// If this function is not specified, the
// PolylineOptions object contained in
// defaultPolylineOptions is used to render the
// anticipated route polyline. visible property sets the
// polyline's visibility. Modify this object and
// pass it back to customize the style of the map.
defaultPolylineOptions.strokeOpacity = 0.5;
defaultPolylineOptions.strokeColor = 'red';
return {
polylineOptions: defaultPolylineOptions,
visible: true
};
}
// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineOptionsSetup = {
polylineOptions: {
strokeOpacity: 0.5,
strokeColor: 'red',
…
},
visible: true,
};
TypeScript
// This function is specified in the
// JourneySharingMapView constructor's options
// parameter.
function anticipatedRoutePolylineSetup(options: {
defaultPolylineOptions: google.maps.PolylineOptions,
visible: boolean,
}): {
polylineOptions: google.maps.PolylineOptions,
visible: boolean,
} {
// If this function is not specified, the
// PolylineOptions object contained in
// defaultPolylineOptions is used to render the
// anticipated route polyline. visible property sets the
// polyline's visibility. Modify this object and
// pass it back to customize the style of the map.
options.defaultPolylineOptions.strokeOpacity = 0.5;
options.defaultPolylineOptions.strokeColor = 'red';
return {
polylineOptions: options.defaultPolylineOptions,
visible: true
};
}
// As an alternative, set static PolylineOptions to
// use for the anticipated route.
const anticipatedRoutePolylineSetup = {
polylineOptions: {
strokeOpacity: 0.5,
strokeColor: 'red',
…
},
visible: true,
};
使用标记自定义
使用 JavaScript 舰队跟踪库,您可以自定义添加到地图的标记的外观和风格。为此,您可以指定标记自定义,随后在向地图添加标记以及每次更新标记之前,系统会应用舰队跟踪库。
最简单的自定义是指定一个将应用于相同类型所有标记的 MarkerOptions
对象。对象创建后,系统会在该对象中指定的更改覆盖所有默认选项。
更高级的选项是指定自定义函数。自定义函数允许根据数据为标记设置样式,以及为标记添加互动功能,例如点击处理。具体而言,舰队跟踪会将有关标记所表示的对象类型(车辆、停止或任务)的数据传递给自定义函数。然后,可以根据标记元素本身的状态更改标记样式;例如,剩余站点数或任务类型。您甚至可以合并来自 Fleet Engine 外部的数据的数据,并根据该信息设置标记的样式。
此外,您还可以使用自定义函数来过滤标记可见性。
为此,请对标记调用 setVisible(false)
。
但是,出于性能方面的原因,我们建议您使用位置提供程序中的原生过滤功能(例如 FleetEngineDeliveryFleetLocationProvider.deliveryVehicleFilter
)进行过滤。也就是说,如果您需要使用其他过滤功能,则可以使用自定义函数来应用过滤。
舰队跟踪库提供以下自定义参数:
使用 MarkerOptions
更改标记的样式
以下示例展示了如何使用 MarkerOptions
对象配置车辆标记的样式。您可以按照此模式使用上面列出的任何标记自定义参数来自定义任意标记的样式。
JavaScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
TypeScript
deliveryVehicleMarkerCustomization = {
cursor: 'grab'
};
使用自定义函数更改标记的样式
以下示例展示了如何配置车辆标记的样式。您可以按照此模式使用上面列出的任何标记自定义参数来自定义任何标记的样式。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
params.marker.setLabel(`${stopsLeft}`);
};
向标记添加点击处理
以下示例展示了如何向车辆标记添加点击处理。 遵循以下模式,使用上文列出的任何标记自定义参数向任何标记添加点击处理。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// Perform desired action.
});
}
};
过滤可见标记
以下示例展示了如何过滤可见的车辆标记。 遵循以下模式,使用上面列出的任何标记自定义参数过滤任何标记。
JavaScript
deliveryVehicleMarkerCustomization =
(params: DeliveryVehicleMarkerCustomizationFunctionParams) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(false);
}
};
TypeScript
deliveryVehicleMarkerCustomization =
(params) => {
var stopsLeft = params.vehicle.remainingVehicleJourneySegments.length;
if (stopsLeft > 10) {
params.marker.setVisible(false);
}
为车辆或位置标记显示 InfoWindow
您可以使用 InfoWindow
显示有关车辆或位置标记的更多信息。
以下示例展示了如何创建 InfoWindow
并将其附加到车辆标记。
JavaScript
// 1. Create an info window.
const infoWindow = new google.maps.InfoWindow(
{disableAutoPan: true});
// (Assumes a delivery vehicle location provider.)
locationProvider.addListener('update', e => {
if (e.deliveryVehicle) {
const distance =
e.deliveryVehicle.remainingDistanceMeters;
infoWindow.setContent(
`Your vehicle is ${distance}m away from the next task.`);
// 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 delivery vehicle location provider.)
locationProvider.addListener('update', (e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
if (e.deliveryVehicle) {
const distance =
e.deliveryVehicle.remainingDistanceMeters;
infoWindow.setContent(
`Your vehicle is ${distance}m away from the next task.`);
// 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'),
locationProvider: locationProvider,
automaticViewportMode:
google.maps.journeySharing
.AutomaticViewportMode.NONE,
...
});
TypeScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProvider: 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 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 历程共享库(包括舰队跟踪),请执行以下操作:
- 为身份验证令牌工厂添加代码。
- 在
initMap()
函数中初始化位置信息提供程序。 - 在
initMap()
函数中初始化地图视图。视图包含地图。 - 将您的自定义设置移至地图视图初始化的回调函数中。
- 向 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 FleetEngineDeliveryVehicleLocationProvider
// as appropriate.
locationProvider = new google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProvider({
YOUR_PROVIDER_ID,
authTokenFetcher,
});
// (3) Initialize map view (which contains the map).
const mapView = new google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map'),
locationProvider: locationProvider,
// any styling options
});
mapView.addListener('ready', () => {
locationProvider.deliveryVehicleId = DELIVERY_VEHICLE_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, which includes Fleet Tracking functionality.
-->
<script defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
</script>
</body>
</html>
现在,如果您使用 Uluru 附近的指定 ID 运送车辆,该车辆将在地图上呈现。