배송 조회

이제 예약된 작업에 JavaScript Consumer SDK를 설정했으므로 소비자 앱으로 배송을 추적할 수 있습니다. 이 문서에서는 이 프로세스의 다음 주요 단계를 다룹니다.

  • 지도를 초기화하고 공유된 여정 표시
  • 여정 진행 상황 업데이트 및 팔로우
  • 배송 팔로우 중지하기
  • 배송 추적 오류 처리

지도 설정

웹 앱에서 배송 상품 수령 또는 배송을 추적하려면 지도를 로드하고 Consumer SDK를 인스턴스화하여 배송 상품 추적을 시작해야 합니다. 새 지도를 로드하거나 기존 지도를 사용할 수 있습니다. 그런 다음 초기화 함수를 사용하여 Consumer SDK를 인스턴스화하여 지도 뷰가 추적 중인 상품의 위치에 대응하도록 합니다.

Google Maps JavaScript API를 사용하여 새 지도 로드

새 지도를 만들려면 웹 앱에서 Google Maps JavaScript API를 로드하세요. 다음 예에서는 Google Maps JavaScript API를 로드하고, SDK를 사용 설정하고, 초기화 확인을 트리거하는 방법을 보여줍니다.

  • callback 매개변수는 API가 로드된 후 initMap 함수를 실행합니다.
  • defer 속성을 사용하면 API가 로드되는 동안 브라우저가 페이지의 나머지 부분을 계속 렌더링할 수 있습니다.

initMap 함수를 사용하여 Consumer SDK를 인스턴스화합니다. 예를 들면 다음과 같습니다.

    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing" defer></script>

기존 지도 로드

이미 사용 중인 지도와 같이 Google Maps JavaScript API로 만든 기존 지도를 로드할 수도 있습니다.

예를 들어 다음 HTML 코드에 정의된 대로 마커가 표시되는 표준 google.maps.Map 항목이 있는 웹페이지가 있다고 가정해 보겠습니다. 다음은 마지막 콜백에서 동일한 initMap 함수를 사용하여 지도를 표시합니다.

    <!DOCTYPE html>
    <html>
      <head>
        <style>
           /* Set the size of the div element that contains the map */
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
        </style>
      </head>
      <body>
        <h3>My Google Maps Demo</h3>
        <!--The div element for the map -->
        <div id="map"></div>
        <script>
        // Initialize and add the map
        function initMap() {
          // The location of Pier 39 in San Francisco
          var pier39 = {lat: 37.809326, lng: -122.409981};
          // The map, initially centered at Mountain View, CA.
          var map = new google.maps.Map(document.getElementById('map'));
          map.setOptions({center: {lat: 37.424069, lng: -122.0916944}, zoom: 14});

          // The marker, now positioned at Pier 39
          var marker = new google.maps.Marker({position: pier39, map: map});
        }
        </script>
        <!-- Load the API from the specified URL.
           * The defer attribute allows the browser to render the page while the API loads.
           * The key parameter contains your own API key.
           * The callback parameter executes the initMap() function.
        -->
        <script defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
        </script>
      </body>
    </html>

배송 위치 정보 제공자 인스턴스화

이전에 정의한 승인 토큰 가져오기와 함께 배송 위치 정보 제공자를 사용하여 Fleet Engine에서 데이터 수신을 시작합니다.

이 예에서는 위치 제공자를 인스턴스화하는 방법을 보여줍니다.

자바스크립트

const locationProvider =
  new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
      projectId: 'your-project-id',
      authTokenFetcher: authTokenFetcher,  // the fetcher defined previously
  });

TypeScript

const locationProvider =
  new google.maps.journeySharing.FleetEngineShipmentLocationProvider({
      projectId: 'your-project-id',
      authTokenFetcher: authTokenFetcher,  // the fetcher defined previously
  });

공유된 여정 표시

예약된 작업의 진행 상황을 표시하려면 추적된 여정의 위치에 해당하는 지도 프레임을 설정하는 뷰를 초기화합니다. 그런 다음 Fleet Engine에서 정보를 가져온 후 Consumer SDK에서 진행 상황을 제공합니다.

도움말:

  1. 페이지에 지도 뷰를 포함하는 <div> 요소가 있는지 확인합니다. 다음 예에서 <div> 요소의 이름은 map_canvas입니다.

  2. Fleet Engine이 추적된 여정에 적용하는 기본 공개 상태 규칙을 알아두세요. 활성 차량 배송 및 예약된 정류장 작업의 공개 상태 규칙을 구성할 수도 있습니다. 작업 구성 가이드의 작업 공개 상태 맞춤설정을 참고하세요.

