Ver una flota

En esta sección, se muestra cómo usar la biblioteca de seguimiento de flota de JavaScript para ver una flota. En estos procedimientos, se da por sentado que configuraste la flota la biblioteca de seguimiento de conversiones y cargas un mapa. Para obtener más información, consulta Configura la biblioteca de seguimiento de la flota de JavaScript.

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

  1. Comienza a hacer un seguimiento de la flota.
  2. Escucha eventos y soluciona errores.
  3. Detén el seguimiento.
  4. Haz el seguimiento de un solo vehículo mientras consultas una flota.

Comienza a hacer un seguimiento de la flota

Para rastrear una flota, debes crear una instancia de un proveedor de ubicación de flota y configurar restricciones de ubicación para el viewport del mapa como se describe a continuación: secciones.

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

La biblioteca JavaScript de seguimiento de la flota 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 del proyecto y una referencia al recuperador de tokens.

  2. Usa una consulta de filtro de vehículos. La consulta de filtro de vehículos controla qué vehículos que muestra el mapa. El filtro se pasa a Fleet Engine.

  3. Configura los límites para la pantalla del vehículo. Usa locationRestriction para limitan el área en la que se muestran los vehículos en el mapa. La ubicación El proveedor no estará activo hasta que se configure. Puedes establecer límites de ubicación en el constructor o después del constructor.

  4. Inicializa la vista de mapa.

En los siguientes ejemplos se muestra cómo crear una instancia de un proveedor de ubicación de flotas para situaciones de tareas programadas y bajo demanda. Estos ejemplos también muestran cómo usar el locationRestriction en el constructor para hacer que el proveedor de ubicación activo.

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

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 configurar locationRestriction después del constructor, agrega lo siguiente: locationProvider.locationRestriction más adelante en el código como que 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 configurar límites de locationRestriction para que coincidan con el área actual en la vista de mapa.

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

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

Cómo inicializar la vista de mapa

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

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 <div> que contiene la vista de mapa El elemento <div> 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 comiences a seguir la flota, deberás escuchar los cambios en los eventos y solucionar los errores que surjan como se describe en las siguientes secciones.

Cómo detectar eventos de cambio

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

Para obtener más detalles, consulta lo siguiente:

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

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

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

Detecta errores

También debes detectar y manejar los errores que ocurren vehículo. Errores que surgen de forma asíncrona al solicitar un vehículo información activa eventos de error.

En el siguiente ejemplo, se muestra cómo escuchar estos eventos para poder manejar 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);
});

Dejar de seguir la flota

Para dejar de rastrear la flota, establece los límites del proveedor de ubicación en nulos, y, a continuación, eliminar el proveedor de ubicación de la vista de mapa, tal como se describe en el secciones a continuación.

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

Para evitar que el proveedor de ubicación siga la flota, establece los límites del proveedor de ubicación a un valor nulo.

Viajes on demand

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Tareas programadas

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

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

Sigue un vehículo de reparto mientras consultas una flota de entregas

Si usas los Servicios de movilidad para tareas programadas, pueden visualizar un flota y muestra la ruta y las próximas tareas para un vehículo de entrega específico en la misma vista de mapa. Para ello, crea una instancia de Ubicación de la flota de entrega un proveedor y un proveedor de ubicación de vehículos de entrega, y agregarlos al mapa vista. Cuando se crea una instancia, el proveedor de ubicación de la flota de entregas comienza a mostrar vehículos de entrega en el mapa. En los siguientes ejemplos, se muestra cómo crear una instancia 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 el seguimiento de un vehículo de reparto

Permitir que el proveedor de ubicación del vehículo de entrega realice el seguimiento de un vehículo de entrega cuando hagas clic en el marcador de la flota, sigue estos pasos:

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

  2. Oculta el marcador para evitar que se duplique.

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

Cómo personalizar un marcador y agregar 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();
      });
    }
  };

Cómo ocultar el marcador para evitar que se duplique

Oculta el marcador del proveedor de ubicación del vehículo de entrega para evitar que se renderice 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?