En esta sección, se muestra cómo usar la biblioteca de seguimiento de flota de JavaScript para ver una flota. En estos procedimientos, se supone que configuraste la biblioteca de seguimiento de flotas y cargaste un mapa. Para obtener más información, consulta Cómo configurar la biblioteca de seguimiento de flota de JavaScript.
En este documento, se analizan las siguientes acciones que puedes realizar cuando visualizas una flota:
- Comienza a hacer un seguimiento de la flota.
- Escucha eventos y controla errores.
- Detener el seguimiento
- Sigue un solo vehículo mientras ves una flota.
Comienza a hacer un seguimiento de la flota
Para hacer un seguimiento de una flota, debes crear una instancia de un proveedor de ubicación de flota y establecer restricciones de ubicación para el viewport del mapa, como se describe en las siguientes secciones.
Crea una instancia de un proveedor de ubicación de flota
La biblioteca de seguimiento de flota de JavaScript incluye un proveedor de ubicación que recupera varios vehículos de Fleet Engine.
Para crear una instancia, sigue estos pasos:
Usa el ID del proyecto y una referencia al recuperador de tokens.
Usa una consulta de filtro de vehículos: La consulta de filtro de vehículos controla qué vehículos se muestran en el mapa. El filtro se pasa a Fleet Engine.
- Para los servicios on demand, usa
vehicleFiltery revisaListVehiclesRequest.filter - Para las tareas programadas, usa
deliveryVehicleFiltery revisaListDeliveryVehiclesRequest.filter.
- Para los servicios on demand, usa
Establece el área de delimitación para la visualización del vehículo. Usa
locationRestrictionpara limitar el área en la que se mostrarán los vehículos en el mapa. El proveedor de ubicación no estará activo hasta que se establezca este valor. Puedes establecer límites de ubicación en el constructor o después de él.Inicializa la vista de mapa.
En los siguientes ejemplos, se muestra cómo crear una instancia de un proveedor de ubicación de flota para
situaciones de tareas programadas y on demand. En estos ejemplos, también se muestra cómo usar locationRestriction en el constructor para activar el proveedor de ubicación.
Viajes on demand
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which 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 vehicles are retrieved.
vehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
TypeScript
locationProvider =
new google.maps.journeySharing
.FleetEngineFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which 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 vehicles are retrieved.
vehicleFilter:
'attributes.foo = "bar" AND attributes.baz = "qux"',
});
Tareas programadas
JavaScript
locationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryFleetLocationProvider({
projectId,
authTokenFetcher,
// Optionally, specify location bounds to
// limit which delivery vehicles are
// retrieved and immediately make the location provider active.
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 make the location provider active.
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"',
});
Para establecer locationRestriction después del constructor, agrega locationProvider.locationRestriction más adelante en tu código, como se muestra en el siguiente ejemplo de JavaScript.
// You can choose to not set locationRestriction in the constructor.
// In this case, the location provider *DOES NOT START* after this line, because
// no locationRestriction is set.
locationProvider = new google.maps.journeySharing.DeliveryFleetLocationProvider({
... // not setting locationRestriction here
});
// You can then set the locationRestriction *after* the constructor.
// After this line, the location provider is active.
locationProvider.locationRestriction = {
north: 1,
east: 2,
south: 0,
west: 1,
};
Cómo configurar una restricción de ubicación con el viewport del mapa
También puedes establecer límites de locationRestriction para que coincidan con el área visible actualmente en la vista de mapa.
Viajes on demand
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;
}
});
Tareas programadas
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 provider 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 provider will start as soon as this is set.
locationProvider.locationRestriction = bounds;
}
});
Inicializa la vista de mapa
Una vez que construyas el proveedor de ubicación, inicializa la vista de mapa de la misma manera que lo haces cuando sigues un solo vehículo.
Después de cargar la biblioteca de JavaScript de uso compartido de viajes, 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 seguir la flota, debes escuchar los cambios de eventos y controlar los errores que surjan, como se describe en las siguientes secciones.
Cómo detectar eventos de cambio
Puedes recuperar metainformación sobre la flota desde el objeto de vehículo con el proveedor de ubicación. Los cambios en la metainformación activan un evento de actualización. La metainformación incluye propiedades del vehículo, como el estado de navegación, la distancia restante y los atributos personalizados.
Para obtener más detalles, consulta los siguientes recursos:
- Referencia de las opciones de vehículos para viajes on demand
- Referencia de las opciones de vehículos para tareas programadas
En los siguientes ejemplos, se muestra cómo escuchar estos eventos de cambio.
Viajes on demand
JavaScript
locationProvider.addListener('update', e => {
// e.vehicles contains data that may be
// useful to the rest of the UI.
for (vehicle of e.vehicles) {
console.log(vehicle.navigationStatus);
}
});
TypeScript
locationProvider.addListener('update',
(e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
// e.vehicles contains data that may be
// useful to the rest of the UI.
if (e.vehicles) {
for (vehicle of e.vehicles) {
console.log(vehicle.navigationStatus);
}
}
});
Tareas programadas
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);
}
}
});
Detecta errores
También debes detectar y controlar los errores que se producen mientras se sigue un vehículo. Los errores que surgen de forma asíncrona cuando se solicita información del vehículo activan eventos de error.
En el siguiente ejemplo, se muestra cómo escuchar estos eventos para que puedas controlar los errores.
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);
});
Detén el seguimiento de la flota
Para dejar de hacer un seguimiento de la flota, establece los límites del proveedor de ubicación en nulo y, luego, quita el proveedor de ubicación de la vista de mapa, como se describe en las siguientes secciones.
Establece los límites del proveedor de ubicación como nulos
Para que el proveedor de ubicación deje de hacer un seguimiento de la flota, establece los límites del proveedor de ubicación en nulo.
Viajes on demand
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Tareas programadas
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
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);
Sigue un vehículo de entrega mientras ves una flota de entrega
Si usas los servicios de movilidad para las tareas programadas, puedes ver una flota y mostrar la ruta y las próximas tareas de un vehículo de entrega específico en esa misma vista de mapa. Para ello, crea una instancia de un proveedor de ubicación de flota de entrega y un proveedor de ubicación de vehículo de entrega, y agrégalos a la vista de mapa. Una vez que se crea una instancia, el proveedor de ubicación de la flota de entrega comienza a mostrar los vehículos de entrega en el mapa. En los siguientes ejemplos, se muestra cómo crear una instancia de ambos proveedores de ubicación:
JavaScript
deliveryFleetLocationProvider =
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"',
});
deliveryVehicleLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher
});
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [
deliveryFleetLocationProvider,
deliveryVehicleLocationProvider,
],
// Any other options
});
TypeScript
deliveryFleetLocationProvider =
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"',
});
deliveryVehicleLocationProvider =
new google.maps.journeySharing
.FleetEngineDeliveryVehicleLocationProvider({
projectId,
authTokenFetcher
});
const mapView = new
google.maps.journeySharing.JourneySharingMapView({
element: document.getElementById('map_canvas'),
locationProviders: [
deliveryFleetLocationProvider,
deliveryVehicleLocationProvider,
],
// Any other options
});
Usa la personalización de marcadores para hacer un seguimiento de un vehículo de entrega
Para habilitar el proveedor de ubicación del vehículo de entrega para que haga un seguimiento de un vehículo de entrega cuando hagas clic en su marcador de flota, sigue estos pasos:
Personalizar un marcador y agregar una acción de clic
Oculta el marcador para evitar que se duplique.
En las siguientes secciones, se incluyen ejemplos de estos pasos.
Personaliza un marcador y agrega una acción de clic
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// params.vehicle.name follows the format
// "providers/{provider}/deliveryVehicles/{vehicleId}".
// Only the vehicleId portion is used for the delivery vehicle
// location provider.
deliveryVehicleLocationProvider.deliveryVehicleId =
params.vehicle.name.split('/').pop();
});
}
};
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
(params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.addListener('click', () => {
// params.vehicle.name follows the format
// "providers/{provider}/deliveryVehicles/{vehicleId}".
// Only the vehicleId portion is used for the delivery vehicle
// location provider.
deliveryVehicleLocationProvider.deliveryVehicleId =
params.vehicle.name.split('/').pop();
});
}
};
Oculta el marcador para evitar que se duplique
Oculta el marcador del proveedor de ubicación del vehículo de entrega para evitar que se rendericen dos marcadores para el mismo vehículo:
JavaScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
(params) => {
if (params.isNew) {
params.marker.setVisible(false);
}
};
TypeScript
// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
(params: deliveryVehicleMarkerCustomizationFunctionParams) => {
if (params.isNew) {
params.marker.setVisible(false);
}
};