다음 예에서는 지도 뷰를 초기화하는 방법을 보여줍니다.

자바스크립트

function initMap() {
  const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
    element: document.getElementById('map_canvas'),
    // Any undefined styling options use defaults.
  });

  // If you did not specify a tracking ID in the location
  // provider constructor, you may do so here.
  // Location tracking starts as soon as this is set.
  locationProvider.trackingId = 'your-tracking-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 wish.
  mapView.map.setCenter({lat: 37.2, lng: -121.9});
  mapView.map.setZoom(14);
}

TypeScript

function initMap() {
  const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
    element: document.getElementById('map_canvas'),
   // Any undefined styling options will use defaults.
  });

  // If you did not specify a tracking ID in the location
  // provider constructor, you may do so here.
  // Location tracking starts as soon as this is set.
  locationProvider.trackingId = 'your-tracking-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 wish.
  mapView.map.setCenter({lat: 37.2, lng: -121.9});
  mapView.map.setZoom(14);
}

배송 현황 업데이트

이벤트를 수신 대기하고 여정이 진행됨에 따라 배송 진행 상황을 업데이트할 수 있습니다. 위치 제공자를 사용하여 taskTrackingInfo 객체에서 메타 정보를 가져옵니다. 메타 정보가 변경되면 업데이트 이벤트가 트리거됩니다. taskTrackingInfo 객체는 다음을 제공합니다.

  • 도착예정시간
  • 남은 경유지 수
  • 수령 또는 배송까지 남은 거리

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

자바스크립트

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

TypeScript

locationProvider.addListener('update',
    (e: google.maps.journeySharing.FleetEngineShipmentLocationProviderUpdateEvent) => {
  // e.taskTrackingInfo contains data that may be useful
  // to the rest of the UI.
  console.log(e.taskTrackingInfo.remainingStopCount);
});

여러 작업의 표시 기준

예약된 작업용 Consumer SDK는 지도에 추적 ID당 하나의 작업만 표시합니다. 하지만 일반적으로 시스템에서 이동하는 동안 상품과 연결된 상태로 유지되는 특정 배송 상품에 하나의 추적 ID를 할당하기도 합니다. 즉, 단일 추적 ID가 동일한 패키지의 수령 작업 후 배송 작업과 같은 여러 작업 또는 패키지의 여러 실패한 배송 작업과 연결될 수 있습니다.

이 상황을 처리하기 위해 Fleet Engine은 다음 표에 표시된 작업 표시 기준을 적용합니다.

작업 기준 결과
수령 작업 열기
정확히 하나가 존재함 작업 표시
여러 개 존재 오류 생성
종료된 수령 작업
정확히 하나가 존재함 작업 표시
여러 개가 존재함 (결과 시간이 있는 항목도 있음) 가장 최근 결과 시간이 있는 작업 표시
여러 개가 존재함 (결과 시간이 있는 항목 없음) 오류 생성
배송 작업 열기
정확히 하나가 존재함 작업 표시
여러 개 존재 오류 생성
Closed delivery tasks(종료된 배송 작업)
정확히 하나가 존재함 작업 표시
여러 개가 존재함 (결과 시간이 있는 항목도 있음) 가장 최근 결과 시간이 있는 작업 표시
여러 개가 존재함 (결과 시간이 있는 항목 없음) 오류 생성

배송 팔로우 중지하기

배송 여정이 완료되거나 취소되면 소비자 앱은 지도 뷰에서 추적 ID와 위치 제공자를 삭제하여 배송을 추적하는 것을 중지해야 합니다. 자세한 내용은 다음 섹션을 참고하세요.

추적 ID 삭제

위치 제공업체가 배송을 추적하지 못하도록 하려면 위치 제공업체에서 추적 ID를 삭제하세요. 다음 예시는 이 작업을 수행하는 방법을 보여줍니다.

자바스크립트

locationProvider.trackingId = '';

TypeScript

locationProvider.trackingId = '';

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

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

자바스크립트

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

배송 추적 오류 처리

배송 정보 요청에서 비동기적으로 발생하는 오류는 error 이벤트를 트리거합니다. 다음 예는 오류를 처리하기 위해 이러한 이벤트를 수신 대기하는 방법을 보여줍니다.

자바스크립트

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

참고: 예기치 않은 오류를 처리하려면 라이브러리 호출을 try...catch 블록으로 래핑해야 합니다.

다음 단계