0

My script is as follows:

function clickFeature(e, feature) {
  var layer = e.target;
  var string = new feature.properties.categorie;
  var bigIcon = new BigIcon({iconSize: [24, 40], iconUrl: +string+'.png'});
  layer.setIcon(layer.options.icon == smallIcon ? bigIcon : smallIcon);
}

var jsonLaag1 = L.geoJSON(geojson, {
  filter: categorie1,
  pointToLayer: function (feature, latlng) {
    return L.marker(latlng, {
      icon: smallIcon
    });
  },
  onEachFeature: onEachFeature,

});

function categorie1(feature) {
  if (feature.properties.categorie == '1') return true
}

function onEachFeature(feature, layer) {
  layer.on({
    'mouseover': clickFeature
  })
  layer.on({
    'mouseout': clickFeature
  })
}

It returns feature is undefined in the console Somewhere further in my script I just can filter with the value of categorie (category in dutch) with the same definition. What goes wrong?

1

The second parameter to your function clickFeature(e, feature) {...} function is always undefined. This happens because Leaflet event handler functions are expected to receive just one parameter (the event).

Do not expect computer code to automagically pass around the values that you need.

Internally, the leaflet code for L.Evented.fire() calls the handler function with just the given context (if set) and one argument via Function.prototype.call.

There are several approaches to a correct implementation.


One approach is to use a closure of the GeoJSON feature:

function onEachFeature(feature, layer) {
  layer.on('mouseover mouseout': function(ev) {
      clickFeature(ev, feature);
  });
}

And since this is the only appearance of a call to clickFeature, that should be refactored as well.


Another approach is to store the needed data in the leaflet layer, which the event handler can access:

function onEachFeature(feature, layer) {
  layer.featureCategory = feature.category;
  layer.on('mouseover mouseout', clickFeature)
}

function clickFeature(e, feature) {
  var layer = e.target;
  var category = layer.featureCategory;
  // etc
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.