0
votes

I'm using L.geoJson and adding layer to my map, then with items.on('click', function (event) {}) displaying info of selected object which is stored in event.layer (getting info with toGeoJSON()).

Problem is, when there are some of the items, everything seems to work, but now when there are >1000 polygons, some of the data when using on('click') does not contain my info of the feature inside event.layer.

What could be a problem?

ADDITIONAL INFO:

Our GeoJSON looks something like this, it has additional data like ID and various properties.

{
"type": "FeatureCollection",
"features": [
  {
    "type": "Feature",
    "id": 1,
    "geometry": {"type": "Point", "coordinates": [102.0, 0.5]},
    "properties": {"prop1": "value1"}
  },
  {
    "type": "Feature",
    "id": 2,
    "geometry": {"type": "Point", "coordinates": [142.0, 15.5]},
    "properties": {"prop1": "value2"}
  }
 ]
 }

I put everything on a map:

data = L.geoJson(data);
allItems.clearLayers().addLayer(data);

Features are displayed on a map.

Then I listen for clicks on the features on the map:

allItems.on('click', function (event) {
    // On many of the features this is empty,
    // on some data can be retrieved.
    // On some that doesn't have ID, properties
    // are empty too
    console.log(event.layer.toGeoJSON().id);
});

GeoJSON has been checked and ID and properties ARE THERE.

1
Could you post the code you're using? Preferably a small testcase on Plunker/JSFiddle. Very hard to be of any help without any codeiH8
Added code example on how I do everything. Unfortunately, I can't share data as it's private.Julius

1 Answers

0
votes

Here's a little explanation about how to handle click events on L.GeoJSON layer and/or it's features. I've commented the code to explain what is going on and added an example on Plunker for you so you can test the concept.

Example on Plunker: http://plnkr.co/edit/TcyDGH?p=preview

Code:

var geoJsonLayer = L.geoJson(data, {
  // Executes on each feature in the dataset
  onEachFeature: function (featureData, featureLayer) {
    // featureData contains the actual feature object
    // featureLayer contains the indivual layer instance
    featureLayer.on('click', function () {
      // Fires on click of single feature
      console.log('Clicked feature layer ID: ' + featureData.id);
    });
  }
}).on('click', function () {
    // Fires on each feature in the layer
    console.log('Clicked GeoJSON layer');
});

As for your code, i'm quite confused as to where the allItems comes from. A layerGroup or something like that? Trying to capture clicks on individual features in the GeoJSON layer on that object won't work, because it won't be able to differentiate between the features. Same goes for the handler on the GeoJSON layer, it will fire, but won't know which feature you clicked. The handler in the onEachFeature function will. But i'm assuming you understand by now if your understanding the code/example above.