Questa sezione mostra come utilizzare la libreria di monitoraggio della flotta JavaScript per visualizzare una flotta. Queste procedure presuppongono che tu abbia configurato la libreria di monitoraggio della flotta e caricato una mappa. Per maggiori dettagli, vedi Configurare la libreria di monitoraggio della flotta JavaScript.
Questo documento illustra le seguenti operazioni che puoi eseguire quando visualizzi un parco risorse:
- Avvia il monitoraggio della flotta.
- Ascolta gli eventi e gestisci gli errori.
- Interrompi il monitoraggio.
- Monitora un singolo veicolo mentre visualizzi una flotta.
Avvia il monitoraggio della flotta
Per monitorare una flotta, devi creare un'istanza di un fornitore di località della flotta e impostare le limitazioni di località per la finestra della mappa come descritto nelle sezioni seguenti.
Crea un'istanza di un fornitore di località della flotta
La libreria di monitoraggio della flotta JavaScript include un fornitore di località che recupera più veicoli da Fleet Engine.
Per creare un'istanza, segui questi passaggi:
Utilizza l'ID progetto e un riferimento al recuperatore di token.
Utilizza una query di filtro dei veicoli La query di filtro dei veicoli controlla i veicoli visualizzati sulla mappa. Il filtro viene passato a Fleet Engine.
- Per i servizi on demand, utilizza
vehicleFiltere consultaListVehiclesRequest.filter - Per le attività pianificate, utilizza
deliveryVehicleFiltere consultaListDeliveryVehiclesRequest.filter
- Per i servizi on demand, utilizza
Imposta l'area di delimitazione per la visualizzazione dei veicoli. Utilizza
locationRestrictionper limitare l'area in cui visualizzare i veicoli sulla mappa. Il fornitore di località non è attivo finché non viene impostato. Puoi impostare i limiti di località nel costruttore o dopo il costruttore.Inizializza la visualizzazione mappa.
Gli esempi seguenti mostrano come creare un'istanza di un provider di località del parco risorse per scenari di attività on demand e pianificate. Questi esempi mostrano anche come utilizzare locationRestriction nel costruttore per attivare il fornitore di località.
Viaggi 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"',
});
Attività pianificate
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"',
});
Per impostare locationRestriction dopo il costruttore, aggiungi
locationProvider.locationRestriction in un secondo momento nel codice, come
mostrato nel seguente esempio 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,
};
Imposta la limitazione di località utilizzando la finestra della mappa
Puoi anche impostare i limiti di locationRestriction in modo che corrispondano all'area attualmente visibile nella visualizzazione mappa.
Viaggi 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;
}
});
Attività pianificate
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;
}
});
Inizializza la visualizzazione mappa
Dopo aver creato il fornitore di località, inizializza la visualizzazione mappa nello stesso modo in cui lo fai quando segui un singolo veicolo.
Dopo aver caricato la libreria JavaScript Journey Sharing, inizializza la visualizzazione mappa e aggiungila alla pagina HTML. La pagina deve contenere un <div> elemento che contiene la visualizzazione mappa. L'elemento <div> è denominato map_canvas negli esempi seguenti.=
Viaggi 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);
Attività pianificate
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);
Ascolta gli eventi e gestisci gli errori
Dopo aver iniziato a seguire il parco risorse, devi rimanere in ascolto delle modifiche degli eventi e gestire eventuali errori che si verificano come descritto nelle sezioni seguenti.
Ascolta gli eventi di modifica
Puoi recuperare i metadati della flotta dall'oggetto veicolo utilizzando il fornitore di località. Le modifiche ai metadati attivano un evento update. I metadati includono le proprietà del veicolo, come lo stato di navigazione, la distanza rimanente e gli attributi personalizzati.
Per maggiori dettagli, consulta quanto segue:
- Riferimento alle opzioni dei veicoli per i viaggi on demand
- Riferimento alle opzioni dei veicoli per le attività pianificate
Gli esempi seguenti mostrano come ascoltare questi eventi di modifica.
Viaggi 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);
}
}
});
Attività pianificate
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);
}
}
});
Ascolta gli errori
Devi anche ascoltare e gestire gli errori che si verificano durante il monitoraggio di un veicolo. Gli errori che si verificano in modo asincrono durante la richiesta di informazioni sul veicolo attivano eventi di errore.
L'esempio seguente mostra come ascoltare questi eventi in modo da poter gestire gli errori.
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);
});
Interrompi il monitoraggio della flotta
Per interrompere il monitoraggio della flotta, imposta i limiti del fornitore di località su null e poi rimuovi il fornitore di località dalla visualizzazione mappa come descritto nelle sezioni seguenti.
Imposta i limiti del fornitore di località su null
Per impedire al fornitore di località di monitorare la flotta, imposta i limiti del fornitore di località su null.
Viaggi on demand
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Attività pianificate
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Rimuovi il fornitore di località dalla visualizzazione mappa
L'esempio seguente mostra come rimuovere un fornitore di località dalla visualizzazione mappa.
JavaScript
mapView.removeLocationProvider(locationProvider);
TypeScript
mapView.removeLocationProvider(locationProvider);
Monitora un veicolo di consegna mentre visualizzi una flotta di consegna
Se utilizzi i servizi di mobilità per le attività pianificate, puoi visualizzare una flotta e mostrare il percorso e le attività imminenti per un veicolo di consegna specifico nella stessa visualizzazione mappa. Per farlo, crea un'istanza di un fornitore di località della flotta di consegna e di un fornitore di località del veicolo di consegna e aggiungili entrambi alla visualizzazione mappa. Una volta creata l'istanza, il fornitore di località della flotta di consegna inizia a mostrare i veicoli di consegna sulla mappa. Gli esempi seguenti mostrano come creare un'istanza di entrambi i fornitori di località:
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
});
Utilizza la personalizzazione dei marcatori per monitorare un veicolo di consegna
Per consentire al fornitore di località del veicolo di consegna di monitorare un veicolo di consegna quando fai clic sul relativo marcatore della flotta:
Personalizza un marcatore e aggiungi un'azione di clic.
Nascondi l'indicatore per evitare indicatori duplicati.
Gli esempi per questi passaggi sono riportati nelle sezioni seguenti.
Personalizza un marcatore e aggiungi un'azione di 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();
});
}
};
Nascondi il marcatore per evitare marcatori duplicati
Nascondi il marcatore dal fornitore di località del veicolo di consegna per evitare di eseguire il rendering di due marcatori per lo stesso veicolo:
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);
}
};