Ver una flota

En esta sección, se muestra cómo usar la biblioteca de JavaScript para el seguimiento de flotas y ver una flota. En estos procedimientos, se supone que configuraste la biblioteca de seguimiento de flota y cargaste un mapa. Para obtener más información, consulta Cómo configurar la biblioteca de seguimiento de flotas de JavaScript.

En este documento, se analizan las siguientes acciones que puedes realizar cuando visualizas una flota:

  1. Comienza a hacer el seguimiento de la flota.
  2. Detecta eventos y controla errores.
  3. Detener el seguimiento
  4. Hacer el seguimiento de un solo vehículo mientras se visualiza una flota

Comienza a hacer el seguimiento de la flota

Para hacer un seguimiento de una flota, debes crear una instancia de un proveedor de ubicación de flota y establecer restricciones de ubicación para la ventana gráfica del mapa, como se describe en las siguientes secciones.

Crea una instancia de un proveedor de ubicación de flota

La biblioteca de seguimiento de flota de JavaScript incluye un proveedor de ubicación que recupera varios vehículos de Fleet Engine.

Para crear una instancia, sigue estos pasos:

  1. Usa el ID de tu proyecto y una referencia a tu buscador de tokens.

  2. Usa una búsqueda de filtro de vehículos: La búsqueda de filtro de vehículos controla qué vehículos muestra el mapa. El filtro se pasa a Fleet Engine.

  3. Establece el área de límite para la visualización del vehículo. Usa locationRestriction para limitar el área en la que se muestran los vehículos en el mapa. El proveedor de ubicación no está activo hasta que se establece este parámetro. Puedes establecer los límites de ubicación en el constructor o después de este.

  4. Inicializa la vista de mapa.

En los siguientes ejemplos, se muestra cómo crear una instancia de un proveedor de ubicación de la flota para situaciones de tareas programadas y a pedido. En estos ejemplos, también se muestra cómo usar locationRestriction en el constructor para activar el proveedor de ubicación.

Viajes a pedido

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

Tareas programadas

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

Para establecer locationRestriction después del constructor, agrega locationProvider.locationRestriction más adelante en tu código, como se muestra en el siguiente ejemplo de 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,
   };

Cómo establecer una restricción de ubicación con el viewport del mapa

También puedes establecer límites de locationRestriction para que coincidan con el área que se ve actualmente en la vista del mapa.

Viajes a pedido

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

Tareas programadas

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

Inicializa la vista de mapa

Una vez que construyas el proveedor de ubicación, inicializa la vista del mapa de la misma manera que lo haces cuando sigues un solo vehículo.

Después de cargar la biblioteca de JavaScript de Compartir el viaje, inicializa la vista de mapa y agrégala a la página HTML. Tu página debe contener un elemento <div> que contenga la vista del mapa. El elemento <div> se denomina map_canvas en los siguientes ejemplos.

Viajes a pedido

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 detectar eventos y controlar errores

Una vez que comiences a seguir la flota, deberás escuchar los cambios de eventos y controlar los errores que surjan, como se describe en las siguientes secciones.

Cómo detectar eventos de cambio

Puedes recuperar metainformación sobre la flota del objeto de vehículo con el proveedor de ubicación. Los cambios en la metainformación activan un evento de actualización. La metainformación incluye propiedades del vehículo, como el estado de navegación, la distancia restante y los atributos personalizados.

Para obtener más información, consulta los siguientes recursos:

En los siguientes ejemplos, se muestra cómo escuchar estos eventos de cambio.

Viajes a pedido

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

Tareas programadas

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

Cómo detectar errores

También debes detectar y controlar los errores que se producen mientras sigues un vehículo. Los errores que surgen de forma asíncrona a partir de la solicitud de información del vehículo activan eventos de error.

En el siguiente ejemplo, se muestra cómo escuchar estos eventos para que puedas controlar los errores.

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

Cómo dejar de hacer el seguimiento de la flota

Para dejar de hacer un seguimiento de la flota, establece los límites del proveedor de ubicación en nulos y, luego, quita el proveedor de ubicación de la vista del mapa, como se describe en las siguientes secciones.

Establece los límites del proveedor de ubicación como nulos

Para evitar que el proveedor de ubicación haga un seguimiento de la flota, establece los límites del proveedor de ubicación como nulos.

Viajes a pedido

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Tareas programadas

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Quita el proveedor de ubicación de la vista del mapa

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Realiza el seguimiento de un vehículo de reparto mientras ves una flota de reparto

Si usas los servicios de movilidad para tareas programadas, puedes ver una flota y mostrar la ruta y las próximas tareas de un vehículo de reparto específico en la misma vista del mapa. Para ello, crea instancias de un Delivery Fleet Location Provider y un Delivery Vehicle Location Provider, y agrégalos a la vista del mapa. Una vez que se crea una instancia, el proveedor de ubicación de la flota de reparto comienza a mostrar los vehículos de reparto en el mapa. En los siguientes ejemplos, se muestra cómo crear instancias de ambos proveedores de ubicación:

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

Cómo usar la personalización de marcadores para hacer un seguimiento de un vehículo de reparto

Para permitir que el proveedor de ubicación del vehículo de reparto haga un seguimiento de un vehículo de reparto cuando haces clic en su marcador de flota, sigue estos pasos:

  1. Personaliza un marcador y agrega una acción de clic.

  2. Oculta el marcador para evitar duplicados.

En las siguientes secciones, se incluyen ejemplos de estos pasos.

Personaliza un marcador y agrega una acción de 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();
      });
    }
  };

Oculta el marcador para evitar duplicados

Oculta el marcador del proveedor de ubicación del vehículo de entrega para evitar renderizar dos marcadores para el mismo vehículo:

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

¿Qué sigue?