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:
JavaScript
x
43
43
1
const tackleshop_point = {
2
"type": "FeatureCollection",
3
"name": "tackleshop",
4
"crs": {
5
"type": "name",
6
"properties": {
7
"name": "urn:ogc:def:crs:OGC:1.3:CRS84"
8
}
9
},
10
"features": [{
11
"type": "Feature",
12
"properties": {
13
"gid": 1,
14
"name": "test 1",
15
"url": "www.google.com"
16
},
17
"geometry": {
18
"type": "Point",
19
"coordinates": [-2.284362363619518, 50.983444094390933]
20
}
21
},
22
{
23
"type": "Feature",
24
"properties": {
25
"gid": 7,
26
"name": "test 2",
27
"url": null
28
},
29
"geometry": {
30
"type": "Point",
31
"coordinates": [-2.283893608524902, 50.981411456895998]
32
}
33
}
34
]
35
}
36
37
const tackleshop = L.geoJSON(tackleshop_point, {}).bindPopup(function(layer) {
38
let cap_name = layer.feature.properties.name.replace(/(^w{1})|(s+w{1})/g, letter => letter.toUpperCase());
39
return `<p>${cap_name}</p><a href="http://${layer.feature.properties.url}" target="_blank">View<a>`
40
/******/
41
;
42
}).addTo(map);
43
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.
JavaScript
1
9
1
const tackleshop = L.geoJSON(tackleshop_point, {
2
onEachFeature(feature, layer) {
3
const url = feature.properties.url;
4
if (url) { // Attach the popup only when the url is specified
5
layer.bindPopup(`<a href="http://${url}">View<a>`);
6
}
7
}
8
}).addTo(map);
9