Melihat fleet

Bagian ini menunjukkan cara menggunakan library pelacakan fleet JavaScript untuk melihat fleet. Prosedur ini mengasumsikan bahwa Anda telah menyiapkan library pelacakan armada dan memuat peta. Untuk mengetahui detailnya, lihat Menyiapkan library pelacakan armada JavaScript.

Dokumen ini membahas hal-hal berikut yang dapat Anda lakukan saat melihat armada:

  1. Mulai lacak armada.
  2. Memproses peristiwa dan menangani error.
  3. Berhenti melacak.
  4. Melacak satu kendaraan saat melihat armada.

Mulai lacak armada

Untuk melacak armada, Anda perlu membuat instance penyedia lokasi armada dan menetapkan batasan lokasi untuk area tampilan peta seperti yang dijelaskan di bagian berikut.

Membuat instance penyedia lokasi fleet

Library pelacakan fleet JavaScript menyertakan penyedia lokasi yang mengambil beberapa kendaraan dari Fleet Engine.

Untuk membuat instance-nya, ikuti langkah-langkah berikut:

  1. Gunakan project ID Anda serta referensi ke pengambil token Anda.

  2. Menggunakan kueri filter kendaraan Kueri filter kendaraan mengontrol kendaraan yang ditampilkan peta. Filter diteruskan ke Fleet Engine.

  3. Setel pembatas untuk layar kendaraan. Gunakan locationRestriction untuk membatasi area untuk menampilkan kendaraan di peta. Penyedia lokasi tidak akan aktif hingga setelan ini ditetapkan. Anda dapat menetapkan batas lokasi di konstruktor, atau setelah konstruktor.

  4. Lakukan inisialisasi tampilan peta.

Contoh berikut menunjukkan cara membuat instance penyedia lokasi fleet untuk skenario tugas on-demand dan terjadwal. Contoh ini juga menunjukkan cara menggunakan locationRestriction dalam konstruktor untuk membuat penyedia lokasi aktif.

Perjalanan on-demand

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which vehicles are retrieved.
          vehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

Tugas terjadwal

JavaScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately make the location provider active.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

Untuk menetapkan locationRestriction setelah konstruktor, tambahkan locationProvider.locationRestriction nanti dalam kode Anda seperti yang ditunjukkan dalam contoh JavaScript berikut.

   // You can choose to not set locationRestriction in the constructor.
   // In this case, the location provider *DOES NOT START* after this line, because
   // no locationRestriction is set.
   locationProvider = new google.maps.journeySharing.DeliveryFleetLocationProvider({
   ... // not setting locationRestriction here
   });

   // You can then set the locationRestriction *after* the constructor.
   // After this line, the location provider is active.
   locationProvider.locationRestriction = {
     north: 1,
     east: 2,
     south: 0,
     west: 1,
   };

Menetapkan pembatasan lokasi menggunakan area pandang peta

Anda juga dapat menetapkan batas locationRestriction agar cocok dengan area yang saat ini terlihat di tampilan peta.

Perjalanan on-demand

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location tracking will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

Tugas terjadwal

JavaScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

TypeScript

google.maps.event.addListenerOnce(
  mapView.map, 'bounds_changed', () => {
    const bounds = mapView.map.getBounds();
    if (bounds) {
      // If you did not specify a location restriction in the
      // location provider constructor, you may do so here.
      // Location provider will start as soon as this is set.
      locationProvider.locationRestriction = bounds;
    }
  });

Melakukan inisialisasi tampilan peta

Setelah membuat penyedia lokasi, lakukan inisialisasi tampilan peta dengan cara yang sama seperti yang Anda lakukan saat mengikuti satu kendaraan.

Setelah memuat library JavaScript Journey Sharing, lakukan inisialisasi tampilan peta dan tambahkan ke halaman HTML. Halaman Anda harus berisi elemen &lt;div&gt; yang menyimpan tampilan peta. Elemen <div> dinamai map_canvas dalam contoh berikut.=

Perjalanan on-demand

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.vehicleId
                        = 'your-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.VehicleId
                        = 'your-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

Tugas terjadwal

JavaScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
});

// If you did not specify a delivery vehicle ID in the
// location provider constructor, you may do so here.
// Location tracking will start as soon as this is set.
locationProvider.deliveryVehicleId
                        = 'your-delivery-vehicle-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 want.
mapView.map.setCenter('Times Square, New York, NY');
mapView.map.setZoom(14);

Memproses peristiwa dan menangani error

Setelah mulai mengikuti armada, Anda perlu memproses perubahan peristiwa dan menangani error yang muncul seperti yang dijelaskan di bagian berikut.

Memproses peristiwa perubahan

Anda dapat mengambil informasi meta tentang fleet dari objek kendaraan menggunakan penyedia lokasi. Perubahan pada informasi meta akan memicu peristiwa update. Informasi meta mencakup properti kendaraan seperti status navigasi, jarak yang tersisa, dan atribut kustom.

Untuk mengetahui detailnya, lihat referensi berikut:

