В этом разделе показано, как использовать библиотеку отслеживания автопарка JavaScript для отслеживания транспортного средства во время поездок по требованию или запланированных задач.
Чтобы отследить транспортное средство, выполните следующие действия:
- Загрузите библиотеку и инициализируйте вид карты
- Укажите местоположение транспортного средства и вид карты
- Прослушивание событий и обработка ошибок
- Остановить отслеживание
Загрузите библиотеку и инициализируйте вид карты
Чтобы отобразить операции вашего флота на карте на вашей веб-странице, используйте скрипт, который вызывает карту с помощью вашего ключа API. Следующий пример показывает, как это сделать из HTML:
Источник URL : вызывает API Карт Google для запроса карты с использованием вашего ключа 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 включает поставщик местоположения для API Fleet Engine. Используйте идентификатор вашего проекта и ссылку на ваш сборщик токенов, чтобы создать его экземпляр, как показано в следующих примерах.
Поездки по требованию
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineVehicleLocationProvider({
projectId,
authTokenFetcher,
// Optionally, you may specify
// vehicleId to immediately start
// tracking.
vehicleId: 'your-vehicle-id',
});
Машинопись
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',
});
Машинопись
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher,
// Optionally, you may specify
// deliveryVehicleId to immediately start
// tracking.
deliveryVehicleId: 'your-delivery-id',
});
Инициализировать вид карты
После загрузки библиотеки JavaScript Journey Sharing инициализируйте вид карты и добавьте его на страницу 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);
Машинопись
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);
Машинопись
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
с помощью поставщика местоположения. Метаданны включают ETA и оставшееся расстояние до следующего забора или высадки транспортного средства. Изменения метаданны вызывают событие обновления в поставщике местоположения.
В следующем примере показано, как прослушивать эти события изменения.
Поездки по требованию
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);
}
});
Машинопись
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);
}
});
Машинопись
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 Journey Sharing инициализируйте вид карты и добавьте его на страницу 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);
Машинопись
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);
Машинопись
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 = '';
Машинопись
locationProvider.vehicleId = '';
Запланированные задачи
JavaScript
locationProvider.deliveryVehicleId = '';
Машинопись
locationProvider.deliveryVehicleId = '';
Удалить поставщика местоположения из вида карты
В следующем примере показано, как удалить поставщика местоположения из представления карты.
JavaScript
mapView.removeLocationProvider(locationProvider);
Машинопись
mapView.removeLocationProvider(locationProvider);