javascript - 从 map 外部动态显示传单标记弹出窗口

标签 javascript arrays json leaflet maps

我正在使用Leaflet javascript 库来显示一些地震信息。您可以在 map 上看到几个红色圆圈。当您单击红色圆圈时,它将在弹出窗口中显示一些详细信息。

我想在您从 map 外部单击链接时显示弹出窗口。这( answer )很有用。但是,我想在没有ID的情况下实现它?我的意思是,如果我在 map 上有超过 30 个标记,而且我没有任何 ID,只有链接中的类名称。当我点击 map 外部的链接时,如何触发弹出窗口?

这个(answer)很好。在这个答案中,他们提到了标记 1、标记 2 和标记 3。但是,就我而言,我不知道会显示多少个标记。有时 5、50、100 或者可能超过 150。这就是我问这个问题的原因。

<html>
  <head>
<meta charset="utf-8" />
<title>Leaflet</title>
<link
  rel="stylesheet"
  href="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="335f5652555f564773021d061d02" rel="noreferrer noopener nofollow">[email protected]</a>/dist/leaflet.css"
  integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ=="
  crossorigin=""
/>
<script
  src="https://unpkg.com/<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="117d7470777d746551203f243f20" rel="noreferrer noopener nofollow">[email protected]</a>/dist/leaflet.js"
  integrity="sha512-GffPMF3RvMeYyc1LWMHtK8EbPv0iNZ8/oTtHPx9/cc2ILxQ+u905qIwdpULaqDkyBKgOaB57QTMg7ztg8Jm2Og=="
  crossorigin=""
></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
  </head>

  <body>
<div id="map" style="width: 400px; height: 400px;"></div>

<script>
  var object = {
    type: "FeatureCollection",
    metadata: {
      generated: 1564051101000,
      url:
        "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5",
      title: "USGS Earthquakes",
      status: 200,
      api: "1.8.1",
      count: 4
    },
    features: [
      {
        type: "Feature",
        properties: {
          mag: 5.2000000000000002,
          place: "79km ENE of L'Esperance Rock, New Zealand",
          time: 1563662132538,
          updated: 1563663302040,
          tz: -720,
          url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pu1",
          detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pu1&format=geojson",
          felt: null,
          cdi: null,
          mmi: null,
          alert: null,
          status: "reviewed",
          tsunami: 0,
          sig: 416,
          net: "us",
          code: "70004pu1",
          ids: ",us70004pu1,",
          sources: ",us,",
          types: ",geoserve,origin,phase-data,",
          nst: null,
          dmin: 1.9299999999999999,
          rms: 1.28,
          gap: 70,
          magType: "mww",
          type: "earthquake",
          title: "M 5.2 - 79km ENE of L'Esperance Rock, New Zealand"
        },
        geometry: { type: "Point", coordinates: [-178.1173, -31.174800000000001, 35] },
        id: "us70004pu1"
      },
      {
        type: "Feature",
        properties: {
          mag: 5.5999999999999996,
          place: "23km NNW of Kandrian, Papua New Guinea",
          time: 1563655424914,
          updated: 1563741959328,
          tz: 600,
          url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004psn",
          detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004psn&format=geojson",
          felt: 1,
          cdi: 4.2999999999999998,
          mmi: 4.4779999999999998,
          alert: "green",
          status: "reviewed",
          tsunami: 1,
          sig: 483,
          net: "us",
          code: "70004psn",
          ids: ",us70004psn,",
          sources: ",us,",
          types: ",dyfi,geoserve,losspager,moment-tensor,origin,phase-data,shakemap,",
          nst: null,
          dmin: 3.2029999999999998,
          rms: 0.89000000000000001,
          gap: 28,
          magType: "mww",
          type: "earthquake",
          title: "M 5.6 - 23km NNW of Kandrian, Papua New Guinea"
        },
        geometry: { type: "Point", coordinates: [149.5069, -6.0086000000000004, 59.789999999999999] },
        id: "us70004psn"
      },
      {
        type: "Feature",
        properties: {
          mag: 5.0999999999999996,
          place: "Easter Island region",
          time: 1563647034336,
          updated: 1563892918040,
          tz: -420,
          url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pra",
          detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pra&format=geojson",
          felt: null,
          cdi: null,
          mmi: null,
          alert: null,
          status: "reviewed",
          tsunami: 0,
          sig: 400,
          net: "us",
          code: "70004pra",
          ids: ",us70004pra,",
          sources: ",us,",
          types: ",geoserve,origin,phase-data,",
          nst: null,
          dmin: 2.7559999999999998,
          rms: 0.71999999999999997,
          gap: 118,
          magType: "mb",
          type: "earthquake",
          title: "M 5.1 - Easter Island region"
        },
        geometry: { type: "Point", coordinates: [-111.38379999999999, -29.3232, 10] },
        id: "us70004pra"
      },
      {
        type: "Feature",
        properties: {
          mag: 5.0999999999999996,
          place: "136km ESE of Pangai, Tonga",
          time: 1563635789233,
          updated: 1563636880040,
          tz: -720,
          url: "https://earthquake.usgs.gov/earthquakes/eventpage/us70004pp5",
          detail: "https://earthquake.usgs.gov/fdsnws/event/1/query?eventid=us70004pp5&format=geojson",
          felt: null,
          cdi: null,
          mmi: null,
          alert: null,
          status: "reviewed",
          tsunami: 0,
          sig: 400,
          net: "us",
          code: "70004pp5",
          ids: ",us70004pp5,",
          sources: ",us,",
          types: ",geoserve,origin,phase-data,",
          nst: null,
          dmin: 3.2749999999999999,
          rms: 1.3100000000000001,
          gap: 116,
          magType: "mww",
          type: "earthquake",
          title: "M 5.1 - 136km ESE of Pangai, Tonga"
        },
        geometry: { type: "Point", coordinates: [-173.15700000000001, -20.294899999999998, 10] },
        id: "us70004pp5"
      }
    ],
    bbox: [-178.1173, -31.1748, 10, 149.5069, -6.0086, 59.79]
  };

  var i = 0;

  document.writeln("<div>");
  for (i = 0; i < object.features.length; i++) {
    var timestamp = object.features[i].properties.time / 1000;
    date = new Date(timestamp * 1000);
    dateString = date.toUTCString();

    var today = date;
    today.setHours(today.getHours() + 4);

    // maps

    document.writeln("<div class='list'>");
    document.writeln("<div>" + object.features[i].properties.mag + " Mag</div>");
    document.writeln("</div>");
  }
  document.writeln("</div>");

  var map = L.map("map").setView([-31.174800000000001, -178.1173], 2);

  // load a tile layer
  L.tileLayer(
    "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}",
    {
      attribution:
        "Tiles &copy; Esri &mdash; Source: Esri, DeLorme, NAVTEQ, USGS, Intermap, iPC, NRCAN, Esri Japan, METI, Esri China (Hong Kong), Esri (Thailand), TomTom, 2012",
      maxZoom: 18
    }
  ).addTo(map);

  // load GeoJSON from an external file
  $.getJSON(
    "https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5",
    function(data) {
      var geojsonMarkerOptions = {
        opacity: 0.8,
        fillOpacity: 0.6
      };

      // color indication by magnitude
      geoLayer = L.geoJson(data, {
        // popup div content
        onEachFeature: function(feature, layer) {
          // variable1 = L.marker([-31.174800000000001,-178.1173]).bindPopup('The html content').addTo(map);

          var popupText =
            "<b>Magnitude:</b> " +
            feature.properties.mag +
            "<br><b>Location:</b> " +
            feature.properties.place;

          layer.bindPopup(popupText, {
            closeButton: true,
            offset: L.point(0, -20)
          });
          layer.on("click", function() {
            layer.openPopup();
          });
        },

        style: function(feature) {
          var mag = feature.properties.mag;
          if (mag >= 4.0) {
            return { color: "red" };
          } else if (mag >= 3.0) {
            return { color: "orange" };
          } else if (mag >= 2.0) {
            return { color: "yellow" };
          } else {
            return { color: "black" };
          }
        },

        // add GeoJSON layer to the map once the file is loaded
        pointToLayer: function(feature, latlng) {
          return L.circleMarker(latlng, geojsonMarkerOptions);
        }
      }).addTo(map);
    }
  );
