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 bằng 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 một 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 các sự kiện và xử lý lỗi.
  3. Dừng theo dõi.
  4. Theo dõi một xe khi xem một độ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 nhà cung cấp vị trí đội xe và đặt các 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í đội xe

Thư viện theo dõi đội xe bằng 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ể cho thư viện này, hãy làm theo các bước sau:

  1. Sử dụng mã dự án cũng như 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 ranh giới hiển thị 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í không hoạt động cho đến khi bạn đặt ranh giới 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 chạy khung nhìn bản đồ.

Các ví dụ sau đây cho thấy cách tạo thực thể cho nhà cung cấp vị trí đội xe cho cả trường hợp theo yêu cầu và tác vụ đã lên 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 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"',
        });

Tác 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 sau đó trong mã của bạn như minh hoạ trong ví dụ về JavaScript sau.

   // 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 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 khung nhìn 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;
    }
  });

Tác 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 khung nhìn bản đồ

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

Sau khi tải thư viện Chia sẻ hành trình bằng JavaScript, hãy khởi chạy khung nhìn bản đồ và thêm khung nhìn đó vào trang HTML. Trang của bạn phải chứa một <div> phần tử giữ khung nhìn 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);

Tác 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);

Lắng nghe các sự kiện và xử lý lỗi

Sau khi bắt đầu theo dõi đội xe, bạn cần lắng nghe 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.

Lắng nghe các 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 nhà cung cấp vị trí. Các thay đổi đối với thông tin meta sẽ kích hoạt sự kiện update. 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, khoảng cách còn lại và các thuộc tính tuỳ chỉnh.

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

Các ví dụ sau đây cho thấy cách lắng nghe 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);
    }
  }
});

Tác 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 muốn lắng nghe và xử lý các lỗi xảy ra trong khi theo dõi một xe. Các lỗi phát sinh không đồng bộ từ việc yêu cầu thông tin về xe sẽ kích hoạt các sự kiện lỗi.

Ví dụ sau đây cho thấy cách lắng nghe 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);
});

Dừng theo dõi đội xe

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

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

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

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

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Tác vụ đã lên lịch

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

Xoá nhà cung cấp vị trí khỏi khung nhìn bản đồ

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

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

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

Nếu đang sử dụng Dịch vụ di động cho các tác vụ đã lên lịch, bạn có thể vừa xem một đội xe vừa hiển thị tuyến đường và các tác vụ sắp tới cho một xe giao hàng cụ thể trong cùng một khung nhìn bản đồ. Để thực hiện 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, đồng thời thêm cả hai nhà cung cấp này vào khung nhìn bản đồ. Sau khi tạo thực thể, nhà cung cấp vị trí độ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 một xe giao hàng khi bạn nhấp vào điểm đánh dấu đội xe của 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 để ngăn điểm đánh dấu trùng lặp.

Các ví dụ cho các bước này có trong các 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 để ngăn điểm đánh dấu trùng lặp

Ẩn điểm đánh dấu khỏi nhà cung cấp vị trí xe giao hàng để ngăn kết xuất 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