Mendapatkan informasi dari koordinat

Artikel ini memperlihatkan cara membuat pencarian alamat terbalik yang memperlihatkan alamat lokasi popup yang dipilih.

Ada dua cara untuk melakukan penelusuran alamat terbalik. Salah satu caranya adalah dengan mengkueri API Pencarian Alamat Terbalik melalui TypeScript REST SDK @azure-rest/maps-search. Cara lain adalah dengan menggunakan Fetch API untuk membuat permintaan ke API Pencarian Alamat Terbalik untuk menemukan alamat. Kedua pendekatan dijelaskan dalam artikel ini.

Membuat permintaan pencarian terbalik melalui REST SDK

import * as atlas from "azure-maps-control";
import MapsSearch from "@azure-rest/maps-search";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", async () => {
    // Use the access token from the map and create an object that implements the TokenCredential interface.
    const credential = {
      getToken: () => {
        return {
          token: map.authentication.getToken()
        };
      }
    };

    // Create a Search client.
    const client = MapsSearch(credential, "<Your Azure Maps Client Id>");

    // Update the style of mouse cursor to a pointer
    map.getCanvasContainer().style.cursor = "pointer";

    // Create a popup
    const popup = new atlas.Popup();

    // Upon a mouse click, open a popup at the selected location and render in the popup the address of the selected location
    map.events.add("click", async (e) => {
      const position = [e.position[1], e.position[0]];

      // Execute the reverse address search query and open a popup once a response is received
      const response = await client.path("/search/address/reverse/{format}", "json").get({
        queryParameters: { query: position }
      });

      // Get address data from response
      const data = response.body.addresses;

      // Construct the popup
      var popupContent = document.createElement("div");
      popupContent.classList.add("popup-content");
      popupContent.innerHTML = data.length !== 0 ? data[0].address.freeformAddress : "No address for that location!";
      popup.setOptions({
        position: e.position,
        content: popupContent
      });

      // Render the popup on the map
      popup.open(map);
    });
  });
};

document.body.onload = onload;

Dalam contoh kode sebelumnya, blok pertama membuat objek peta dan mengatur mekanisme autentikasi untuk menggunakan ID Microsoft Entra. Untuk informasi selengkapnya, lihat Membuat peta.

Blok kode kedua membuat objek yang mengimplementasikan antarmuka TokenCredential untuk mengautentikasi permintaan HTTP ke Azure Peta dengan token akses. Kemudian meneruskan objek kredensial ke Peta Search dan membuat instans klien.

Blok kode ketiga memperbarui gaya kursor mouse ke pointer dan membuat objek popup. Untuk informasi selengkapnya, lihat Menambahkan popup di peta.

Blok kode keempat menambahkan pendengar peristiwa klik mouse. Saat dipicu, kueri pencarian akan dibuat dengan koordinat titik yang dipilih. Kemudian membuat permintaan GET untuk mengkueri Get Search Address Reverse API untuk alamat koordinat.

Blok kode kelima menyiapkan konten popup HTML untuk menampilkan alamat respons untuk posisi koordinat yang dipilih.

Perubahan kursor, objek popup, dan click peristiwa semuanya dibuat di pendengar peristiwa beban peta. Struktur kode ini memastikan peta dimuat sepenuhnya sebelum mengambil informasi koordinat.

Membuat permintaan penelusuran terbalik melalui Fetch API

Pilih lokasi di peta untuk membuat permintaan geocode terbalik untuk lokasi tersebut menggunakan ambil.

import * as atlas from "azure-maps-control";
import "azure-maps-control/dist/atlas.min.css";

const onload = () => {
  // Initialize a map instance.
  const map = new atlas.Map("map", {
    view: "Auto",
    // Add authentication details for connecting to Azure Maps.
    authOptions: {
      // Use Azure Active Directory authentication.
      authType: "aad",
      clientId: "<Your Azure Maps Client Id>",
      aadAppId: "<Your Azure Active Directory Client Id>",
      aadTenant: "<Your Azure Active Directory Tenant Id>"
    }
  });

  map.events.add("load", async () => {
    // Update the style of mouse cursor to a pointer
    map.getCanvasContainer().style.cursor = "pointer";

    // Create a popup
    const popup = new atlas.Popup();

    // Upon a mouse click, open a popup at the selected location and render in the popup the address of the selected location
    map.events.add("click", async (e) => {
      //Send a request to Azure Maps reverse address search API
      let url = "https://atlas.microsoft.com/search/address/reverse/json?";
      url += "&api-version=1.0";
      url += "&query=" + e.position[1] + "," + e.position[0];

      // Process request
      fetch(url, {
        headers: {
          Authorization: "Bearer " + map.authentication.getToken(),
          "x-ms-client-id": "<Your Azure Maps Client Id>"
        }
      })
        .then((response) => response.json())
        .then((response) => {
          const popupContent = document.createElement("div");
          popupContent.classList.add("popup-content");
          const address = response["addresses"];
          popupContent.innerHTML =
            address.length !== 0 ? address[0]["address"]["freeformAddress"] : "No address for that location!";
          popup.setOptions({
            position: e.position,
            content: popupContent
          });
          // render the popup on the map
          popup.open(map);
        });
    });
  });
};

document.body.onload = onload;

Dalam contoh kode sebelumnya, blok kode pertama membuat objek peta dan mengatur mekanisme autentikasi untuk menggunakan ID Microsoft Entra. Anda dapat melihat Membuat peta untuk instruksi.

Blok kode kedua memperbarui gaya kursor mouse ke pointer. Hal ini menginstansiasi objek popup. Untuk informasi selengkapnya, lihat Menambahkan popup di peta.

Blok kode ketiga menambahkan pendengar peristiwa untuk klik mouse. Setelah klik mouse, ia menggunakan Fetch API untuk mengkueri Azure Peta Reverse Address Search API untuk alamat koordinat yang dipilih. Untuk respons yang berhasil, ia mengumpulkan alamat untuk lokasi yang dipilih. Langkah ini menentukan konten dan posisi popup menggunakan fungsi setOptions dari kelas popup.

Perubahan kursor, objek popup, dan click peristiwa semuanya dibuat di pendengar peristiwa beban peta. Struktur kode ini memastikan peta dimuat sepenuhnya sebelum mengambil informasi koordinat.

Gambar berikut adalah cuplikan layar yang menunjukkan hasil dari dua sampel kode.

A screenshot of a map showing reverse address search results in a popup.

Langkah berikutnya

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

Lihat artikel berikut untuk contoh kode lengkap: