Suivre un véhicule

Cette section explique comment utiliser la bibliothèque de suivi de parc JavaScript pour suivre un véhicule lors de trajets à la demande ou de tâches planifiées.

Pour suivre un véhicule, procédez comme suit :

  1. Charger la bibliothèque et initialiser la vue de la carte
  2. Fournir la position du véhicule et la vue cartographique
  3. Écouter les événements et gérer les erreurs
  4. Arrêter le suivi

Charger la bibliothèque et initialiser la vue de la carte

Pour afficher les opérations de votre parc sur une carte de votre page Web, utilisez un script qui appelle une carte à l'aide de votre clé API. L'exemple suivant montre comment procéder à partir du code HTML :

  • URL source : appelle l'API Google Maps pour demander une carte à l'aide de votre clé API.

  • Paramètre callback : exécute la fonction initMap une fois que l'API renvoie l'appel.

  • Paramètre libraries : charge la bibliothèque de suivi de parc.

  • Attribut defer : permet au navigateur de continuer à afficher le reste de votre page pendant que l'API se charge.

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>
    

Fournir la position du véhicule et la vue Carte

Pour commencer à suivre un véhicule, vous devez instancier un fournisseur de localisation de véhicule et initialiser une vue de carte avec l'ID du véhicule, comme décrit dans les sections suivantes.

Instancier un fournisseur de localisation de véhicule

La bibliothèque JavaScript de suivi de flotte inclut un fournisseur de localisation pour l'API Fleet Engine. Utilisez votre ID de projet et une référence à votre récupérateur de jetons pour l'instancier, comme indiqué dans les exemples suivants.

Trajets à la demande

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // vehicleId to immediately start
          // tracking.
          vehicleId: 'your-vehicle-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // vehicleId to immediately start
          // tracking.
          vehicleId: 'your-vehicle-id',
});

Tâches planifiées

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // deliveryVehicleId to immediately start
          // tracking.
          deliveryVehicleId: 'your-delivery-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, you may specify
          // deliveryVehicleId to immediately start
          // tracking.
          deliveryVehicleId: 'your-delivery-id',
});

Initialiser la vue de la carte

Après avoir chargé la bibliothèque JavaScript Journey Sharing, initialisez la vue de carte et ajoutez-la à la page HTML. Votre page doit contenir un élément <div> qui contient la vue de la carte. L'élément <div> est nommé map_canvas dans les exemples suivants.

Trajets à la demande

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

Tâches planifiées

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

Écouter les événements et gérer les erreurs

Une fois que vous avez commencé à suivre un véhicule, vous souhaitez mettre à jour sa progression sur une carte et gérer les erreurs au fur et à mesure qu'il se déplace sur son itinéraire.

Écouter les événements de véhicule

Pour suivre la progression d'un véhicule pour les trajets à la demande ou les tâches planifiées, vous devez écouter les événements de modification.

Vous récupérez les métadonnées de l'objet vehicle ou deliveryVehicle à l'aide du fournisseur de localisation. Les méta-informations incluent l'heure d'arrivée prévue et la distance restante avant la prochaine prise en charge ou dépose du véhicule. Les modifications apportées aux méta-informations déclenchent un événement update dans le fournisseur de localisation.

L'exemple suivant montre comment écouter ces événements de modification.

Trajets à la demande

JavaScript

locationProvider.addListener('update', e => {
  // e.vehicle contains data that may be
  // useful to the rest of the UI.
  if (e.vehicle) {
    console.log(e.vehicle.vehicleState);
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineVehicleLocationProviderUpdateEvent) => {
  // e.vehicle contains data that may be
  // useful to the rest of the UI.
  if (e.vehicle) {
    console.log(e.vehicle.vehicleState);
  }
});

Tâches planifiées

JavaScript

locationProvider.addListener('update', e => {
  // e.deliveryVehicle contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicle) {
    console.log(e.deliveryVehicle.remainingDuration);
  }
});

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineDeliveryVehicleLocationProviderUpdateEvent) => {
  // e.deliveryVehicle contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicle) {
    console.log(e.deliveryVehicle.remainingDuration);
  }
});

Gérer les erreurs

Après avoir chargé la bibliothèque JavaScript Journey Sharing, initialisez la vue de carte et ajoutez-la à la page HTML. Votre page doit contenir un élément <div> qui contient la vue de la carte. L'élément <div> est nommé map_canvas dans les exemples suivants.

Trajets à la demande

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

Tâches planifiées

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

Arrêter le suivi d'un véhicule

Pour arrêter le suivi d'un véhicule, vous devez le supprimer du fournisseur de localisation et supprimer le fournisseur de localisation de la vue de carte, comme décrit dans les sections suivantes. Les exemples ci-dessous s'appliquent à l'implémentation des trajets à la demande et des tâches planifiées.

Supprimer un véhicule du fournisseur de localisation

Pour empêcher le fournisseur de localisation de suivre un véhicule, supprimez l'ID du véhicule de livraison du fournisseur de localisation.

Trajets à la demande

JavaScript

locationProvider.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

Tâches planifiées

JavaScript

locationProvider.deliveryVehicleId = '';

TypeScript

locationProvider.deliveryVehicleId = '';

Supprimer le fournisseur de localisation de la vue de carte

L'exemple suivant montre comment supprimer un fournisseur de localisation de la vue de carte.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Étape suivante