Selecionar e realçar

O padrão que a maioria dos portais quer: uma lista na página, um mapa ao lado, cada um controlando o outro. Passe o mouse sobre uma linha para realçar a cidade (nada é selecionado, nenhum pop-up abre); clique em uma linha para selecioná-la e voar até lá; clique em uma cidade no mapa e a página descobre qual foi.

Abrir este exemplo separadamente

O que observar

  • selectByKey com field recebe os seus identificadores: o mapa encontra as feições.
  • O field precisa ser uma coluna que o mapa publicado contém. Um mapa publicado tem apenas as colunas que usa, então o autor adiciona uma coluna de chave aos Campos da dica de ferramenta da camada; aqui, city_id.
  • highlight é um destaque temporário, sem a semântica de seleção, feito para o hover em listas. Até 500 chaves.
  • featureClick retorna apenas os campos da dica de ferramenta da camada (o que o leitor já pode ver), mais um featureKey estável.

O código

A página completa. Troque pelo seu próprio ID de publicação e peça ao autor do mapa que adicione seu site às origens permitidas dele.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Select and highlight - Icon Map Embed API</title>
  <link rel="stylesheet" href="https://www.icon-map.com/embed-examples/examples.css"> <!-- demo styling only -->
</head>
<body>
  <div class="ex-main">
    <div class="ex-side">
      <h2>The 15 largest cities</h2>
      <ul class="ex-list" id="list"></ul>
      <h2>Last click on the map</h2>
      <pre class="ex-readout" id="clicked">Click any city.</pre>
    </div>
    <div id="map"></div>
  </div>

  <script src="https://www.icon-map.com/js/iconmap-embed/2/iconmap-embed.umd.min.js"></script>
  <script>
    // This list is the page's OWN data - in a real portal it comes from your system.
    // `city_id` is the key it shares with the map's data. A published map carries only the columns
    // it uses, so the author put city_id in the layer's tooltip fields - that is what publishes it.
    const cities = [
      ["Tokyo, Japan", 35.7], ["New York, United States", 19.0], ["Mexico City, Mexico", 19.0],
      ["Mumbai, India", 19.0], ["São Paulo, Brazil", 18.8], ["Delhi, India", 15.9],
      ["Shanghai, China", 15.0], ["Kolkata, India", 14.8], ["Dhaka, Bangladesh", 12.8],
      ["Buenos Aires, Argentina", 12.8], ["Los Angeles, United States", 12.5], ["Karachi, Pakistan", 12.1],
      ["Cairo, Egypt", 11.9], ["Rio de Janeiro, Brazil", 11.8], ["Ōsaka, Japan", 11.3],
    ];

    const el = document.getElementById("map");
    const map = IconMapEmbed.embed(el, {
      publishId: "pub_...",
      // The map is a globe: let this page's own background show in the space around it.
      background: "transparent",
      chrome: { legend: false, layerControl: false, bookmarksBar: false, tourTransport: false },
      visibility: { visuals: { "chart-continent": false, "slicer-continent": false, "slicer-size": false, "slicer-capital": false } },
      events: ["featureClick"],
    });
    map.ready.catch((error) => console.error(error.code, error.message));

    const list = document.getElementById("list");
    for (const [id, millions] of cities) {
      const row = document.createElement("li");
      row.dataset.id = id;
      row.innerHTML = `<span>${id.split(",")[0]}</span><span>${millions.toFixed(1)}M</span>`;

      // Hover: emphasise on the map WITHOUT selecting - no popup, no event, nothing else follows.
      row.onmouseenter = () => map.highlight({ layerId: "cities", field: "city_id", keys: [id] });
      row.onmouseleave = () => map.clearHighlight();

      // Click: select by YOUR key and frame it. With `field`, the map finds the features for you.
      row.onclick = () => {
        mark(id);
        map.selectByKey({ layerId: "cities", field: "city_id", keys: [id], zoomTo: true });
      };
      list.append(row);
    }

    // The other direction: a click on the map tells the page which city it was.
    // `fields` holds the layer's tooltip fields - what the reader can already see.
    map.on("featureClick", (feature) => {
      if (!feature || feature.layerId !== "cities") return;
      const { city, country, population } = feature.fields;
      document.getElementById("clicked").textContent =
        `${city}, ${country}\n${Number(population).toLocaleString()} people\nfeatureKey: ${feature.featureKey}`;
      mark(`${city}, ${country}`);
    });

    function mark(id) {
      for (const row of list.children) row.classList.toggle("on", row.dataset.id === id);
    }
  </script>
</body>
</html>

Saiba mais