</script>
  </body>
</html>

最佳答案

以下是使用 es6 的可能解决方案的示例:

例如创建一个 div 来保存要动态添加的 anchor 标记:

<div id="anchors"></div>

现在在js文件中:

  let markersArray = {}; // create the associative array
  let magsArray = {}; // here hold the ids that correspond to the mags


  // load GeoJSON from an external file
  $.getJSON("https://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2019-07-20&endtime=2019-07-21&minmagnitude=5", data => {

    // color indication by magnitude
    L.geoJson(data, {

      // add GeoJSON layer to the map once the file is loaded
      pointToLayer: function(feature, latlng) {
        const mag = feature.properties.mag;
        const geojsonMarkerOptions = {
          opacity: 0.8,
          fillOpacity: 0.6,
          // here define the style using ternary operators for circles
          color: mag >= 4.0 ? 'red' : mag >= 3.0 ? 'orange' : mag >= 2.0 ? 'yellow' : 'black'
        };

        // here store the circle markers in the array
        markersArray[feature.id] = L.circleMarker(latlng, geojsonMarkerOptions)
               .addTo(map)
               .bindPopup(
              `<b>Magnitude:</b> " ${feature.properties.mag} 
               <br><b>Location:</b>  ${feature.properties.place}`, {
          closeButton: true,
          offset: L.point(0, -20)
        });

        // here record the mags
        magsArray[feature.id] = feature.properties.mag;

        return L.circleMarker(latlng, geojsonMarkerOptions);
      },
    })

    // add dynamically anchor tags
    let markup = '';
    for (let i in markersArray) {
      markup += `<a href="#" onclick="markersArray['${i}'].openPopup()"><b>${magsArray[i]} Mag</b></a><br/>`;
    }
    document.getElementById('anchors').innerHTML = markup;
  });

最后但并非最不重要的一点是,我不明白使用 API 获取数据的原因,并且两者都将其作为文件中的常量变量。

Demo

关于javascript - 从 map 外部动态显示传单标记弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57286300/

相关文章:

javascript - 处理 null JSON 对象

javascript - 如何使用 ASP.NET 查找客户机时区

c - 如何将文件(C 语言)加载到全局定义的字符数组中?

php - 对字符串数组进行排序,就像中间字符串数字位于字符串末尾一样

javascript - 使用 Express 路由将 json 文件传递​​给客户端

php - 发送“(引号)用 JSON 在 cURL 上签名

javascript - Angular : Error trying to diff '[object Object]' . 只允许数组和迭代

javascript - 即使搜索完成后我也想保留我的输入字段数据

python - 根据条件替换 numpy 数组中的最小元素

java - 改造:根据响应进行 Json 解析器