Questa sezione mostra come utilizzare la libreria di monitoraggio del parco risorse JavaScript per visualizzare un parco risorse. Queste procedure presuppongono che tu abbia configurato la libreria di monitoraggio del parco risorse e caricato una mappa. Per maggiori dettagli, consulta Configura la libreria di monitoraggio del parco risorse JavaScript.
Questo documento illustra le seguenti operazioni che puoi eseguire durante la visualizzazione di un parco risorse:
- Inizia a monitorare la flotta.
- Ascolta gli eventi e gestisci gli errori.
- Interrompi il monitoraggio.
- Monitora un singolo veicolo mentre visualizzi un parco risorse.
Inizia a monitorare la flotta
Per monitorare un parco risorse, devi creare un'istanza di un provider di località del parco risorse e impostare le limitazioni di località per l'area visibile della mappa, come descritto nelle sezioni seguenti.
Crea un'istanza di un provider di posizione del parco risorse
La libreria di monitoraggio del parco veicoli JavaScript include un provider di località che recupera più veicoli da Fleet Engine.
Per crearne 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 quali veicoli vengono 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 del veicolo. Utilizza
locationRestrictionper limitare l'area in cui visualizzare i veicoli sulla mappa. Il provider di posizione 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 provider di posizione.
Corse 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 più avanti nel codice, come
mostrato nell'esempio JavaScript riportato di seguito.
// 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 della località utilizzando l'area visibile della mappa
Puoi anche impostare i limiti di locationRestriction in modo che corrispondano all'area attualmente visibile nella visualizzazione mappa.
Corse 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 provider di località, inizializza la visualizzazione mappa nello stesso modo in cui segui un singolo veicolo.
Dopo aver caricato la libreria JavaScript di Journey Sharing, inizializza la visualizzazione mappa e aggiungila alla pagina HTML. La pagina deve contenere un elemento <div> che contiene la visualizzazione della mappa. L'elemento <div> è denominato map_canvas negli esempi seguenti.
Corse 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
Una volta iniziato a seguire il parco veicoli, devi ascoltare le modifiche degli eventi e gestire eventuali errori che si verificano, come descritto nelle sezioni seguenti.
Ascolta gli eventi di modifica
Puoi recuperare le meta-informazioni sulla flotta dall'oggetto Vehicle utilizzando il provider di geolocalizzazione. Le modifiche alle meta informazioni attivano un evento di aggiornamento. Le meta informazioni includono proprietà del veicolo come lo stato di navigazione, la distanza rimanente e gli attributi personalizzati.
Per maggiori dettagli, consulta:
- Riferimento per le opzioni dei veicoli per le corse on demand
- Riferimento alle opzioni del veicolo per le attività pianificate
I seguenti esempi mostrano come ascoltare questi eventi di modifica.
Corse 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.
Il seguente esempio mostra come ascoltare questi eventi per 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 del parco veicoli
Per interrompere il monitoraggio del parco risorse, imposta i limiti del provider di geolocalizzazione su null, quindi rimuovi il provider di geolocalizzazione dalla visualizzazione mappa come descritto nelle sezioni seguenti.
Imposta i limiti del provider di posizione su null
Per impedire al provider di localizzazione di monitorare la flotta, imposta i limiti del provider di localizzazione su null.
Corse on demand
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Attività pianificate
JavaScript
locationProvider.locationRestriction = null;
TypeScript
locationProvider.locationRestriction = null;
Rimuovi il fornitore di posizione dalla visualizzazione mappa
L'esempio seguente mostra come rimuovere un provider 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 provider di località della flotta di consegna e di un provider di località dei veicoli di consegna e aggiungili entrambi alla visualizzazione mappa. Una volta creata un'istanza, il provider di località della flotta di consegna inizia a mostrare i veicoli di consegna sulla mappa. I seguenti esempi mostrano come creare un'istanza di entrambi i provider di posizione:
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 degli indicatori per monitorare un veicolo per le consegne
Per consentire al provider di posizione del veicolo per le consegne di monitorare un veicolo per le consegne quando fai clic sul relativo indicatore della flotta, segui questi passaggi:
Personalizza un indicatore 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 indicatore 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 l'indicatore per evitare indicatori duplicati
Nascondi l'indicatore dal provider di località del veicolo di consegna per evitare il rendering di due indicatori 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);
}
};