Как отслеживать поездки с помощью JavaScript

Выберите платформу: Android iOS JavaScript

Когда вы отслеживаете поездку, в вашем приложении для пользователей показывается местоположение нужного транспортного средства. Для этого приложению нужно начать отслеживать поездку, обновлять информацию о ее ходе и прекратить отслеживание, когда поездка завершится.

В этом документе описаны следующие основные этапы процесса:

  1. Как настроить карту
  2. Инициализация карты и отображение совместной поездки
  3. Как отслеживать ход поездки и обновлять информацию
  4. Как отменить подписку на маршрут
  5. Как устранять ошибки в поездках

Как настроить карту

Чтобы отслеживать доставку или получение груза в веб-приложении, загрузите карту и создайте экземпляр Consumer SDK. Вы можете загрузить новую карту или использовать существующую. Затем вы используете функцию инициализации, чтобы создать экземпляр Consumer SDK, чтобы представление карты соответствовало местоположению отслеживаемого объекта.

Как загрузить новую карту с помощью Google Maps JavaScript API

Чтобы создать новую карту, загрузите Google Maps JavaScript API в веб-приложение. В следующем примере показано, как загрузить Google Maps JavaScript API, включить SDK и запустить проверку инициализации.

  • Параметр callback выполняет функцию initMap после загрузки API.
  • Атрибут defer разрешает браузеру обрабатывать остальную часть страницы во время загрузки API.

Используйте функцию initMap, чтобы создать экземпляр Consumer SDK. Пример:

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

Как загрузить существующую карту

Вы также можете загрузить существующую карту, созданную с помощью Maps JavaScript API, например ту, которую вы уже используете.

Предположим, у вас есть веб-страница со стандартным объектом google.maps.Map, на котором показывается маркер, как определено в следующем HTML-коде. В конце функции обратного вызова используется та же функция initMap:

    <!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>

Как заменить существующую карту

Вы можете заменить существующую карту, содержащую маркеры или другие настройки, не потеряв их.

Например, если у вас есть веб-страница со стандартным объектом google.maps.Map, на котором показан маркер, вы можете заменить карту, сохранив маркер. Ниже описано, как это сделать.

Чтобы заменить карту и сохранить настройки, добавьте на HTML-страницу передачу поездки, выполнив следующие действия (они также пронумерованы в примере ниже):

  1. Добавьте код для фабрики токенов аутентификации.

  2. Инициализируйте поставщика геоданных в функции initMap().

  3. Инициализируйте представление карты в функции initMap(). В представлении есть карта.

  4. Перенесите настройки в функцию обратного вызова для инициализации просмотра карты.

  5. Добавьте библиотеку местоположений в загрузчик API.

Ниже приведен пример. Если вы совершите поездку с указанным идентификатором рядом с Улуру, она будет показана на карте:

    <!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>

Инициализация карты и отображение прогресса поездки

Когда поездка начинается, приложение должно создать экземпляр поставщика данных о местоположении и инициализировать карту, чтобы начать передачу данных о поездке. Примеры приведены в разделах ниже.

Создание экземпляра поставщика геоданных для поездки

В JavaScript SDK есть встроенный поставщик данных о местоположении для Fleet Engine Ridesharing API. Используйте идентификатор проекта и ссылку на фабрику токенов, чтобы создать ее экземпляр.

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

Инициализация вида карты

После загрузки JavaScript SDK инициализируйте представление карты и добавьте его на HTML-страницу. На странице должен быть элемент <div>, содержащий представление карты. В примере ниже элемент <div> называется map_canvas.

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

Как отслеживать ход поездки и обновлять информацию

Приложение должно отслеживать события и обновлять информацию о ходе поездки. Вы можете получить метаинформацию о поездке из объекта задачи, используя поставщика геоданных. Метаданные включают расчетное время прибытия и оставшееся расстояние до точки посадки или высадки. Изменения в метаданных вызывают событие update. В примере ниже показано, как прослушивать эти события.

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

Как отменить подписку на маршрут

Когда поездка завершится, вам нужно будет отключить отслеживание поездки поставщиком геоданных. Для этого удалите идентификатор поездки и поставщика данных о местоположении. Примеры приведены в разделах ниже.

Удалите идентификатор поездки из поставщика геоданных.

В следующем примере показано, как удалить идентификатор поездки из поставщика данных о местоположении.

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

Удалите поставщика данных о местоположении из представления карты.

В следующем примере показано, как удалить поставщика данных о местоположении из представления карты.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Как устранять ошибки в поездках

Ошибки, которые возникают асинхронно при запросе информации о поездке, вызывают события ошибок. В примере ниже показано, как прослушивать эти события для обработки ошибок.

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

Дальнейшие действия

Как настроить стиль карты