자바스크립트로 여행 따라가기

플랫폼 선택: Android iOS JavaScript

여정을 공유하면 소비자 앱에서 제공할 수 있습니다. 이렇게 하려면 앱에서 공유를 시작해야 합니다 이동 중 여정 진행 상황을 업데이트하고, 이동할 수 있습니다

이 문서에서는 이 프로세스의 다음과 같은 주요 단계를 설명합니다.

  1. 지도 설정하기
  2. 지도 초기화 및 공유된 여정 표시
  3. 이동 상황 업데이트 및 확인하기
  4. 여정 공유 중지
  5. 여정 공유 오류 처리

지도 설정하기

웹 앱에서 배송 수령 또는 배송을 추적하려면 지도를 로드해야 합니다. 소비자 SDK를 인스턴스화하여 여정 추적을 시작하세요 로드 가능 새 지도를 만들거나 기존 지도를 사용합니다. 그런 다음 초기화를 사용하여 함수를 사용하여 지도뷰가 추적 중인 아이템의 위치.

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

새 지도를 만들려면 웹 앱에서 Google Maps JavaScript API를 로드합니다. 이 다음 예는 Google Maps JavaScript API를 로드하고 초기화 확인을 트리거합니다.

  • callback 매개변수는 API가 로드된 후 initMap 함수를 실행합니다.
  • defer 속성을 사용하면 브라우저에서 페이지에 표시됩니다.

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

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

기존 지도 로드

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

예를 들어 표준 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>

기존 지도 바꾸기

마커 또는 기타 맞춤설정이 포함된 기존 지도를 바꿀 수 있습니다. 계속 사용할 수 있습니다.

예를 들어 표준 google.maps.Map가 포함된 웹페이지가 있는 경우 엔터티가 있는 경우 지도를 바꿔도 표시됩니다. 이 섹션에서는 이를 위한 단계를 설명합니다.

지도를 교체하고 맞춤설정을 유지하려면 다음 위치에 여정 공유를 추가하세요. HTML 페이지를 만들 수 있습니다. 다음과 같습니다.

  1. 인증 토큰 팩토리의 코드를 추가합니다.

  2. initMap() 함수에서 위치 제공자를 초기화합니다.

  3. initMap() 함수에서 지도뷰를 초기화합니다. 뷰에는 있습니다.

  4. 맞춤설정을 지도뷰의 콜백 함수로 이동합니다. 초기화하지 않아도 됩니다

  5. API 로더에 위치 라이브러리를 추가합니다.

다음 예는 어떤 변경사항을 적용할지 보여줍니다. 여행사와 함께 운항하는 경우 지정된 ID가 울루루 근처에 있을 경우, 이제 지도에 렌더링됩니다.

    <!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>
    let locationProvider;

    // (1) Authentication Token Fetcher
    async function authTokenFetcher(options) {
      // options is a record containing two keys called
      // serviceType and context. The developer should
      // generate the correct SERVER_TOKEN_URL and request
      // based on the values of these fields.
      const response = await fetch(SERVER_TOKEN_URL);
          if (!response.ok) {
            throw new Error(response.statusText);
          }
          const data = await response.json();
          return {
            token: data.Token,
            expiresInSeconds: data.ExpiresInSeconds
          };
    }

    // Initialize and add the map
    function initMap() {
      // (2) Initialize location provider.
      locationProvider = new google.maps.journeySharing.FleetEngineTripLocationProvider({
        projectId: "YOUR_PROVIDER_ID",
        authTokenFetcher,
      });

      // (3) Initialize map view (which contains the map).
      const mapView = new google.maps.journeySharing.JourneySharingMapView({
        element: document.getElementById('map'),
        locationProviders: [locationProvider],
        // any styling options
      });

      locationProvider.tripId = TRIP_ID;

        // (4) Add customizations like before.

        // 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 async attribute allows the browser to render the page while the API loads
          * The key parameter will contain your own API key (which is not needed for this tutorial)
          * The callback parameter executes the initMap() function
          *
          * (5) Add the SDK to the API loader.
        -->
        <script defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&libraries=journeySharing">
        </script>
      </body>
    </html>

지도 초기화 및 공유된 여정 표시

이동이 시작되면 앱에서 이동 위치 정보 제공자를 인스턴스화해야 합니다. 지도를 초기화하여 여정 공유를 시작합니다. 다음 섹션을 참고하세요. 를 참조하세요.

이동 위치 정보 제공자 인스턴스화

JavaScript SDK에는 미리 정의된 위치 정보 제공자가 있습니다. 사용할 수 있습니다 프로젝트 ID 및 인스턴스화하기 위해 토큰 팩토리에 대한 참조를 제공합니다.

자바스크립트

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

TypeScript

locationProvider =
    new google.maps.journeySharing
        .FleetEngineTripLocationProvider({
          projectId: 'your-project-id',
          authTokenFetcher: authTokenFetcher, // the token fetcher defined in the previous step

          // Optionally, you may specify a trip ID to
          // immediately start tracking.
          tripId: 'your-trip-id',
});

지도뷰 초기화

JavaScript SDK를 로드한 후 초기화 HTML 페이지에 추가합니다. 페이지에는 지도뷰를 포함하는 <div> 요소 <div> 요소 다음 예에서 이름이 map_canvas입니다.

자바스크립트

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

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

TypeScript

const mapView = new
    google.maps.journeySharing.JourneySharingMapView({
  element: document.getElementById('map_canvas'),
  locationProviders: [locationProvider],
  // Styling customizations; see below.
  vehicleMarkerSetup: vehicleMarkerSetup,
  anticipatedRoutePolylineSetup:
      anticipatedRoutePolylineSetup,
  // Any undefined styling options will use defaults.
});

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

이동 상황 업데이트 및 확인하기

앱은 이벤트를 수신 대기하고 이동 상황을 여정으로 업데이트해야 합니다. 진행될 수 있습니다 작업 객체에서 이동에 대한 메타 정보를 검색할 수 있습니다. 위치 정보 제공자를 사용합니다. 메타 정보에는 도착예정시간과 승차 또는 하차 전 남은 거리 메타 정보 변경사항 update 이벤트를 트리거합니다. 다음 예는 이러한 포드를 수신 대기하는 변경할 수 있습니다

자바스크립트

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

TypeScript

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

여정 공유 중지

이동이 끝나면 위치 정보 제공자가 있습니다. 이렇게 하려면 이동 ID를 삭제해야 합니다. 및 위치 정보 제공자 예시는 다음 섹션을 참고하세요.

위치 정보 제공자에서 여행 ID 삭제

다음 예는 위치 정보 제공자에서 이동 ID를 삭제하는 방법을 보여줍니다.

자바스크립트

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

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

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

자바스크립트

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

여정 공유 오류 처리

경로 정보 요청 트리거에서 비동기식으로 발생하는 오류 오류 이벤트입니다. 다음 예는 이러한 이벤트를 수신 대기하는 방법을 보여줍니다. 오류가 발생할 수 있습니다

자바스크립트

locationProvider.addListener('error', e => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

TypeScript

locationProvider.addListener('error', (e: google.maps.ErrorEvent) => {
  // e.error contains the error that triggered the
  // event
  console.error(e.error);
});

다음 단계

지도 스타일 지정