Xem nhóm thiết bị

Phần này trình bày cách sử dụng thư viện theo dõi đội xe JavaScript để xem một đội xe. Các quy trình này giả định rằng bạn đã thiết lập thư viện theo dõi đội xe và tải bản đồ. Để biết thông tin chi tiết, hãy xem bài viết Thiết lập thư viện theo dõi đội xe bằng JavaScript.

Tài liệu này thảo luận về những việc bạn có thể làm khi xem một đội xe:

  1. Bắt đầu theo dõi đội xe.
  2. Lắng nghe sự kiện và xử lý lỗi.
  3. Dừng theo dõi.
  4. Theo dõi một xe trong khi xem đội xe.

Bắt đầu theo dõi đội xe

Để theo dõi một đội xe, bạn cần tạo thực thể cho một nhà cung cấp vị trí đội xe và đặt các quy định hạn chế về vị trí cho khung nhìn bản đồ như mô tả trong các phần sau.

Tạo thực thể cho nhà cung cấp vị trí của đội xe

Thư viện theo dõi đội xe JavaScript bao gồm một nhà cung cấp vị trí tìm nạp nhiều xe từ Fleet Engine.

Để tạo thực thể, hãy làm theo các bước sau:

  1. Sử dụng mã dự án cũng như thông tin tham chiếu đến trình tìm nạp mã thông báo.

  2. Sử dụng truy vấn bộ lọc xe Truy vấn bộ lọc xe kiểm soát những xe mà bản đồ hiển thị. Bộ lọc được truyền đến Fleet Engine.

  3. Đặt vùng giới hạn cho màn hình của xe. Sử dụng locationRestriction để giới hạn khu vực hiển thị xe trên bản đồ. Nhà cung cấp vị trí sẽ không hoạt động cho đến khi bạn đặt giá trị này. Bạn có thể đặt ranh giới vị trí trong hàm khởi tạo hoặc sau hàm khởi tạo.

  4. Khởi động chế độ xem bản đồ.

Các ví dụ sau đây cho thấy cách tạo thực thể cho một nhà cung cấp vị trí của đội xe cho cả trường hợp theo yêu cầu và trường hợp theo lịch. Các ví dụ này cũng cho thấy cách sử dụng locationRestriction trong hàm khởi tạo để kích hoạt trình cung cấp vị trí.

Chuyến đi theo yêu cầu

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

Nhiệm vụ đã lên lịch

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

Để đặt locationRestriction sau hàm khởi tạo, hãy thêm locationProvider.locationRestriction vào sau trong mã của bạn như trong ví dụ về JavaScript sau đây.

   // 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,
   };

Đặt quy định hạn chế về vị trí bằng khung nhìn bản đồ

Bạn cũng có thể đặt ranh giới locationRestriction để khớp với khu vực hiện đang hiển thị trong chế độ xem bản đồ.

Chuyến đi theo yêu cầu

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

Nhiệm vụ đã lên lịch

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

Khởi chạy chế độ xem bản đồ

Sau khi tạo trình cung cấp vị trí, hãy khởi chạy chế độ xem bản đồ theo cách tương tự như khi bạn theo dõi một chiếc xe.

Sau khi tải thư viện Chia sẻ hành trình JavaScript, hãy khởi chạy chế độ xem bản đồ và thêm chế độ xem đó vào trang HTML. Trang của bạn phải chứa một phần tử <div> chứa chế độ xem bản đồ. Phần tử <div> được đặt tên là map_canvas trong các ví dụ sau.=

Chuyến đi theo yêu cầu

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

Nhiệm vụ đã lên lịch

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

Theo dõi sự kiện và xử lý lỗi

Sau khi bắt đầu theo dõi đội xe, bạn cần theo dõi các thay đổi về sự kiện và xử lý mọi lỗi phát sinh như mô tả trong các phần sau.

Theo dõi sự kiện thay đổi

Bạn có thể truy xuất thông tin meta về đội xe từ đối tượng xe bằng cách sử dụng nhà cung cấp vị trí. Những thay đổi đối với thông tin meta sẽ kích hoạt sự kiện update (cập nhật). Thông tin meta bao gồm các thuộc tính của xe như trạng thái điều hướng, quãng đường còn lại và các thuộc tính tùy chỉnh.

Để biết thông tin chi tiết, hãy tham khảo nội dung sau:

Các ví dụ sau đây cho thấy cách theo dõi các sự kiện thay đổi này.

Chuyến đi theo yêu cầu

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

Nhiệm vụ đã lên lịch

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

Lắng nghe lỗi

Bạn cũng nên theo dõi và xử lý các lỗi xảy ra trong khi theo dõi một xe. Lỗi phát sinh không đồng bộ khi yêu cầu thông tin về xe sẽ kích hoạt sự kiện lỗi.

Ví dụ sau đây cho thấy cách theo dõi các sự kiện này để bạn có thể xử lý lỗ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);
});

Ngừng theo dõi đội xe

Để dừng theo dõi đội xe, bạn đặt ranh giới của trình cung cấp vị trí thành rỗng, sau đó xoá trình cung cấp vị trí khỏi chế độ xem bản đồ như mô tả trong các phần sau.

Đặt giới hạn của nhà cung cấp vị trí thành rỗng

Để ngăn nhà cung cấp vị trí theo dõi đội xe, hãy đặt giới hạn của nhà cung cấp vị trí thành rỗng.

Chuyến đi theo yêu cầu

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Nhiệm vụ đã lên lịch

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Xoá nhà cung cấp vị trí khỏi chế độ xem bản đồ

Ví dụ sau đây cho thấy cách xoá một nhà cung cấp vị trí khỏi chế độ xem bản đồ.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

Theo dõi xe giao hàng trong khi xem đội xe giao hàng

Nếu đang sử dụng dịch vụ Di chuyển cho các nhiệm vụ theo lịch, bạn có thể xem cả đội xe và hiển thị tuyến đường cũng như các nhiệm vụ sắp tới cho một xe giao hàng cụ thể trong cùng một chế độ xem bản đồ. Để làm việc này, hãy tạo thực thể cho cả Nhà cung cấp vị trí đội xe giao hàng và Nhà cung cấp vị trí xe giao hàng, rồi thêm cả hai vào chế độ xem bản đồ. Sau khi được tạo thực thể, nhà cung cấp vị trí của đội xe giao hàng sẽ bắt đầu hiển thị các xe giao hàng trên bản đồ. Các ví dụ sau đây cho thấy cách tạo thực thể cho cả hai nhà cung cấp vị trí:

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

Sử dụng tính năng tuỳ chỉnh điểm đánh dấu để theo dõi xe giao hàng

Để cho phép nhà cung cấp vị trí xe giao hàng theo dõi xe giao hàng khi bạn nhấp vào điểm đánh dấu đội xe, hãy làm theo các bước sau:

  1. Tuỳ chỉnh điểm đánh dấu và thêm thao tác nhấp.

  2. Ẩn điểm đánh dấu để tránh điểm đánh dấu trùng lặp.

Ví dụ về các bước này có trong những phần sau.

Tuỳ chỉnh điểm đánh dấu và thêm thao tác nhấp

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

Ẩn điểm đánh dấu để tránh trùng lặp điểm đánh dấu

Ẩn điểm đánh dấu khỏi nhà cung cấp vị trí của xe giao hàng để tránh hiển thị hai điểm đánh dấu cho cùng một xe:

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

Bước tiếp theo