En esta sección, se muestra cómo usar la biblioteca de seguimiento de flotas de JavaScript para hacer un seguimiento de un vehículo en viajes on demand o tareas programadas.
Para hacer un seguimiento de un vehículo, sigue estos pasos:
- Carga la biblioteca y, luego, inicializa la vista de mapa
- Proporciona la ubicación del vehículo y la vista de mapa
- Detecta eventos y controla errores
- Detener el seguimiento
Carga la biblioteca y, luego, inicializa la vista de mapa
Para mostrar las operaciones de tu flota en un mapa de tu página web, usa una secuencia de comandos que llame a un mapa con tu clave de API. En el siguiente ejemplo, se muestra cómo hacerlo desde HTML:
URL source: Llama a la API de Google Maps para solicitar un mapa con tu clave de API.
Parámetro
callback: Ejecuta la funcióninitMapdespués de que la API devuelve la llamada.Parámetro
libraries: Carga la biblioteca de seguimiento de flota.Atributo
defer: Permite que el navegador siga renderizando el resto de tu página mientras se carga la API.<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
Proporciona la ubicación del vehículo y la vista de mapa
Para comenzar a hacer un seguimiento de un vehículo, debes crear una instancia de un proveedor de ubicación de vehículos y, luego, inicializar una vista de mapa con el ID del vehículo, como se describe en las siguientes secciones.
Crea una instancia de un proveedor de ubicación de vehículos
La biblioteca de seguimiento de flota de JavaScript incluye un proveedor de ubicación para la API de Fleet Engine. Usa el ID del proyecto y una referencia al recuperador de tokens para crear una instancia, como se muestra en los siguientes ejemplos.
Viajes on demand
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',
});
Tareas programadas
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',
});
Inicializa la vista de mapa
Después de cargar la biblioteca de JavaScript de Recorridos compartidos, inicializa la vista de mapa y agrégala a la página HTML. Tu página debe contener un elemento <div> que contenga la vista de mapa. En los siguientes ejemplos, el elemento <div> se denomina map_canvas.=
Viajes on demand
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);
Tareas programadas
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);
Escucha eventos y controla errores
Una vez que hayas comenzado a hacer un seguimiento de un vehículo, querrás actualizar su progreso en un mapa y controlar los errores a medida que el vehículo se desplaza por su ruta.
Cómo detectar eventos de vehículos
Para hacer un seguimiento del progreso de un vehículo en viajes on demand o tareas programadas, debes escuchar los eventos de cambio.
Recuperas los metadatos del objeto vehicle o deliveryVehicle con el proveedor de ubicación. La metainformación incluye la hora estimada de llegada y la distancia restante antes de la próxima recogida o entrega del vehículo. Los cambios en la metainformación activan un evento de actualización en el proveedor de ubicación.
En el siguiente ejemplo, se muestra cómo escuchar estos eventos de cambio.
Viajes on demand
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);
}
});
Tareas programadas
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);
}
});
Soluciona errores
Después de cargar la biblioteca de JavaScript de Recorridos compartidos, inicializa la vista de mapa y agrégala a la página HTML. Tu página debe contener un elemento <div> que contenga la vista de mapa. En los siguientes ejemplos, el elemento <div> se denomina map_canvas.=
Viajes on demand
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);
Tareas programadas
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);
Cómo dejar de seguir un vehículo
Para dejar de hacer un seguimiento de un vehículo, debes quitarlo del proveedor de ubicación y quitar el proveedor de ubicación de la vista de mapa, como se describe en las siguientes secciones. Los ejemplos que se muestran aquí se aplican a la implementación de viajes on demand y tareas programadas.
Cómo quitar un vehículo del proveedor de ubicación
Para evitar que el proveedor de ubicación haga un seguimiento de un vehículo, quita el ID del vehículo de entrega del proveedor de ubicación.
Viajes on demand
JavaScript
locationProvider.vehicleId = '';
TypeScript
locationProvider.vehicleId = '';
Tareas programadas
JavaScript
locationProvider.deliveryVehicleId = '';
TypeScript
locationProvider.deliveryVehicleId = '';
Quita el proveedor de ubicación de la vista de mapa
En el siguiente ejemplo, se muestra cómo quitar un proveedor de ubicación de la vista de mapa.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);