Warm tip: This article is reproduced from stackoverflow.com, please click
javascript leaflet

Leaflet TypeError while fetching feature property

发布于 2020-04-11 22:38:08

What I am trying to do is to pass specific feature's id to HTML input element on click on that feature.

So far I have this:

  function onFeature(feature, layer) {
    layer.on({
      click: document.getElementById('id_address').value = parseInt(feature.properties.pk)
    });
  }

$.ajax({
    type:"GET",
    url: "../geojson",
    dataType: 'json',
    success: function(response){
      layer = L.geoJson(response, {
        style: function(feature){
          return {color: "#2c65c1", fillColor: "4774bc", weight: 2};
        },
        onEachFeature: onFeature
      }).addTo(map);
    }
  });

But when I click on a feature on the map I got following error in console: TypeError: i[n].action.call is not a function Can anyone explain what is going on here?

Parsing works fine, so the value to pass to HTML input is a number.

Questioner
BreadFish
Viewed
33
peeebeee 2020-02-02 23:17

Your syntax for setting up a Leaflet click event isn't quite right. Also, you need to define the event so it dynamically picks up the required properties of the layer that was clicked on...

 function onFeature(feature, layer) {
    layer.on('click', function(e) {
       document.getElementById('id_address').value = parseInt(e.target.properties.pk)
    });
  }