获取传单弹出仅在功能属性不为空时显示

Get Leaflet pop up to only show when feature properties are not null

我有包含 URLs 的 GeoJSON 数据。并非所有功能都有 url 数据。我有一个弹出窗口,显示名称和 link 到 url。当特征 URL 不为空时,我希望能够仅显示 link 到 URL,但始终至少显示名称。我的代码如下:

    const tackleshop_point = {
  "type": "FeatureCollection",
  "name": "tackleshop",
  "crs": {
    "type": "name",
    "properties": {
      "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
    }
  },
  "features": [{
      "type": "Feature",
      "properties": {
        "gid": 1,
        "name": "test 1",
        "url": "www.google.com"
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-2.284362363619518, 50.983444094390933]
      }
    },
    {
      "type": "Feature",
      "properties": {
        "gid": 7,
        "name": "test 2",
        "url": null
      },
      "geometry": {
        "type": "Point",
        "coordinates": [-2.283893608524902, 50.981411456895998]
      }
    }
  ]
}

const tackleshop = L.geoJSON(tackleshop_point, {}).bindPopup(function(layer) {
  let cap_name = layer.feature.properties.name.replace(/(^\w{1})|(\s+\w{1})/g, letter => letter.toUpperCase());
  return `<p>${cap_name}</p><a href="http://${layer.feature.properties.url}" target="_blank">View<a>`
  /******/
  ;
}).addTo(map);

与其将 bindPopup 方法与函数一起使用,否则发现该功能没有要显示的 URL 为时已晚,在这种情况下您实际上不希望弹出窗口,您可以利用 L.geoJSON 工厂的 onEachFeature option 有条件地附加弹出窗口:

A Function that will be called once for each created Feature, after it has been created and styled. Useful for attaching events and popups to features.

const tackleshop = L.geoJSON(tackleshop_point, {
  onEachFeature(feature, layer) {
    const url = feature.properties.url;
    if (url) { // Attach the popup only when the url is specified
      layer.bindPopup(`<a href="http://${url}">View<a>`);
    }
  }
}).addTo(map);