Bagikan melalui


Mendapatkan informasi dari koordinat

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

Ada dua cara untuk melakukan pencarian alamat secara terbalik. Salah satu caranya adalah dengan mengkueri REverse Address Search API 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 Maps dengan token akses. Kemudian meneruskan objek kredensial ke MapsSearch dan membuat instans klien.

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

Blok keempat kode 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 sepenuhnya dimuat sebelum mengambil informasi koordinat.

Membuat permintaan pencarian terbalik melalui Fetch API

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

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 penunjuk. Ini membuat instans 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 API Pencarian Alamat Terbalik Azure Maps untuk alamat koordinat yang dipilih. Untuk respons yang berhasil, ia mengumpulkan alamat untuk lokasi yang dipilih. Ini mendefinisikan konten popup dan posisi 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 sepenuhnya dimuat sebelum mengambil informasi koordinat.

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

Cuplikan layar peta yang memperlihatkan hasil pencarian alamat terbalik dalam popup.

Langkah selanjutnya

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

Lihat artikel berikut untuk contoh kode lengkap: