Mengikuti perjalanan di JavaScript

Pilih platform: Android iOS JavaScript

Saat Anda membagikan perjalanan, aplikasi konsumen akan menampilkan lokasi kendaraan yang sesuai untuk konsumen. Untuk melakukannya, aplikasi Anda harus mulai berbagi perjalanan, memperbarui progres perjalanan selama perjalanan, dan berhenti membagikan ketika perjalanan selesai.

Dokumen ini membahas langkah-langkah penting berikut dalam proses ini:

  1. Siapkan peta
  2. Melakukan inisialisasi peta dan menampilkan perjalanan bersama
  3. Perbarui dan ikuti progres perjalanan
  4. Hentikan berbagi perjalanan
  5. Menangani error berbagi perjalanan

Siapkan peta

Untuk mengikuti pengambilan atau pengantaran pengiriman di aplikasi web, Anda perlu memuat peta dan buat instance Consumer SDK untuk mulai melacak perjalanan Anda. Anda dapat memuat menggunakan peta baru atau menggunakan yang sudah ada. Anda kemudian menggunakan inisialisasi untuk membuat instance Consumer SDK sehingga tampilan peta sesuai dengan lokasi item yang sedang dilacak.

Memuat peta baru menggunakan Google Maps JavaScript API

Untuk membuat peta baru, muat Google Maps JavaScript API di aplikasi web Anda. Tujuan contoh berikut menunjukkan cara memuat Google Maps JavaScript API, mengaktifkan SDK, dan memicu pemeriksaan inisialisasi.

  • Parameter callback menjalankan fungsi initMap setelah API dimuat.
  • Atribut defer memungkinkan browser terus merender sisa halaman saat API dimuat.

Gunakan fungsi initMap untuk membuat instance Consumer SDK. Contoh:

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

Memuat peta yang ada

Anda juga dapat memuat peta yang sudah ada yang dibuat dengan Google Maps JavaScript API, seperti yang sudah Anda gunakan.

Misalnya, Anda memiliki halaman web dengan google.maps.Map standar entitas tempat penanda ditampilkan seperti yang didefinisikan dalam kode HTML berikut. Ini menampilkan peta Anda menggunakan fungsi initMap yang sama dalam callback di bagian akhir:

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

Mengganti peta yang ada

Anda dapat mengganti peta yang ada yang menyertakan penanda atau penyesuaian lainnya tanpa kehilangan penyesuaian tersebut.

Misalnya, jika Anda memiliki halaman web dengan google.maps.Map standar entitas tempat penanda ditampilkan, Anda bisa mengganti peta dan menyimpan penanda. Bagian ini menjelaskan langkah-langkah untuk melakukannya.

Untuk mengganti peta dan mempertahankan penyesuaian, tambahkan berbagi perjalanan ke halaman HTML Anda menggunakan langkah-langkah ini, yang juga diberi nomor dalam contoh berikut ini:

  1. Tambahkan kode untuk factory token autentikasi.

  2. Lakukan inisialisasi penyedia lokasi dalam fungsi initMap().

  3. Lakukan inisialisasi tampilan peta dalam fungsi initMap(). Tampilan berisi atribut peta.

  4. Memindahkan penyesuaian Anda ke dalam fungsi callback untuk tampilan peta inisialisasi.

  5. Tambahkan library lokasi ke loader API.

Contoh berikut menunjukkan perubahan yang akan dilakukan. Jika Anda melakukan perjalanan dengan ID yang ditentukan di dekat Uluru, kini akan dirender di peta:

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

Melakukan inisialisasi peta dan menampilkan perjalanan bersama

Saat perjalanan dimulai, aplikasi Anda perlu membuat instance penyedia lokasi perjalanan lalu menginisialisasi peta untuk memulai berbagi perjalanan. Lihat bagian berikut untuk contoh.

Membuat instance penyedia lokasi perjalanan

JavaScript SDK memiliki penyedia lokasi yang telah ditetapkan untuk Fleet Engine Ridesharing API. Gunakan project ID dan referensi ke factory token Anda untuk membuat instance-nya.

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

Melakukan inisialisasi tampilan peta

Setelah memuat JavaScript SDK, lakukan inisialisasi tampilan peta dan menambahkannya ke laman HTML. Halaman Anda harus berisi elemen <div> yang menyimpan tampilan peta. Elemen <div> bernama map_canvas dalam contoh berikut.

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

Perbarui dan ikuti progres perjalanan

Aplikasi Anda harus memproses peristiwa dan memperbarui progres perjalanan sebagai perjalanan progresnya. Anda dapat mengambil informasi meta tentang perjalanan dari objek tugas menggunakan penyedia lokasi. Informasi {i>meta<i} mencakup PWT dan jarak yang tersisa sebelum penjemputan atau pengantaran. Perubahan pada informasi meta memicu peristiwa update. Contoh berikut menunjukkan cara mendengarkan peristiwa perubahan.

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

Hentikan berbagi perjalanan

Saat perjalanan berakhir, Anda harus menghentikan penyedia lokasi agar tidak melacak berkemah. Untuk melakukannya, hapus ID perjalanan dan penyedia lokasi. Lihat bagian berikut untuk mengetahui contohnya.

Menghapus ID perjalanan dari penyedia lokasi

Contoh berikut menunjukkan cara menghapus ID perjalanan dari penyedia lokasi.

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

Menghapus penyedia lokasi dari tampilan peta

Contoh berikut menampilkan cara menghapus penyedia lokasi dari tampilan peta.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Menangani error berbagi perjalanan

Error yang muncul secara asinkron karena pemicu permintaan informasi perjalanan peristiwa error. Contoh berikut menunjukkan cara memproses peristiwa ini untuk menangani error.

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

Langkah berikutnya

Menata gaya peta