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

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

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

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

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

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

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

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

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

  • พารามิเตอร์ callback จะเรียกใช้ฟังก์ชัน initMap หลังจากที่ API โหลด
  • แอตทริบิวต์ 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 สร้างขึ้นได้ด้วย เช่น แผนที่ที่คุณใช้อยู่

ตัวอย่างเช่น สมมติว่าคุณมีหน้าเว็บที่มีเอนทิตี 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);

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

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

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

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

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