متابعة رحلة في JavaScript

اختيار النظام الأساسي: Android iOS JavaScript

عند مشاركة رحلة، يعرض تطبيق المستهلك موقع المركبة المناسبة للمستهلك. لتنفيذ هذا الإجراء، يجب أن يبدأ تطبيقك بالمشاركة. الرحلة وتحديث مدى تقدم الرحلة أثناء الرحلة والتوقف عن مشاركة الرحلة عند اكتمال الرحلة.

يتناول هذا المستند الخطوات الرئيسية التالية في هذه العملية:

  1. إعداد خريطة
  2. تهيئة خريطة وعرض الرحلة المشتركة
  3. تعديل مسار الرحلة ومتابعته
  4. إيقاف مشاركة الرحلة
  5. التعامل مع أخطاء المشاركة في الرحلة

إعداد خريطة

لمتابعة استلام شحنة أو تسليمها في تطبيق الويب، عليك تحميل خريطة. وإنشاء مثيل لحزمة تطوير البرامج (SDK) الخاصة بالمستهلك لبدء تتبُّع رحلتك يمكنك تحميل خريطة جديدة أو استخدام خريطة حالية. يمكنك بعد ذلك استخدام واجهة برمجة التطبيقات لإنشاء مثيل SDK للمستهلك حتى يتجاوب عرض الخريطة مع موقع السلعة التي يتم تتبّعها

تحميل خريطة جديدة باستخدام واجهة برمجة تطبيقات JavaScript لخرائط Google

لإنشاء خريطة جديدة، يجب تحميل واجهة برمجة تطبيقات JavaScript لخرائط Google في تطبيق الويب. تشير رسالة الأشكال البيانية المثال التالي كيفية تحميل واجهة برمجة تطبيقات JavaScript لخرائط Google، وتمكين SDK وبدء التحقق من التهيئة.

  • تشغِّل المَعلمة callback الدالة initMap بعد تحميل واجهة برمجة التطبيقات.
  • تتيح السمة defer للمتصفح مواصلة عرض بقية محتوى الصفحة أثناء تحميل واجهة برمجة التطبيقات.

يمكنك استخدام الدالة initMap لإنشاء مثيل لحزمة تطوير البرامج (SDK) الخاصة بالمستهلك. على سبيل المثال:

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

تحميل خريطة حالية

يمكنك أيضًا تحميل خريطة حالية تم إنشاؤها بواسطة واجهة برمجة تطبيقات JavaScript لخرائط Google، كتلك التي تستخدمها بالفعل.

على سبيل المثال، لنفترض أن لديك صفحة ويب تتضمن google.maps.Map قياسي الذي تظهر عليه علامة كما هو موضح في رمز HTML التالي. هذا النمط تعرض خريطتك باستخدام الدالة 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. أضِف مكتبة المواقع الجغرافية إلى أداة تحميل واجهة برمجة التطبيقات.

يوضح المثال التالي التغييرات التي يجب إجراؤها. إذا كنت تدير رحلة مع المعرف المحدد بالقرب من أولورو، يتم عرضه الآن على الخريطة:

    <!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>

تهيئة خريطة وعرض الرحلة المشتركة

عند بدء رحلة، يحتاج تطبيقك إلى إنشاء مثيل لموفِّر الموقع الجغرافي للرحلة. ثم تهيئة خريطة لبدء مشاركة الرحلة. الاطّلاع على الأقسام التالية للحصول على أمثلة.

إنشاء مثيل موفّر موقع الرحلة

تحتوي حزمة تطوير البرامج (SDK) لJavaScript على موفّر موقع جغرافي محدّد مسبقًا. لواجهة برمجة تطبيقات مشاركة الرحلات في Fleet Engine. استخدِم معرّف مشروعك مرجعًا لمصنع الرموز المميزة لإنشاء مثيله.

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

إعداد عرض الخريطة

بعد تحميل حزمة تطوير البرامج (SDK) لـ JavaScript، ابدأ عرض الخريطة وإضافته إلى صفحة 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);

تعديل مسار الرحلة ومتابعته

يجب أن يستمع تطبيقك إلى الأحداث وأن يعدّل مسار التقدّم في الرحلة. المشروع. يمكنك استرداد معلومات تعريفية حول رحلة من كائن المهمة. باستخدام موفر الموقع. تتضمن معلومات التعريف الوقت المقدر للوصول المسافة المتبقية قبل الركوب أو التسليم. التغييرات على المعلومات الوصفية إلى تشغيل حدث 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);
});

الخطوات التالية

تصميم خريطة