Contoh berikut menunjukkan cara memproses peristiwa perubahan ini.

Perjalanan on-demand

JavaScript

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

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineFleetLocationProviderUpdateEvent) => {
  // e.vehicles contains data that may be
  // useful to the rest of the UI.
  if (e.vehicles) {
    for (vehicle of e.vehicles) {
      console.log(vehicle.navigationStatus);
    }
  }
});

Tugas terjadwal

JavaScript

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

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineDeliveryFleetLocationProviderUpdateEvent) => {
  // e.deliveryVehicles contains data that may be
  // useful to the rest of the UI.
  if (e.deliveryVehicles) {
    for (vehicle of e.deliveryVehicles) {
      console.log(vehicle.remainingDistanceMeters);
    }
  }
});

Memantau error

Anda juga ingin memproses dan menangani error yang terjadi saat mengikuti kendaraan. Error yang muncul secara asinkron dari permintaan informasi kendaraan akan memicu peristiwa error.

Contoh berikut menunjukkan cara memproses peristiwa ini sehingga Anda dapat menangani error.

JavaScript

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

TypeScript

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

Berhenti melacak armada

Untuk berhenti melacak armada, Anda menetapkan batas penyedia lokasi ke null, lalu menghapus penyedia lokasi dari tampilan peta seperti yang dijelaskan di bagian berikut.

Menetapkan batas penyedia lokasi ke null

Untuk menghentikan penyedia lokasi melacak fleet, tetapkan batas penyedia lokasi ke null.

Perjalanan on-demand

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Tugas terjadwal

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Menghapus penyedia lokasi dari tampilan peta

Contoh berikut menampilkan cara menghapus penyedia lokasi dari tampilan peta.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Melacak kendaraan pengiriman sambil melihat armada pengiriman

Jika menggunakan layanan Mobilitas untuk tugas terjadwal, Anda dapat melihat armada dan menampilkan rute serta tugas mendatang untuk kendaraan pengiriman tertentu di tampilan peta yang sama. Untuk melakukannya, buat instance Penyedia Lokasi Armada Pengiriman dan Penyedia Lokasi Kendaraan Pengiriman, lalu tambahkan keduanya ke tampilan peta. Setelah dibuat instance-nya, penyedia lokasi armada pengiriman akan mulai menampilkan kendaraan pengiriman di peta. Contoh berikut menunjukkan cara membuat instance kedua penyedia lokasi:

JavaScript

deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});

TypeScript

deliveryFleetLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryFleetLocationProvider({
          projectId,
          authTokenFetcher,

          // Optionally, specify location bounds to
          // limit which delivery vehicles are
          // retrieved and immediately start tracking.
          locationRestriction: {
            north: 37.3,
            east: -121.8,
            south: 37.1,
            west: -122,
          },
          // Optionally, specify a filter to limit
          // which delivery vehicles are retrieved.
          deliveryVehicleFilter:
            'attributes.foo = "bar" AND attributes.baz = "qux"',
        });

deliveryVehicleLocationProvider =
    new google.maps.journeySharing
        .FleetEngineDeliveryVehicleLocationProvider({
          projectId,
          authTokenFetcher
        });

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [
    deliveryFleetLocationProvider,
    deliveryVehicleLocationProvider,
  ],
  // Any other options
});

Gunakan penyesuaian penanda untuk melacak kendaraan pengiriman

Agar penyedia lokasi kendaraan pengiriman dapat melacak kendaraan pengiriman saat Anda mengklik penanda armadanya, ikuti langkah-langkah berikut:

  1. Menyesuaikan penanda dan menambahkan tindakan klik.

  2. Menyembunyikan penanda untuk mencegah penanda duplikat.

Contoh untuk langkah-langkah ini ada di bagian berikut.

Menyesuaikan penanda dan menambahkan tindakan klik

JavaScript

// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };

TypeScript

// Specify the customization function either separately, or as a field in
// the options for the delivery fleet location provider constructor.
deliveryFleetLocationProvider.deliveryVehicleMarkerCustomization =
  (params: google.maps.journeySharing.DeliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.addListener('click', () => {
        // params.vehicle.name follows the format
        // "providers/{provider}/deliveryVehicles/{vehicleId}".
        // Only the vehicleId portion is used for the delivery vehicle
        // location provider.
        deliveryVehicleLocationProvider.deliveryVehicleId =
            params.vehicle.name.split('/').pop();
      });
    }
  };

Menyembunyikan penanda untuk mencegah penanda duplikat

Sembunyikan penanda dari penyedia lokasi kendaraan pengiriman untuk mencegah rendering dua penanda untuk kendaraan yang sama:

JavaScript

// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };

TypeScript

// Specify the customization function either separately, or as a field in
// the options for the delivery vehicle location provider constructor.
deliveryVehicleLocationProvider.deliveryVehicleMarkerCustomization =
  (params: deliveryVehicleMarkerCustomizationFunctionParams) => {
    if (params.isNew) {
      params.marker.setVisible(false);
    }
  };

Langkah berikutnya