javascript - Mapbox Leaflet 将弹出窗口添加到 GeoJson

标签 javascript jquery json leaflet geojson

我已经设置了一个带有mapbox样式的传单 map ,它正在加载外部GeoJson。这工作得很好,只是它不从 GeoJson 导入任何样式参数,例如标记颜色。就像 f.e. :

   "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",

导入后以默认的蓝色标记颜色显示。 这是第一个问题。我想我的第二个问题(也是更重要的)与此有关。我想基于 geoJson 为每个标记添加一个信息框弹出窗口。这可能吗?如何实现?

感谢您提前提供建议!

我的网页代码:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/leaflet@1.0.3/dist/leaflet.js"></script>
<script>
// Add AJAX request for data
    var counties = $.ajax({
      url:"https://myurl.net/wp-content/uploads/2020/02/geojson-example2.geojson",
      dataType: "json",
      success: console.log("County data successfully loaded."),
      error: function (xhr) {
        alert(xhr.statusText)
      }
    })
    // Specify that this code should run once the county data request is complete
    $.when(counties).done(function() {
        var map = L.map('map')
            .setView([51.1656914, 10.4515257], 5);
            var basemap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
            attribution: 'Map data © <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses            /by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
            maxZoom: 18,
            id: 'mapbox/dark-v10',
            accessToken: 'mytoken'}).addTo(map);
        // Add requested external GeoJSON to map
        var kyCounties = L.geoJSON(counties.responseJSON).addTo(map);
    });
</script>

GeoJson

{  "type": "FeatureCollection",  "features": [
{
  "type": "Feature",
  "properties": {
    "marker-color": "#4de21b",
    "marker-size": "medium",
    "marker-symbol": "",
    "icon":"purpleIcon"
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      10.52490234375,
      51.631657349449995
    ]
  }
},
{
  "type": "Feature",
  "properties": {
    "marker-color": "#af2ecf",
    "marker-size": "medium",
    "marker-symbol": ""
  },
  "geometry": {
    "type": "Point",
    "coordinates": [
      9.47021484375,
      52.17393169256849
    ]
  }    }  ]}

最佳答案

您可以分别使用L.geoJSONpointToLayeronEachFeature通过将颜色作为返回参数传递来实现所需的行为所需的标记图标,并再次通过有条件地检查 geojson 要素属性来生成标记弹出窗口。 您可以在下面找到一个演示,通过模拟假异步调用来检索 geojson(如您的情况所示)来说明上述内容。

<!DOCTYPE html>
<html>

<head>
  <title>Quick Start - Leaflet</title>

  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/>
    <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script>

</head>

<body>
  <div id="mapid" style="height: 100vh;"></div>
  <script>
    var map = L.map("mapid").setView([51.1656914, 10.4515257], 7);

    L.tileLayer(
      "https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw", {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
          '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
          'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: "mapbox/streets-v11",
        tileSize: 512,
        zoomOffset: -1
      }
    ).addTo(map);

    const geojson = {
      type: "FeatureCollection",
      features: [{
          type: "Feature",
          properties: {
            "marker-color": "#4de21b",
            "marker-size": "medium",
            "marker-symbol": "",
            icon: "purpleIcon"
          },
          geometry: {
            type: "Point",
            coordinates: [10.52490234375, 51.631657349449995]
          }
        },
        {
          type: "Feature",
          properties: {
            "marker-color": "#af2ecf",
            "marker-size": "medium",
            "marker-symbol": ""
          },
          geometry: {
            type: "Point",
            coordinates: [9.47021484375, 52.17393169256849]
          }
        }
      ]
    };

    const simulateAsyncCall = () => {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(geojson);
        }, 1000);
      });
    };

    function onEachFeature(feature, layer) {
      const popupContent = `I have marker color <b>${
          feature.properties["marker-color"]
        }</b>, and marker size <b>${feature.properties["marker-size"]}</b>`;

      if (feature.properties && feature.properties.popupContent) {
        popupContent += feature.properties.popupContent;
      }

      layer.bindPopup(popupContent);
    }

    const icon = color =>
      new L.Icon({
        iconUrl: `https://cdn.rawgit.com/pointhi/leaflet-color-markers/master/img/marker-icon-2x-${
            color === "#af2ecf" ? "violet" : "green"
          }.png`,
        shadowUrl: "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/images/marker-shadow.png",
        iconSize: [25, 41],
        iconAnchor: [12, 41],
        popupAnchor: [1, -34],
        shadowSize: [41, 41]
      });

    simulateAsyncCall().then(geojson => {
      console.log(geojson);
      L.geoJSON(geojson, {
        pointToLayer: function(feature, latlng) {
          const color = feature.properties["marker-color"];
          return L.marker(latlng, {
            icon: icon(color)
          });
        },
        onEachFeature
      }).addTo(map);
    });
  </script>
</body>

</html>

关于javascript - Mapbox Leaflet 将弹出窗口添加到 GeoJson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60238920/

相关文章:

java - 使用 Java 抓取 JSON 内容

c++ - 使用 C++ 每秒追加到磁盘上 JSON 文件中的 JSON 数组

javascript - 选中复选框时隐藏表格行

javascript - 向左滚动div不起作用可滚动菜单 fiddle jquery

jquery - 如何向 slider 添加填充?

php - 为什么 jQuery 不提交此表单? (或者我做错了什么?:-p)

javascript - ajax 响应显示为零

javascript - Jquery/Javascript 应用单击 * 但不单击特定元素及其子元素

javascript - 如何默认将 NativeScript 设置为 RTL 布局

json - 在 Flutter 的 Ferry Graphql 中序列化标量 JSON 以实现灵活的查询