I have GeoJSON data that contains URLs. Not all of the features have url data. I have a pop up which shows the name and a link to the url. I’d like to be able to only show the link to URL when the feature URL is not null but will always show the name as a minimum. My code is below:
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);
Advertisement
Answer
Instead of using the bindPopup
method with a function, which finds out too late that the feature does not have a URL to show, in which case you actually want no popup, you can leverage the onEachFeature
option of the L.geoJSON
factory to attach a popup conditionally:
A
Function
that will be called once for each createdFeature
, 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);