مشاركة عبر


استخدام الوحدة لخدمات خرائط Azure

توفر عدة تطوير برامج الويب لتطبيق خرائط Azure وحدة خدمات. هذه الوحدة النمطية هي مكتبة مساعدة تجعل من السهل استخدام خدمات REST في خرائط Azure في تطبيقات الويب أو Node.js.من خلال استخدام JavaScript أو TypeScript.

إشعار

إيقاف وحدة خدمة خرائط Azure Web SDK

تم الآن إهمال وحدة خدمة خرائط Azure Web SDK وسيتم إيقافها في 9/30/26. لتجنب انقطاع الخدمة، نوصي بالترحيل إلى خرائط Azure JavaScript REST SDK بحلول 9/30/26. لمزيد من المعلومات، راجع دليل مطوري JavaScript/TypeScript REST SDK (معاينة).

استخدام وحدة الخدمات في صفحة ويب

  1. قم بإنشاء ملف HTML جديد.

  2. حمّل الوحدة لخدمات خرائط Azure. يمكنك تحميله بإحدى طريقتين:

    • استخدم إصدار شبكة تسليم المحتوى من Azure المستضاف عمومياً من الوحدة النمطية لخدمات خرائط Azure. أضف مرجع برنامج نصي إلى <head> عنصر الملف:
    <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
    • بدلاً من ذلك، حمّل وحدة الخدمات للتعليمات البرمجية المصدر خرائط Azure لعدة تطوير البرامج للويب محليًا باستخدام حزمة npm azure-maps-rest، ثم استضافها مع تطبيقك. تتضمن هذه الحزمة أيضًا تعريفات TypeScript. استخدم هذا الأمر:

      npm install azure-maps-rest

      بعد ذلك، استخدم إعلان استيراد لإضافة الوحدة النمطية إلى ملف مصدر:

      import * as service from "azure-maps-rest";
      
  3. أنشئ البنية الأساسية لبرنامج ربط العمليات التجارية للمصادقة. يجب إنشاء البنية الأساسية لبرنامج ربط العمليات التجارية قبل أن تتمكن من تهيئة نقطة نهاية عميل عنوان URL للخدمة. استخدم مفتاح حساب خرائط Azure الخاص بك أو بيانات اعتماد Microsoft Entra لمصادقة عميل خرائط Azure خدمة البحث. في هذا المثال، يتم إنشاء عميل عنوان URL خدمة البحث.

    إذا كنت تستخدم مفتاح اشتراك للمصادقة:

    // Get an Azure Maps key at https://azure.com/maps.
    var subscriptionKey = '<Your Azure Maps Key>';
    
    // Use SubscriptionKeyCredential with a subscription key.
    var subscriptionKeyCredential = new atlas.service.SubscriptionKeyCredential(subscriptionKey);
    
    // Use subscriptionKeyCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(subscriptionKeyCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });
    
    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);
    

    إذا كنت تستخدم معرف Microsoft Entra للمصادقة:

    // Enter your Azure AD client ID.
    var clientId = "<Your Azure Active Directory Client Id>";
    
    // Use TokenCredential with OAuth token (Azure AD or Anonymous).
    var aadToken = await getAadToken();
    var tokenCredential = new atlas.service.TokenCredential(clientId, aadToken);
    
    // Create a repeating time-out that will renew the Azure AD token.
    // This time-out must be cleared when the TokenCredential object is no longer needed.
    // If the time-out is not cleared, the memory used by the TokenCredential will never be reclaimed.
    var renewToken = async () => {
      try {
        console.log("Renewing token");
        var token = await getAadToken();
        tokenCredential.token = token;
        tokenRenewalTimer = setTimeout(renewToken, getExpiration(token));
      } catch (error) {
        console.log("Caught error when renewing token");
        clearTimeout(tokenRenewalTimer);
        throw error;
      }
    }
    tokenRenewalTimer = setTimeout(renewToken, getExpiration(aadToken));
    
    // Use tokenCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(tokenCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });
    
    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);
    
    function getAadToken() {
      // Use the signed-in auth context to get a token.
      return new Promise((resolve, reject) => {
        // The resource should always be https://atlas.microsoft.com/.
        const resource = "https://atlas.microsoft.com/";
        authContext.acquireToken(resource, (error, token) => {
          if (error) {
            reject(error);
          } else {
            resolve(token);
          }
        });
      })
    }
    
    function getExpiration(jwtToken) {
      // Decode the JSON Web Token (JWT) to get the expiration time stamp.
      const json = atob(jwtToken.split(".")[1]);
      const decode = JSON.parse(json);
    
      // Return the milliseconds remaining until the token must be renewed.
      // Reduce the time until renewal by 5 minutes to avoid using an expired token.
      // The exp property is the time stamp of the expiration, in seconds.
      const renewSkew = 300000;
      return (1000 * decode.exp) - Date.now() - renewSkew;
    }
    

    للحصول على مزيد من المعلومات، راجع المصادقة باستخدام خرائط Azure.

  4. تستخدم التعليمات البرمجية التالية عميل عنوان URL خرائط Azure خدمة البحث الذي تم إنشاؤه حديثًا لترميز الموقع الجغرافي: "1 Microsoft Way، Redmond، WA". تستخدم التعليمات البرمجية الدالة searchAddress وتعرض النتائج على هيئة جدول في نص الصفحة.

    // Search for "1 microsoft way, redmond, wa".
    searchURL.searchAddress(atlas.service.Aborter.timeout(10000), '1 microsoft way, redmond, wa')
      .then(response => {
        var html = [];
    
        // Display the total results.
        html.push('Total results: ', response.summary.numResults, '<br/><br/>');
    
        // Create a table of the results.
        html.push('<table><tr><td></td><td>Result</td><td>Latitude</td><td>Longitude</td></tr>');
    
        for(var i=0;i<response.results.length;i++){
          html.push('<tr><td>', (i+1), '.</td><td>', 
            response.results[i].address.freeformAddress, 
            '</td><td>', 
            response.results[i].position.lat,
            '</td><td>', 
            response.results[i].position.lon,
            '</td></tr>');
        }
    
        html.push('</table>');
    
        // Add the resulting HTML to the body of the page.
        document.body.innerHTML = html.join('');
    });
    

