Menggunakan modul layanan Azure Maps

Azure Maps Web SDK menyediakan modul layanan. Modul ini adalah pustaka pembantu yang memudahkan penggunaan layanan Azure Maps REST di web atau aplikasi Node.js menggunakan JavaScript atau TypeScript.

Catatan

Penghentian Modul Layanan Azure Peta Web SDK

Modul Layanan Azure Peta Web SDK sekarang tidak digunakan lagi dan akan dihentikan pada 30/9/26. Untuk menghindari gangguan layanan, sebaiknya migrasi ke Azure Peta JavaScript REST SDK sebesar 30/9/26. Untuk informasi selengkapnya, lihat Panduan Pengembang JavaScript/TypeScript REST SDK (pratinjau).

Menggunakan modul layanan di halaman web

  1. Buat file HTML baru.

  2. Muat modul layanan Azure Maps. Anda dapat memuatnya dengan salah satu dari dua cara:

    • Gunakan versi Azure Content Delivery Network yang di hosting secara global dari modul layanan Azure Maps. Tambah referensi skrip ke <head> elemen dari file:
    <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
    • Atau, Anda dapat memuat modul layanan untuk kode sumber Azure Maps Web SDK secara lokal menggunakan paket npm azure-maps-drawing-tools, lalu meng-hosting-nya dengan aplikasi Anda. Paket ini juga memasukkan definisi TypeScript. Gunakan perintah ini:

      npm install azure-maps-rest

      Kemudian, gunakan deklarasi impor untuk menambahkan modul ke dalam file sumber:

      import * as service from "azure-maps-rest";
      
  3. Buat kebijakan autentikasi. Alur harus dibuat sebelum Anda dapat menginisialisasi titik akhir klien URL layanan. Gunakan kunci akun Azure Peta Anda sendiri atau kredensial Microsoft Entra untuk mengautentikasi klien Azure Peta layanan Pencarian. Dalam contoh ini, klien URL layanan Pencarian dibuat.

    Jika Anda menggunakan kunci langganan untuk autentikasi:

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

    Jika Anda menggunakan ID Microsoft Entra untuk autentikasi:

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

    Untuk informasi selengkapnya, lihat Autentikasi dengan Azure Maps.

  4. Kode berikut menggunakan klien URL layanan Azure Maps Search yang baru dibuat untuk membuat kode geografis alamat: "1 Microsoft Way, Redmond, WA". Kode itu menggunakan fungsi searchAddress dan menampilkan hasil sebagai tabel dalam isi halaman.

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

Berikut adalah sampel kode lengkap yang berjalan:

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

Gambar berikut adalah cuplikan layar yang menunjukkan hasil kode sampel ini, tabel dengan alamat yang dicari, bersama dengan koordinat yang dihasilkan.

Cuplikan layar tabel HTML memperlihatkan alamat yang dicari dan koordinat yang dihasilkan.

Dukungan cloud Azure Government

Azure Maps Web SDK mendukung cloud Azure Government. Semua URL JavaScript dan CSS yang digunakan untuk mengakses Azure Peta Web SDK tetap sama, namun tugas berikut perlu dilakukan untuk menyambungkan ke versi cloud Azure Government dari platform Azure Peta.

Saat menggunakan kontrol peta interaktif, tambah baris kode berikut sebelum membuat instans kelas Map.

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

Pastikan untuk menggunakan detail autentikasi Azure Maps dari platform cloud Azure Government saat mengautentikasi peta dan layanan.

Domain untuk layanan perlu diatur saat membuat instans titik akhir URL API. Misalnya, kode berikut membuat instans kelas SearchURL dan mengarahkan domain ke cloud Azure Government.

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

Jika langsung mengakses layanan Azure Maps REST, ubah domain URL menjadi atlas.azure.us. Misalnya, jika menggunakan layanan API pencarian, ubah domain URL dari https://atlas.microsoft.com/search/ menjadi https://atlas.azure.us/search/.

Langkah berikutnya

Pelajari selengkapnya tentang kelas dan metode yang digunakan di artikel ini:

Untuk sampel kode lainnya yang menggunakan modul layanan, lihat artikel berikut ini: