Как отслеживать поездки с помощью 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>

Загрузка существующей карты

Вы также можете загрузить существующую карту, созданную с помощью Google 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);
});

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

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