فيما يلي نموذج التعليمات البرمجية الكامل قيد التشغيل:

<html>
 <head>

  <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>

  <script type="text/javascript">
    
    // Get an Azure Maps key at https://azure.com/maps.
    var subscriptionKey = '{Your-Azure-Maps-Subscription-key}';

    // Use SubscriptionKeyCredential with a subscription key.
    var subscriptionKeyCredential = new atlas.service.SubscriptionKeyCredential(subscriptionKey);

    // Use subscriptionKeyCredential to create a pipeline.
    var pipeline = atlas.service.MapsURL.newPipeline(subscriptionKeyCredential, {
      retryOptions: { maxTries: 4 } // Retry options
    });

    // Create an instance of the SearchURL client.
    var searchURL = new atlas.service.SearchURL(pipeline);

    // Search for "1 microsoft way, redmond, wa".
    searchURL.searchAddress(atlas.service.Aborter.timeout(10000), '1 microsoft way, redmond, wa')
      .then(response => {
      var html = [];

      // Display the total results.
      html.push('Total results: ', response.summary.numResults, '<br/><br/>');

      // Create a table of the results.
      html.push('<table><tr><td></td><td>Result</td><td>Latitude</td><td>Longitude</td></tr>');

      for(var i=0;i<response.results.length;i++){
        html.push('<tr><td>', (i+1), '.</td><td>', 
        response.results[i].address.freeformAddress, 
        '</td><td>', 
        response.results[i].position.lat,
        '</td><td>', 
        response.results[i].position.lon,
        '</td></tr>');
      }

      html.push('</table>');

      // Add the resulting HTML to the body of the page.
      document.body.innerHTML = html.join('');
    });

  </script>
</head>

<style>
  table {
    border: 1px solid black;
    border-collapse: collapse;
  }
  td, th {
    border: 1px solid black;
    padding: 5px;
  }
</style>

<body> </body>

</html>

الصورة التالية هي لقطة شاشة تعرض نتائج نموذج التعليمات البرمجية هذا، وجدول يحتوي على العنوان الذي تم البحث عنه، جنبا إلى جنب مع الإحداثيات الناتجة.

لقطة شاشة لجدول HTML يعرض العنوان الذي تم البحث فيه والإحداثيات الناتجة.

دعم Azure Government cloud

تدعم خرائط Azure Web SDK سحابة Microsoft Azure Government. تظل جميع عناوين URL ل JavaScript وCSS المستخدمة للوصول إلى خرائط Azure Web SDK كما هي، ولكن يجب القيام بالمهام التالية للاتصال بإصدار سحابة Azure Government من النظام الأساسي خرائط Azure.

عند استخدام عنصر التحكم بالخريطة التفاعلي، أضف الخط التالي من التعليمات البرمجية قبل إنشاء مثيل للفئة Map.

atlas.setDomain('atlas.azure.us');

تأكّد من استخدام تفاصيل مصادقة خرائط Azure من النظام الأساسي السحابي Microsoft Azure Government عند مصادقة الخريطة والخدمات.

يجب تعيين مجال الخدمات عند إنشاء مثيل لنقطة نهاية عنوان URL لواجهة برمجة التطبيقات. على سبيل المثال، تنشئ التعليمات البرمجية التالية مثيلاً للفئة SearchURL وتوجه المجال إلى سحابة Microsoft Azure Government.

var searchURL = new atlas.service.SearchURL(pipeline, 'atlas.azure.us');

في حالة كان الوصول مباشرة إلى خدمات REST الخاصة بخرائط Azure، فقم بتغيير مجال URL إلى atlas.azure.us. على سبيل المثال، في حالة كنت تستخدم خدمة واجهة برمجة تطبيقات البحث، فقم بتغيير مجال عنوان URL من https://atlas.microsoft.com/search/ إلى https://atlas.azure.us/search/.

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

تعرّف على المزيد حول الفئات والأساليب المُستخدمة في هذه المقالة:

للحصول على مزيد من نماذج التعليمات البرمجية التي تستخدم وحدة الخدمات، راجع هذه المقالات: