Leaflets - Find a method to add onEachFeature to an existing geojson layer

I am working with geojson data in a leaflet. In their guide at http://leafletjs.com/examples/geojson.html, they write that there are two ways to add geoionic data to a map:

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

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

"As an alternative, we could create an empty GeoJSON layer and assign it to a variable so that we can add additional functions to it later."

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

I am currently using the latter method (I create an empty layer and add data to it). What I'm doing right now is that I'm trying to add an onEachFeature function. Although I can not get it to work using the myLayer.addData method.

In my code, I use this.geoJson.addData(geoJson, { onEachFeature: onEachFeature }); . Where geoJson is the actual geoJson line, and "this.geoJson" is the empty geoJson layer that was created and added to the map. Although this does not work.

But if I create a new geoJson layer at the same time, I enter the geoJson data, it all works:

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

So I'm basically wondering how I should make the onEachFeature function work when adding data using the layer.addData function?

+6
source share
1 answer

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

addData will use the onEachFeature callback that you pass when creating the layer.

So this should work

 var myLayer = L.geoJson(false, { onEachFeature: onEachFeature }).addTo(this.map); myLayer.addData(geojsonFeature); 
+7
source

Source: https://habr.com/ru/post/974186/


All Articles