Realizar el seguimiento de un vehículo

En esta sección, se muestra cómo usar la biblioteca de seguimiento de flota de JavaScript para realizar un seguimiento de un vehículo para viajes a pedido o tareas programadas.

Sigue estos pasos para realizar el seguimiento de un vehículo:

  1. Carga la biblioteca y, luego, inicializa la vista de mapa
  2. Proporciona la ubicación del vehículo y la vista de mapa
  3. Escucha eventos y soluciona errores
  4. Detener el seguimiento

Carga la biblioteca e inicializa la vista de mapa

Para mostrar las operaciones de tu flota en un mapa de tu página web, usa una secuencia de comandos que llama a un mapa mediante tu clave de API. En el siguiente ejemplo, se muestra cómo para hacerlo desde HTML:

  • URL source: Llama a la API de Google Maps para solicitar un mapa con tu clave de API.

  • Parámetro callback: Ejecuta la función initMap después de que la API muestra la llamada.

  • Parámetro libraries: Carga la biblioteca de seguimiento de flotas.

  • Atributo defer: Permite que el navegador continúe renderizando el resto de tu contenido. mientras se carga la API.

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

Proporciona la ubicación del vehículo y la vista de mapa

Para comenzar a rastrear un vehículo, ambos crean una instancia de un proveedor de ubicación de vehículos y, luego, inicializa una vista de mapa con el ID de vehículo, como se describe a continuación secciones.

Crea una instancia de proveedor de ubicación de vehículos

La biblioteca de seguimiento de flota de JavaScript incluye un proveedor de ubicación para la flota Engine. Usa el ID del proyecto y una referencia al recuperador de tokens para crear una instancia, como se muestra en los siguientes ejemplos.

Viajes on demand

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

Tareas programadas

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

Cómo inicializar la vista de mapa

Después de cargar la biblioteca de JavaScript Journey Share, inicializa la vista de mapa y agregarla a la página HTML. Tu página debe contener un elemento &lt;div&gt; que contiene la vista de mapa El elemento &lt;div&gt; se llama map_canvas en los siguientes ejemplos.

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

Tareas programadas

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

Detecta eventos y soluciona errores

Una vez que comienzas a hacer el seguimiento de un vehículo, quieres actualizar su progreso en un mapa y manejar errores a medida que el vehículo recorre su ruta.

Cómo detectar eventos de vehículos

Para realizar el seguimiento del progreso de un vehículo en los viajes a pedido o las tareas programadas, debes detectar eventos de cambio.

Puedes recuperar el meta del objeto vehicle o deliveryVehicle con el proveedor de ubicación. La metainformación incluye la hora de llegada estimada y la distancia restante. antes del próximo lugar de partida o destino del vehículo. Cambios en la metainformación activar un evento update en el proveedor de ubicación.

En el siguiente ejemplo, se muestra cómo escuchar estos eventos de cambio.

Viajes on demand

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

Tareas programadas

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

Cómo solucionar errores

Después de cargar la biblioteca de JavaScript Journey Share, inicializa la vista de mapa y agregarla a la página HTML. Tu página debe contener un elemento &lt;div&gt; que contiene la vista de mapa El elemento &lt;div&gt; se llama map_canvas en los siguientes ejemplos.

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

Tareas programadas

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

Cómo detener el seguimiento de un vehículo

Para dejar de rastrear un vehículo, debes quitarlo del proveedor de ubicación y eliminar el proveedor de ubicación de la vista de mapa, tal como se describe a continuación secciones. Estos ejemplos se aplican a viajes on demand y a tareas programadas para implementarlos.

Cómo quitar un vehículo del proveedor de ubicación

Para evitar que el proveedor de ubicación siga un vehículo, quita el el ID del vehículo de entrega del proveedor de ubicación.

Viajes on demand

JavaScript

locationProvider.vehicleId = '';

TypeScript

locationProvider.vehicleId = '';

Tareas programadas

JavaScript

locationProvider.deliveryVehicleId = '';

TypeScript

locationProvider.deliveryVehicleId = '';

Quitar el proveedor de ubicación de la vista de mapa

En el siguiente ejemplo, se muestra cómo quitar un proveedor de ubicación de la vista de mapa.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

¿Qué sigue?