当您跟踪行程时,您的消费者应用会向消费者显示相应车辆的位置。为此,应用需要开始跟踪行程、在行程期间更新旅程进度,并在行程完成时停止跟踪行程。
本文档介绍了此流程中的以下关键步骤:
- 设置地图
- 初始化地图并显示共享的旅程
- 更新并跟踪行程进度
- 停止关注行程
- 处理行程错误
设置地图
如需在 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 网页中。以下示例中也对这些步骤进行了编号:
为身份验证令牌工厂添加代码。
在
initMap()
函数中初始化位置信息提供程序。在
initMap()
函数中初始化地图视图。该视图包含地图。将自定义设置移到地图视图初始化的回调函数中。
将位置信息库添加到 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 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: '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);
更新并跟踪行程进度
应用应监听事件,并随着行程的进展更新行程进度。您可以使用位置信息提供程序从任务对象中检索有关行程的元信息。元信息包括上车或下车前的预计到达时间和剩余距离。元信息发生更改时,会触发更新事件。以下示例展示了如何监听这些更改事件。
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);
});