В этом разделе рассказывается, как использовать библиотеку отслеживания автопарка JavaScript, чтобы отслеживать транспортное средство для поездок по запросу или запланированных задач.
Чтобы отслеживать автомобиль, выполните следующие действия:
- Как загрузить библиотеку и инициализировать представление карты
- Как предоставить доступ к данным о местоположении автомобиля и карте
- Как отслеживать события и обрабатывать ошибки
- Как прекратить отслеживание
Загрузка библиотеки и инициализация карты
Чтобы отобразить операции автопарка на карте на веб-странице, используйте скрипт, который вызывает карту с помощью вашего ключа API. Ниже показано, как это сделать в HTML.
Источник URL. Вызывает Google Maps API, чтобы запросить карту с помощью вашего ключа API.
Параметр
callbackвыполняет функциюinitMapпосле того, как API возвращает вызов.Параметр
librariesзагружает библиотеку отслеживания автопарка.Атрибут
deferпозволяет браузеру продолжать отрисовку остальной части страницы во время загрузки API.<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
Показывать местоположение автомобиля и карту
Чтобы начать отслеживать автомобиль, создайте экземпляр поставщика местоположения автомобиля и инициализируйте представление карты с идентификатором автомобиля, как описано в следующих разделах.
Создание экземпляра поставщика данных о местоположении автомобиля
Библиотека отслеживания автопарка на JavaScript включает поставщика данных о местоположении для Fleet Engine API. Используйте идентификатор проекта и ссылку на средство получения токенов, чтобы создать экземпляр, как показано в примерах ниже.
Поездки по запросу
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
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'),
locationProviders: [locationProvider],
});
// 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 want.
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],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Запланированные задачи
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
});
// 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 want.
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],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Как отслеживать события и обрабатывать ошибки
После того как вы начали отслеживать транспортное средство, вам нужно обновлять его местоположение на карте и обрабатывать ошибки, возникающие во время поездки.
Как отслеживать события, связанные с транспортными средствами
Чтобы отслеживать прогресс транспортного средства для поездок по запросу или запланированных задач, вам нужно прослушивать события изменения.
Метаданные извлекаются из объекта vehicle или deliveryVehicle с помощью поставщика данных о местоположении. Метаданные включают расчетное время прибытия и оставшееся расстояние до следующей точки посадки или высадки. При изменении метаданных поставщик местоположения запускает событие 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('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 для передачи поездки инициализируйте режим карты и добавьте его на HTML-страницу. На странице должен быть элемент <div>, в котором будет размещено представление карты. В приведенных ниже примерах элемент <div> называется map_canvas.
Поездки по запросу
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
});
// 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 want.
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],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Запланированные задачи
JavaScript
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [locationProvider],
});
// 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 want.
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],
});
// 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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);
Как перестать отслеживать автомобиль
Чтобы прекратить отслеживание автомобиля, удалите его из поставщика данных о местоположении и удалите поставщика данных о местоположении из представления карты, как описано в следующих разделах. Приведенные здесь примеры относятся к реализации как поездок по запросу, так и запланированных задач.
Как удалить транспортное средство у поставщика данных о местоположении
Чтобы поставщик геолокационных данных перестал отслеживать автомобиль, удалите идентификатор транспортного средства из его системы.
Поездки по запросу
JavaScript
locationProvider.vehicleId = '';
TypeScript
locationProvider.vehicleId = '';
Запланированные задачи
JavaScript
locationProvider.deliveryVehicleId = '';
TypeScript
locationProvider.deliveryVehicleId = '';
Как удалить поставщика данных о местоположении из представления карты
В следующем примере показано, как удалить поставщика данных о местоположении из представления карты.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);