简体   繁体   English

Mapbox Leaflet 向 GeoJson 添加弹出窗口

[英]Mapbox Leaflet Add Popup to GeoJson

I've setup a leaflet map with a mapbox style, which is loading an external GeoJson.我已经设置了一个带有地图框样式的传单地图,它正在加载外部 GeoJson。 That works fine, except it doesn't import any styling parameters from the GeoJson such as the marker-color.这工作正常,除了它不会从 GeoJson 导入任何样式参数,例如标记颜色。 Like fe :像 fe :

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

Is shown in the default blue'ish marker-color after import.导入后以默认的蓝色标记颜色显示。 So that's the first issue.所以这是第一个问题。 And I guess my second (and more important) issue is connected with this.我想我的第二个(也是更重要的)问题与此有关。 I'd like to add an infobox-popup for each marker based on the geoJson.我想根据 geoJson 为每个标记添加一个信息框弹出窗口。 Is that possible and how?这是可能的吗?

Thanks for advice in advance!提前感谢您的建议!

My webcode:我的网络代码:

<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>

The GeoJson 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
    ]
  }    }  ]}

You can use L.geoJSON 's pointToLayer & onEachFeature respectively to achieve the desired behavior by passing the color as an argument to return the desired marker icon and again by conditionally checking the geojson feature properties to generate the marker popup.您可以分别使用L.geoJSONpointToLayeronEachFeature来实现所需的行为,方法是将颜色作为参数传递以返回所需的标记图标,并再次通过有条件地检查 geojson 功能属性来生成标记弹出窗口。 Below you can find a demo to illustrate the above mentioned by simulating a fake async call to retrieve the geojson as in your case.您可以在下面找到一个演示,通过模拟假异步调用来检索 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM