Sigue un viaje en JavaScript

Selecciona la plataforma: Android iOS JavaScript

Cuando compartes un viaje, tu aplicación para consumidores muestra la ubicación de la vehículo apropiado para el consumidor. Para ello, la app debe comenzar a compartir del viaje, actualizar el progreso durante el viaje y dejar de compartir la del viaje cuando este finaliza.

En este documento, se abarcan los siguientes pasos clave en este proceso:

  1. Cómo configurar un mapa
  2. Inicializa un mapa y muestra el recorrido compartido
  3. Actualiza y sigue el progreso del viaje
  4. Dejar de compartir el viaje
  5. Maneja errores de uso compartido de recorridos

Cómo configurar un mapa

Para seguir el retiro o la entrega de un envío en tu aplicación web, debes cargar un mapa y crear una instancia del SDK para consumidores para hacer un seguimiento de tu recorrido. Puedes cargar un mapa nuevo o usar uno existente. Luego, usarás el comando de inicialización para crear una instancia del SDK de consumidor, de modo que la vista de mapa corresponda al la ubicación del artículo del que se realiza el seguimiento.

Carga un mapa nuevo con la Google Maps JavaScript API

Para crear un mapa nuevo, carga la Google Maps JavaScript API en tu aplicación web. El En el siguiente ejemplo, se muestra cómo cargar la Google Maps JavaScript API, habilitar el y activa la verificación de inicialización.

  • El parámetro callback ejecuta la función initMap después de que se carga la API.
  • El atributo defer permite que el navegador continúe renderizando el resto de tu contenido. mientras se carga la API.

Usa la función initMap para crear una instancia del SDK de consumidor. Por ejemplo:

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

Cómo cargar un mapa existente

También puedes cargar un mapa existente creado por la Google Maps JavaScript API, por ejemplo, uno que ya tengas en uso.

Por ejemplo, supongamos que tienes una página web con un elemento google.maps.Map estándar. la entidad en la que se muestra un marcador, tal como se define en el siguiente código HTML. Esta muestra tu mapa con la misma función initMap en la devolución de llamada al final:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
           /* Set the size of the div element that contains the map */
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>
        <script>
        // Initialize and add the map
        function initMap() {
          // The location of Pier 39 in San Francisco
          var pier39 = {lat: 37.809326, lng: -122.409981};
          // The map, initially centered at Mountain View, CA.
          var map = new google.maps.Map(document.getElementById('map'));
          map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

          // The marker, now positioned at Pier 39
          var marker = new google.maps.Marker({position: pier39, map: map});
        }
        </script>
        <!-- Load the API from the specified URL.
           * The defer attribute allows the browser to render the page while the API loads.
           * The key parameter contains your own API key.
           * The callback parameter executes the initMap() function.
        -->
        <script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
      </body>
    </html>

Cómo reemplazar un mapa existente

Puedes reemplazar un mapa existente que incluya marcadores y otras personalizaciones sin perder esas personalizaciones.

Por ejemplo, si tienes una página web con un elemento google.maps.Map estándar, en la que se muestra un marcador, puedes reemplazar el mapa y mantener el marcador. En esta sección, se describen los pasos para hacerlo.

Para reemplazar el mapa y mantener las personalizaciones, agrega viajes compartidos a tu página HTML siguiendo estos pasos, que también están numerados en el ejemplo que sigue:

  1. Agrega código para la fábrica del token de autenticación.

  2. Inicializa un proveedor de ubicación en la función initMap().

  3. Inicializa la vista de mapa en la función initMap(). La vista contiene las mapa.

  4. Mueve tu personalización a la función de devolución de llamada para la vista de mapa de inicio.

  5. Agrega la biblioteca de ubicaciones al cargador de API.

En el siguiente ejemplo, se muestran los cambios que se deben realizar. Si realizas un viaje con el ID especificado cerca de Uluru, ahora se renderiza en el mapa:

    <!DOCTYPE html>
    <html>
      <head>
        <style>
           /* Set the size of the div element that contains the map */
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>
        <script>
    let locationProvider;

    // (1) Authentication Token Fetcher
    async function authTokenFetcher(options) {
      // options is a record containing two keys called
      // serviceType and context. The developer should
      // generate the correct SERVER_TOKEN_URL and request
      // based on the values of these fields.
      const response = await fetch(SERVER_TOKEN_URL);
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          const data = await response.json();
          return {
            token: data.Token,
            expiresInSeconds: data.ExpiresInSeconds
          };
    }

    // Initialize and add the map
    function initMap() {
      // (2) Initialize location provider.
      locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
        projectId: "YOUR_PROVIDER_ID",
        authTokenFetcher,
      });

      // (3) Initialize map view (which contains the map).
      const mapView = new google.maps.journeySharing.JourneySharingMapView({
        element: document.getElementById('map'),
        locationProviders: [locationProvider],
        // any styling options
      });

      locationProvider.tripId = TRIP_ID;

        // (4) Add customizations like before.

        // The location of Pier 39 in San Francisco
        var pier39 = {lat: 37.809326, lng: -122.409981};
        // The map, initially centered at Mountain View, CA.
        var map = new google.maps.Map(document.getElementById('map'));
        map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

        // The marker, now positioned at Pier 39
        var marker = new google.maps.Marker({position: pier39, map: map});
      };

        </script>
        <!-- Load the API from the specified URL
          * The async attribute allows the browser to render the page while the API loads
          * The key parameter will contain your own API key (which is not needed for this tutorial)
          * The callback parameter executes the initMap() function
          *
          * (5) Add the SDK to the API loader.
        -->
        <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
        </script>
      </body>
    </html>

Inicializa un mapa y muestra el recorrido compartido

Cuando comienza un viaje, la app debe crear una instancia de un proveedor de ubicación de viajes y, luego, inicializar un mapa para empezar a compartir el recorrido. Consulta las siguientes secciones para ver ejemplos.

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

El SDK de JavaScript tiene un proveedor de ubicación predefinido para la API de transporte compartido de Fleet Engine. Usa tu ID del proyecto y una referencia a la fábrica de tokens para crear una instancia.

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

Cómo inicializar la vista de mapa

Después de cargar el SDK de JavaScript, inicializa la vista de mapa y agregarla a la página HTML. Tu página debe contener un elemento <div> que contenga la vista de mapa El elemento <div> se llama map_canvas en el siguiente ejemplo.

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

// If you did not specify a trip ID in the location
// provider constructor, you may do so here.
// Location tracking starts as soon as this is set.
locationProvider.tripId = 'your-trip-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 choose.
mapView.map.setCenter({lat: 37.2, lng: -121.9});
mapView.map.setZoom(14);

Actualiza y sigue el progreso del viaje

Tu app debe escuchar eventos y actualizar el progreso del viaje como un viaje. avanza el proyecto. Puedes recuperar información meta sobre un viaje desde el objeto de tarea usando el proveedor de ubicación. La metainformación incluye la hora de llegada estimada y la distancia restante antes del punto de partida o de destino. Cambios en la metainformación activar un evento update En el siguiente ejemplo, se muestra cómo escuchar los eventos de cambio.

JavaScript

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

TypeScript

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

Dejar de compartir el viaje

Cuando el viaje finalice, debes impedir que el proveedor de ubicación realice el seguimiento viaje. Para ello, debes quitar el ID de viaje y el proveedor de ubicación. Consulta las siguientes secciones para ver ejemplos.

Quita el ID de viaje del proveedor de ubicación

En el siguiente ejemplo, se muestra cómo quitar un ID de viaje del proveedor de ubicación.

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

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

Maneja errores de uso compartido de recorridos

Errores que surgen de forma asíncrona al solicitar información de viaje los eventos de error. En el siguiente ejemplo, se muestra cómo escuchar estos eventos para manejar los errores.

JavaScript

locationProvider.addListener('error', e => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

¿Qué sigue?

Cómo aplicar diseño a un mapa