Visualizza un parco risorse

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 il parco risorse libreria di monitoraggio e caricato una mappa. Per maggiori dettagli, vedi Imposta la libreria di monitoraggio del parco risorse JavaScript.

Questo documento illustra le seguenti azioni che puoi eseguire quando visualizzi un parco risorse:

  1. Inizia a monitorare il parco risorse.
  2. Ascoltare gli eventi e gestire gli errori.
  3. Interrompi il monitoraggio.
  4. Monitorare un singolo veicolo mentre consulti una flotta.

Inizia a monitorare il parco risorse

Per monitorare un parco risorse, devi creare un'istanza del fornitore di servizi di localizzazione e imposta limitazioni di località per l'area visibile della mappa come descritto di seguito sezioni.

Creare un'istanza per un fornitore di servizi di localizzazione del parco risorse

La libreria di monitoraggio del parco risorse JavaScript include un provider di posizione che recupera più veicoli da Fleet Engine.

Per creare un'istanza, segui questi passaggi:

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

  2. Utilizzare una query di filtro per veicoli La query di filtro per veicoli controlla quali veicoli che la mappa mostra. Il filtro viene passato a Fleet Engine.

  3. Imposta i limiti per il display del veicolo. Usa locationRestriction per Limita l'area in cui visualizzare i veicoli sulla mappa. Il luogo il provider non è attivo finché non viene impostato. Puoi impostare i limiti di località nel costruttore o dopo il costruttore.

  4. Inizializza la visualizzazione mappa.

I seguenti esempi mostrano come creare un'istanza di un provider di posizione del parco risorse per per gli scenari di attività on demand e di attività pianificate. Gli esempi mostrano anche come utilizzare locationRestriction nel costruttore per rendere il provider di località attivo.

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 più avanti nel codice come come mostrato nel seguente esempio di 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 di località usando l'area visibile della mappa

Puoi anche impostare locationRestriction limite in modo che corrisponda 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;
    }
  });

Inizializzare la visualizzazione mappa

Dopo aver creato il fornitore di località, inizializza la visualizzazione mappa nello stesso come fai quando segui un solo veicolo.

Dopo aver caricato la libreria di condivisione del percorso JavaScript, inizializzala la visualizzazione mappa e aggiungerla alla pagina HTML. La pagina deve contenere Un elemento <div> contenente la visualizzazione mappa. L'elemento <div> è denominato map_canvas nei seguenti esempi.=

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 ascoltare le modifiche agli eventi e gestire eventuali errori che si presentano come descritto nelle sezioni seguenti.

Ascolta gli eventi di modifica

Puoi recuperare le metadati sulla flotta dall'oggetto veicolo utilizzando il fornitore della posizione. Le modifiche alle metadati attivano un aggiornamento . Le meta informazioni includono proprietà del veicolo come la navigazione stato, distanza rimanente e attributi personalizzati.

Per maggiori dettagli, consulta quanto segue:

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

Monitora gli errori

Vuoi anche rimanere in ascolto e gestire gli errori che si verificano mentre segui veicolo. Errori che si verificano in modo asincrono dalla richiesta del veicolo informazioni attivano eventi di errore.

L'esempio seguente mostra come ascoltare questi eventi per consentirti di 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 risorse

Per interrompere il monitoraggio del parco risorse, imposta i limiti del provider di posizione su null, e poi rimuovi il fornitore di servizi dalla visualizzazione mappa come descritto le sezioni seguenti.

Imposta i limiti del provider di località su null

Imposta i limiti per impedire al fornitore di posizione di monitorare il parco risorse del provider 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;

Rimuovere il fornitore di posizione dalla visualizzazione mappa

L'esempio seguente mostra come rimuovere un fornitore di posizione dalla visualizzazione mappa.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Tracciare un veicolo per la consegna mentre visualizzi una flotta di consegna

Se utilizzi i servizi di mobilità per le attività pianificate, potete entrambi visualizzare un flotta e mostrare il percorso e le prossime attività per uno specifico veicolo per la consegna nella stessa vista mappa. Per farlo, crea un'istanza per una località del parco risorse un fornitore e un fornitore di servizi di localizzazione dei veicoli per la consegna e aggiungili entrambi alla mappa vista. Una volta creata un'istanza, il fornitore della posizione del parco di consegna inizia a mostrare veicoli per la consegna sulla mappa. I seguenti esempi mostrano come creare un'istanza entrambi i fornitori di sedi:

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

Utilizzo della personalizzazione degli indicatori per monitorare un veicolo per le consegne

Per consentire al fornitore della posizione del veicolo per la consegna di monitorare un veicolo per la consegna quando fai clic sull'indicatore del parco risorse, segui questi passaggi:

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

  2. Nascondi l'indicatore per evitare indicatori duplicati.

Ecco alcuni esempi di questi passaggi.

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 al fornitore della posizione del veicolo per la consegna per impedire il rendering 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);
    }
  };

Passaggi successivi