Fleet 보기

이 섹션에서는 JavaScript Fleet Tracking Library를 사용하여 Fleet을 보는 방법을 보여줍니다. 이 절차에서는 Fleet Tracking Library를 설정하고 지도를 로드했다고 가정합니다. 자세한 내용은 JavaScript Fleet Tracking Library 설정을 참고하세요.

이 문서에서는 Fleet을 볼 때 할 수 있는 다음 작업을 설명합니다.

  1. Fleet 추적을 시작합니다.
  2. 이벤트를 수신 대기하고 오류를 처리합니다.
  3. 추적을 중지합니다.
  4. Fleet을 보는 동안 단일 차량을 추적합니다.

Fleet 추적 시작

Fleet을 추적하려면 Fleet 위치 제공자를 인스턴스화하고 다음 섹션에 설명된 대로 지도 표시 영역의 위치 제한을 설정해야 합니다.

Fleet 위치 제공자 인스턴스화

JavaScript Fleet Tracking Library에는 Fleet Engine에서 여러 차량을 가져오는 위치 제공자가 포함되어 있습니다.

인스턴스화하려면 다음 단계를 따르세요.

  1. 프로젝트 ID 와 토큰 가져오기 도구에 대한 참조를 사용합니다.

  2. 차량 필터 쿼리 사용 차량 필터 쿼리는 지도에 표시되는 차량을 제어합니다. 필터는 Fleet Engine에 전달됩니다.

  3. 차량 표시의 경계 영역을 설정합니다. locationRestriction을 사용하여 지도에 차량을 표시할 영역을 제한합니다. 위치 제공자는 이 설정이 완료될 때까지 활성화되지 않습니다. 생성자에서 또는 생성자 후에 위치 경계를 설정할 수 있습니다.

  4. 지도 뷰를 초기화합니다.

다음 예에서는 온디맨드 및 예약된 작업 시나리오 모두에 대해 Fleet 위치 제공자를 인스턴스화하는 방법을 보여줍니다. 또한 이 예에서는 생성자에서 locationRestriction을 사용하여 위치 제공자를 활성화하는 방법을 보여줍니다.

온디맨드 이동

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

예약된 작업

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

생성자 후에 locationRestriction을 설정하려면 다음 JavaScript 예와 같이 코드의 뒷부분에 locationProvider.locationRestriction을 추가합니다.

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

지도 표시 영역을 사용하여 위치 제한 설정

또한 locationRestriction 경계를 지도 뷰에 현재 표시되는 영역과 일치하도록 설정할 수 있습니다.

온디맨드 이동

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

예약된 작업

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

지도 뷰 초기화

위치 제공자를 구성한 후에는 단일 차량을 추적할 때와 동일한 방식으로 지도 뷰를 초기화합니다.

JavaScript Journey Sharing Library를 로드한 후 지도 뷰를 초기화하고 HTML 페이지에 추가합니다. 페이지에는 지도 뷰를 포함하는 <div> 요소가 포함되어야 합니다. 다음 예에서 <div> 요소 의 이름은 map_canvas 입니다.=

온디맨드 이동

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

예약된 작업

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

이벤트 수신 대기 및 오류 처리

Fleet 추적을 시작한 후에는 다음 섹션에 설명된 대로 이벤트 변경사항을 수신 대기하고 발생하는 오류를 처리해야 합니다.

변경 이벤트 수신 대기

위치 제공자를 사용하여 차량 객체에서 Fleet에 관한 메타 정보를 가져올 수 있습니다. 메타 정보가 변경되면 update 이벤트가 트리거됩니다. 메타 정보에는 탐색 상태, 남은 거리, 맞춤 속성과 같은 차량 속성이 포함됩니다.

자세한 내용은 다음을 참고하세요.

다음 예에서는 이러한 변경 이벤트를 수신 대기하는 방법을 보여줍니다.

온디맨드 이동

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

예약된 작업

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

오류 수신 대기

차량을 추적하는 동안 발생하는 오류를 수신 대기하고 처리할 수도 있습니다. 차량 정보를 요청할 때 비동기적으로 발생하는 오류는 오류 이벤트를 트리거합니다.

다음 예에서는 오류를 처리할 수 있도록 이러한 이벤트를 수신 대기하는 방법을 보여줍니다.

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

Fleet 추적 중지

Fleet 추적을 중지하려면 위치 제공자의 경계를 null로 설정한 후 다음 섹션에 설명된 대로 지도 뷰에서 위치 제공자를 삭제합니다.

위치 제공자 경계를 null로 설정

위치 제공자가 Fleet을 추적하지 못하도록 하려면 위치 제공자의 경계를 null로 설정합니다.

온디맨드 이동

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

예약된 작업

JavaScript

locationProvider.locationRestriction = null;

TypeScript

locationProvider.locationRestriction = null;

지도 뷰에서 위치 제공자 삭제

다음 예에서는 지도 뷰에서 위치 제공자를 삭제하는 방법을 보여줍니다.

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

배송 Fleet을 보는 동안 배송 차량 추적

예약된 작업에 Mobility 서비스를 사용하는 경우 Fleet을 보고 동일한 지도 뷰에서 특정 배송 차량의 경로와 예정된 작업을 표시할 수 있습니다. 이렇게 하려면 배송 Fleet 위치 제공자와 배송 차량 위치 제공자를 모두 인스턴스화하고 둘 다 지도 뷰에 추가합니다. 인스턴스화되면 배송 Fleet 위치 제공자가 지도에 배송 차량을 표시하기 시작합니다. 다음 예에서는 두 위치 제공자를 모두 인스턴스화하는 방법을 보여줍니다.

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

마커 맞춤설정을 사용하여 배송 차량 추적

배송 차량 위치 제공자가 Fleet 마커를 클릭할 때 배송 차량을 추적하도록 하려면 다음 단계를 따르세요.

  1. 마커를 맞춤설정하고 클릭 작업을 추가합니다.

  2. 중복 마커를 방지하기 위해 마커를 숨깁니다.

이 단계의 예는 다음 섹션에 있습니다.

마커 맞춤설정 및 클릭 작업 추가

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

중복 마커를 방지하기 위해 마커 숨기기

동일한 차량에 대해 두 개의 마커가 렌더링되지 않도록 배송 차량 위치 제공자에서 마커를 숨깁니다.

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

다음 단계