Visualizza un parco risorse

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 descrive le seguenti operazioni che puoi eseguire quando visualizzi una flotta:

  1. Inizia a monitorare la flotta.
  2. Ascolta gli eventi e gestisci gli errori.
  3. Interrompi il monitoraggio.
  4. Monitora un singolo veicolo mentre visualizzi una flotta.

Inizia a monitorare la flotta

Per monitorare una flotta, devi creare un'istanza di un fornitore di località della flotta e impostare le limitazioni della posizione per l'area visibile della mappa come descritto nelle sezioni seguenti.

Crea un'istanza di un fornitore di localizzazione della flotta

La libreria di monitoraggio della flotta JavaScript include un fornitore di servizi di localizzazione che recupera più veicoli da Fleet Engine.

Per istanziarlo, segui questi passaggi:

  1. Utilizza l'ID progetto e un riferimento al tuo recuperatore di token.

  2. Utilizza una query di filtro per i veicoli. La query di filtro per i veicoli controlla quali veicoli vengono visualizzati sulla mappa. Il filtro viene passato a Fleet Engine.

  3. Imposta l'area di delimitazione per la visualizzazione del veicolo. Utilizza locationRestriction per limitare l'area in cui visualizzare i veicoli sulla mappa. Il fornitore di servizi di localizzazione non è attivo finché non viene impostato. Puoi impostare i limiti di posizione nel costruttore o dopo il costruttore.

  4. Inizializza la visualizzazione mappa.

Gli esempi riportati di seguito mostrano come creare un'istanza di un fornitore di servizi di localizzazione della flotta per scenari di attività on demand e pianificate. Questi esempi mostrano anche come utilizzare locationRestriction nel costruttore per attivare il fornitore di servizi di localizzazione.

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,
   };

Impostare 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 della 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

Una volta creato il fornitore di servizi di localizzazione, inizializza la visualizzazione della mappa nello stesso modo in cui lo fai quando segui un singolo veicolo.

Dopo aver caricato la libreria JavaScript Journey Sharing, inizializza la visualizzazione della 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.=

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

Una volta iniziato a seguire la flotta, devi rilevare le modifiche agli eventi e gestire gli errori che si verificano come descritto nelle sezioni seguenti.

Ascolta gli eventi di modifica

Puoi recuperare i metadati del parco risorse dall'oggetto veicolo utilizzando il fornitore di servizi di localizzazione. Le modifiche alle meta informazioni attivano un evento di aggiornamento. I metadati includono le proprietà del veicolo, come lo stato di navigazione, la distanza rimanente e gli attributi personalizzati.

Per maggiori dettagli, consulta le seguenti risorse:

I seguenti esempi 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);
    }
  }
});

Ascolto di errori

Inoltre, devi ascoltare e gestire gli errori che si verificano mentre segui 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 rilevare questi eventi per 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 servizi di localizzazione su null e poi rimuovi il fornitore di servizi di localizzazione dalla visualizzazione della mappa come descritto nelle sezioni seguenti.

Imposta i limiti del fornitore di servizi di localizzazione su null

Per impedire al fornitore di servizi di localizzazione di monitorare la flotta, imposta i limiti del fornitore di servizi di localizzazione su null.

Viaggi on demand

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Attività pianificate

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Rimuovere il fornitore di servizi di localizzazione dalla visualizzazione della mappa

L'esempio seguente mostra come rimuovere un fornitore di servizi di localizzazione dalla visualizzazione della mappa.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Monitorare un veicolo di consegna durante la visualizzazione di una flotta di consegna

Se utilizzi i servizi di mobilità per le attività pianificate, puoi visualizzare sia una flotta sia il percorso e le attività imminenti per un veicolo di consegna specifico nella stessa visualizzazione della mappa. Per farlo, crea un'istanza di un fornitore di posizione della flotta di consegna e di un fornitore di posizione del veicolo di consegna e aggiungili entrambi alla visualizzazione della mappa. Una volta creata un'istanza, il fornitore di posizioni della flotta di consegna inizia a mostrare i veicoli di consegna sulla mappa. Gli esempi riportati di seguito mostrano come creare un'istanza di entrambi i fornitori di geolocalizzazione:

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
});

Utilizzare la personalizzazione dei segnaposto per monitorare un veicolo di consegna

Per consentire al fornitore di servizi di localizzazione del veicolo di consegna di monitorare un veicolo di consegna quando fai clic sul relativo indicatore della flotta, segui questi passaggi:

  1. Personalizza un indicatore e aggiungi un'azione di clic.

  2. Nascondi il marcatore per evitare duplicati.

Alcuni esempi per questi passaggi sono riportati nelle sezioni seguenti.

Personalizzare un indicatore e aggiungere 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();
      });
    }
  };

Nascondere il marcatore per evitare duplicati

Nascondi il marcatore del fornitore della posizione del veicolo di consegna per evitare 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);
    }
  };

Passaggi successivi