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 を読み込んで 初期化チェックをトリガーします。

  • callback パラメータは、API の読み込み後に initMap 関数を実行します。
  • defer 属性を使用すると、ブラウザは残りの部分のレンダリングを続行できます。 表示されます。

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 ローダに追加します。

次の例は、行う変更を示しています。旅行関連の計画がある場合、 指定した ID がウルル付近にあると、地図にレンダリングされます。

    <!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プロジェクト ID と トークン ファクトリへの参照を追加してインスタンス化します。

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

移動経路の共有を停止

ルートが終了したら、位置情報プロバイダによるルートの追跡を停止する必要があります。 移動しますそのためには、ルート ID を削除します。 位置情報プロバイダ次のセクションで例をご覧ください。

位置情報提供元からルート ID を削除する

次の例は、位置情報提供元からルート ID を削除する方法を示しています。

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

次のステップ

地図のスタイルを設定する