I'm trying to pass two functions as parameters, in order to customize a layer visualization for a Leaflet map. Apart from the specific case, which may not be relevant here as i'm asking for a more general concept, what i've done is:
Map.createLayer(function onEachFeature(feature, layer) {
var popupContent = "<p>I started out as a GeoJSON " +
feature.geometry.type + ", but now I'm a Leaflet vector!</p>";
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
},
function pointToLayer(feature, latlng) {
return L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
})
});
where the method "createLayer" of Map (which wraps a Leaflet Map) does:
public createLayer(popupContent:(feature, layer) => void, renderPoint:(feature,latlng) => L.CircleMarker): ICOLayer{
this.layer = L.geoJSON(this.datasource.get(), {
style: function(feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: popupContent,
pointToLayer: renderPoint
});
return this;
}
this doesn't work and i don't know why, but if i pass them as anonymous functions (thus ignoring the input parameters) everything works fine:
public createLayer(popupContent:(feature, layer) => void, renderPoint:(feature,latlng) => L.CircleMarker): ICOLayer{
this.layer = L.geoJSON(this.datasource.get(), {
style: function(feature) {
return feature.properties && feature.properties.style;
},
onEachFeature: function onEachFeature(feature, layer) {
var popupContent = "<p>I started out as a GeoJSON " +
feature.geometry.type + ", but now I'm a Leaflet vector!</p>";
if (feature.properties && feature.properties.popupContent) {
popupContent += feature.properties.popupContent;
}
layer.bindPopup(popupContent);
},
pointToLayer: function pointToLayer(feature, latlng) {
return L.circleMarker(latlng, {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
})
}
});
return this;
}
I've also tried removing the signature of the functions in input, passing them as mere variables, but it didn't work, I am not familiar with javascript/typescript, thus this might be a stupid error. Pardon me in advance.
EDIT: No error message is displayed while executing the first approach
It looks like you have really identical code in both cases. One problem I can imagine here - scope problem.
L.circleMarke
- (when having the code block in your first example) theL
variable is not defined. But moving code inside module wherecreateLayer
method is - you getL
reference, I assume, from imports.Second question would be, why you don't get an exception about undefined
L
. I can assume, somewhere in code, there is atry..catch
statement, which swallows the exception.Run your code in chrome with developer tools opened and with
pause on caught exceptions
option on.Also, you can put breakpoints inside functions for two cases, to ensure the functions are being called.