Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

leaflet - Looking for method of adding onEachFeature to existing geojson layer

I'm working with geojson data in leaflet. In their guide at http://leafletjs.com/examples/geojson.html they write that there are two ways of adding geojson data to the map:

"GeoJSON objects are added to the map through a GeoJSON layer. To create it and add it to a map, we can use the following code:"

L.geoJson(geojsonFeature).addTo(map);

"Alternatively, we could create an empty GeoJSON layer and assign it to a variable so that we can add more features to it later."

var myLayer = L.geoJson().addTo(map);
myLayer.addData(geojsonFeature);

I am currently using the last method (I'm creating an empty layer and adds data to that). What I am doing right now is that I'm trying to add an onEachFeature function. Though I'm not getting it to work when using the myLayer.addData way of doing it.

In my code I'm using this.geoJson.addData(geoJson, { onEachFeature: onEachFeature });. Where geoJson is the actual geoJson string and "this.geoJson" is the empty geoJson layer that's been created and added to the map. Though this is not working.

But if I create a new geoJson layer at the same time I'm entering the geoJson data it all works:

L.geoJson(geoJson, {
    onEachFeature: onEachFeature
}).addTo(this.map);

So what I'm mainly wondering is how I should do to make the onEachFeature function work when adding the data with the layer.addData function?

like image 314
jimutt Avatar asked Aug 21 '14 21:08

jimutt


1 Answers

According to the source code , addData only takes 1 arg: geojson.

addData will use the callback onEachFeature you pass when you create the layer.

So this should work

var myLayer = L.geoJson(false, {
    onEachFeature: onEachFeature
}).addTo(this.map);

myLayer.addData(geojsonFeature);
like image 137
YaFred Avatar answered Nov 14 '22 01:11

YaFred