Condividi tramite


Usare il modulo dei servizi di Mappe di Azure

Azure Maps Web SDK offre un modulo di servizi. Questo modulo è una libreria helper che semplifica l'uso dei servizi REST di Mappe di Azure nelle applicazioni Web o Node.js usando JavaScript o TypeScript.

Annotazioni

Ritiro del modulo del servizio Web SDK di Mappe di Azure

Il modulo del servizio Web SDK di Mappe di Azure è ora deprecato e verrà ritirato il 30/9/26. Per evitare interruzioni del servizio, è consigliabile eseguire la migrazione all'SDK REST JavaScript di Mappe di Azure entro il 30/9/26. Per altre informazioni, vedere Guida per gli sviluppatori dell'SDK REST JavaScript/TypeScript (anteprima).

Usare il modulo servizi in una pagina Web

  1. Creare un nuovo file HTML.

  2. Caricare il modulo dei servizi di Mappe di Azure. È possibile caricarla in uno dei due modi seguenti:

    • Usare la versione della rete per la distribuzione di contenuti di Azure, ospitata a livello globale, del modulo dei servizi Mappe di Azure. Aggiungere un riferimento allo script all'elemento <head> del file:
    <script src="https://atlas.microsoft.com/sdk/javascript/service/2/atlas-service.min.js"></script>
    
    • In alternativa, caricare il modulo dei servizi per il codice sorgente dell'SDK Web di Mappe di Azure in locale usando il pacchetto npm azure-maps-rest e quindi ospitarlo con l'app. Questo pacchetto include anche le definizioni TypeScript. Usare questo comando:

      npm install azure-maps-rest

      Usare quindi una dichiarazione di importazione per aggiungere il modulo in un file di origine:

      import * as service from "azure-maps-rest";
      
  3. Creare una pipeline di autenticazione. La pipeline deve essere creata prima di poter inizializzare un endpoint client dell'URL del servizio. Usare la propria chiave dell'account di Mappe di Azure o le credenziali di Microsoft Entra per autenticare un client del servizio di ricerca di Mappe di Azure. In questo esempio viene creato il client URL del servizio di ricerca.

    Se si usa una chiave di sottoscrizione per l'autenticazione:

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

    Se si usa Microsoft Entra ID per l'autenticazione:

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

    Per altre informazioni, vedere Autenticazione con Mappe di Azure.

  4. Il codice seguente usa il client URL del servizio di ricerca di Mappe di Azure appena creato per geocodificare un indirizzo: "1 Microsoft Way, Redmond, WA". Il codice usa la searchAddress funzione e visualizza i risultati come tabella nel corpo della pagina.

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

Di seguito è riportato l'esempio di codice completo ed in esecuzione:

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

L'immagine seguente è uno screenshot che mostra i risultati di questo codice di esempio, una tabella con l'indirizzo cercato, insieme alle coordinate risultanti.

Screenshot di una tabella HTML che mostra l'indirizzo cercato e le coordinate risultanti.

Supporto del cloud di Azure per enti pubblici

L'SDK per Web di Mappe di Azure supporta il cloud di Azure per enti pubblici. Tutti gli URL JavaScript e CSS usati per accedere ad Azure Maps Web SDK rimangono invariati, ma è necessario eseguire le attività seguenti per connettersi alla versione cloud di Azure per enti pubblici della piattaforma Mappe di Azure.

Quando si usa il controllo di mappa interattivo, aggiungere la seguente riga di codice prima di creare un'istanza della classe Map.

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

Assicurarsi di utilizzare i dettagli di autenticazione di Azure Maps dalla piattaforma cloud di Azure Government quando si autenticano la mappa e i servizi.

Il dominio per i servizi deve essere impostato durante la creazione di un'istanza di un endpoint URL API. Ad esempio, il codice seguente crea un'istanza della SearchURL classe e punta il dominio al cloud di Azure per enti pubblici.

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

Se si accede direttamente ai servizi REST di Mappe di Azure, modificare il dominio URL in atlas.azure.us. Ad esempio, se si usa il servizio API di ricerca, modificare il dominio URL da https://atlas.microsoft.com/search/ a https://atlas.azure.us/search/.

Passaggi successivi

Per altre informazioni sulle classi e sui metodi usati in questo articolo, vedere:

Per altri esempi di codice che usano il modulo services, vedere gli articoli seguenti: