ติดตามการเดินทางใน JavaScript

เลือกแพลตฟอร์ม Android iOS JavaScript

เมื่อแชร์เส้นทาง แอปสำหรับผู้บริโภคจะแสดงตำแหน่งของ ยานพาหนะที่เหมาะสมให้กับผู้บริโภค แอปของคุณต้องเริ่มแชร์จึงจะดำเนินการนี้ได้ อัปเดตความคืบหน้าระหว่างการเดินทาง และหยุดแชร์ เมื่อการเดินทางเสร็จสมบูรณ์

เอกสารนี้ครอบคลุมถึงขั้นตอนสำคัญต่อไปนี้ในกระบวนการนี้

  1. ตั้งค่าแผนที่
  2. เริ่มต้นแผนที่และแสดงการเดินทางที่แชร์ร่วมกัน
  3. อัปเดตและติดตามความคืบหน้าของการเดินทาง
  4. หยุดการแชร์เส้นทาง
  5. จัดการข้อผิดพลาดในการแชร์เส้นทาง

ตั้งค่าแผนที่

คุณต้องโหลดแผนที่เพื่อติดตามการไปรับเองหรือจัดส่งสินค้าให้ในเว็บแอป และสร้างอินสแตนซ์ Consumer SDK เพื่อเริ่มติดตามเส้นทางของคุณ คุณโหลดได้ แผนที่ใหม่หรือใช้แผนที่เดิม จากนั้นคุณใช้การเริ่มต้น เพื่อสร้างอินสแตนซ์ SDK ของผู้บริโภคเพื่อให้มุมมองแผนที่สอดคล้องกับ ตำแหน่งของรายการที่ติดตาม

โหลดแผนที่ใหม่โดยใช้ JavaScript API ของ Google Maps

หากต้องการสร้างแผนที่ใหม่ ให้โหลด JavaScript API ของ Google Maps ในเว็บแอป ตัวอย่างต่อไปนี้แสดงวิธีโหลด JavaScript API ของ Google Maps ให้เปิดใช้งาน SDK แล้วเริ่มการตรวจสอบการเริ่มต้น

  • พารามิเตอร์ callback เรียกใช้ฟังก์ชัน initMap หลังจากโหลด API
  • แอตทริบิวต์ defer จะช่วยให้เบราว์เซอร์แสดงผลส่วนที่เหลือ ขณะที่ API โหลดอยู่

ใช้ฟังก์ชัน 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 มาตรฐาน เอนทิตีที่เครื่องหมายแสดงตามที่ระบุไว้ในโค้ด HTML ต่อไปนี้ ช่วงเวลานี้ แสดงแผนที่ของคุณโดยใช้ฟังก์ชัน initMap เดียวกันใน Callback ที่ตอนท้าย

    <!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. ย้ายการปรับแต่งของคุณลงในฟังก์ชัน Callback สำหรับมุมมองแผนที่ การเริ่มต้น

  5. เพิ่มไลบรารีตำแหน่งลงในตัวโหลด API

ตัวอย่างต่อไปนี้แสดงการเปลี่ยนแปลงที่จะเกิดขึ้น หากคุณจัดการเดินทางกับ รหัสที่ระบุไว้ใกล้ Uluru รหัสจะแสดงบนแผนที่

    <!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 มีผู้ให้บริการตำแหน่งที่กำหนดไว้ล่วงหน้า สำหรับ Fleet Engine Ridesharing API ใช้รหัสโปรเจ็กต์และ การอ้างอิงไปยังโรงงานโทเค็นของคุณเพื่อสร้างอินสแตนซ์

JavaScript

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 ในตัวอย่างต่อไปนี้

JavaScript

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

อัปเดตและติดตามความคืบหน้าของการเดินทาง

แอปควรคอยฟังเหตุการณ์และอัปเดตความคืบหน้าของการเดินทางเป็นการเดินทาง มีความคืบหน้า คุณเรียกข้อมูลเมตาเกี่ยวกับการเดินทางจากออบเจ็กต์งานได้ โดยใช้ผู้ให้บริการตำแหน่ง ข้อมูลเมตาประกอบด้วย ETA และ ระยะทางที่เหลือก่อนไปรับหรือส่งสินค้า การเปลี่ยนแปลงข้อมูลเมตา เรียกใช้เหตุการณ์ update ตัวอย่างต่อไปนี้แสดงวิธีฟังรายการเหล่านี้ เปลี่ยนกิจกรรม

JavaScript

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

หยุดการแชร์เส้นทาง

เมื่อการเดินทางสิ้นสุดลง คุณจะต้องหยุดผู้ให้บริการตำแหน่งไม่ให้ติดตาม โดยนำรหัสการเดินทางออก และผู้ให้บริการตำแหน่ง โปรดดูตัวอย่างในส่วนต่อไปนี้

นํารหัสการเดินทางออกจากผู้ให้บริการตําแหน่ง

ตัวอย่างต่อไปนี้แสดงวิธีนํารหัสการเดินทางออกจากผู้ให้บริการตําแหน่ง

JavaScript

locationProvider.tripId = '';

TypeScript

locationProvider.tripId = '';

นำผู้ให้บริการตำแหน่งออกจากมุมมองแผนที่

ตัวอย่างต่อไปนี้แสดงวิธีนำผู้ให้บริการตำแหน่งออกจากมุมมองแผนที่

JavaScript

mapView.removeLocationProvider(locationProvider);

TypeScript

mapView.removeLocationProvider(locationProvider);

จัดการข้อผิดพลาดในการแชร์เส้นทาง

ข้อผิดพลาดที่เกิดขึ้นไม่พร้อมกันจากทริกเกอร์การขอข้อมูลการเดินทาง เหตุการณ์ข้อผิดพลาด ตัวอย่างต่อไปนี้แสดงวิธีฟังเหตุการณ์เหล่านี้ จัดการข้อผิดพลาดได้

JavaScript

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

ขั้นตอนถัดไป

จัดรูปแบบแผนที่