Melihat fleet

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

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

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

Mulai lacak armada

Untuk melacak armada, Anda perlu membuat instance penyedia lokasi fleet dan menetapkan pembatasan lokasi untuk area pandang peta seperti dijelaskan dalam bagian.

Membuat instance penyedia lokasi fleet

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

Untuk membuat instance, ikuti langkah-langkah berikut:

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

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

  3. Setel pembatas untuk layar kendaraan. Gunakan locationRestriction untuk membatasi area untuk menampilkan kendaraan di peta. Lokasinya provider tidak aktif sampai ini ditetapkan. Anda juga bisa menyetel batas lokasi dalam konstruktor, atau setelah konstruktor.

  4. Melakukan inisialisasi tampilan peta.

Contoh berikut menunjukkan cara membuat instance penyedia lokasi fleet untuk baik untuk skenario tugas on-demand maupun terjadwal. Contoh ini juga menunjukkan cara menggunakan locationRestriction di 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 lebih lambat di kode Anda sebagai 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 saat ini terlihat dalam 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 membangun penyedia lokasi, inisialisasi tampilan peta dengan sama seperti saat Anda mengikuti sebuah kendaraan.

Setelah memuat library Berbagi Perjalanan JavaScript, lakukan inisialisasi tampilan peta dan menambahkannya ke laman HTML. Halaman Anda harus berisi elemen <div> yang menyimpan tampilan peta. Elemen <div> diberi nama 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 fleet, Anda perlu memproses perubahan peristiwa dan menangani kesalahan apa pun yang timbul seperti yang dijelaskan di bagian berikut.

Memproses peristiwa perubahan

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

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 perlu memproses dan menangani error yang terjadi saat mengikuti saat ini. Error yang muncul secara asinkron saat meminta kendaraan peristiwa error pemicu informasi.

Contoh berikut menunjukkan cara memproses peristiwa ini sehingga Anda dapat menangani {i>error.<i}

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 fleet, Anda harus menyetel batas penyedia lokasi ke null, lalu hapus penyedia lokasi dari tampilan peta seperti dijelaskan dalam bagian berikut ini.

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 Mobility untuk tugas terjadwal, Anda berdua dapat melihat armada dan menampilkan rute dan tugas yang akan datang untuk kendaraan pengiriman tertentu dalam tampilan peta yang sama. Untuk melakukannya, buat instance Lokasi Armada Pengiriman Penyedia dan Penyedia Lokasi Kendaraan Pengiriman, lalu tambahkan keduanya ke peta {i>view<i}. Setelah instance dibuat, penyedia lokasi inventaris pengiriman mulai ditampilkan 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 mengklik penanda fleetnya, ikuti langkah-langkah berikut:

  1. Sesuaikan penanda dan tambahkan 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

Menyembunyikan 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