JS leaflet: How to pass (Geo-)json ID to on click event?

LarsVegas picture LarsVegas · Mar 29, 2013 · Viewed 9.7k times · Source

My django web app should do the following: Pass a Geojson object to a view, map the points with leaflet and display some additional information when the user clicks on a point marker. I'm not so familiar with js so I got stuck binding the right kind of data to click event. Here is a sample geojson object. How can I access the 'id' with my click event?

var geojsonFeature = {'geometry':
                          {'type': 'MultiPoint', 
                          'coordinates': [[4.939, 52.33], [4.9409, 52.33]]
                          }, 
                     'type': 'Feature', 
                     'properties': 
                        {'id': '52','popupContent': 'id=52'}
                     };

Adding the geojson object to the map..

var gj = L.geoJson(geojsonFeature, {
    pointToLayer: function (feature, latlng) {
    return L.circleMarker(latlng, geojsonMarkerOptions);
    }}).addTo(map);

And the on()-click....

gj.on('click', function(evt) {
   alert(id) // well, this is where I need help
});

NOTE: I don't want to use something like bindPopup(feature.properties.popupContent) because I want to open a new window that calls a different django view with some extra data from the database.

Answer

LarsVegas picture LarsVegas · Mar 30, 2013

For everyone with a similar problem: What you want to use is the onEachFeature function. The feature represents a geojson object. Using the sample data provided above the id can be accessed through feature.properties.popupContent.

function onEachFeature(feature, layer) {
    layer.on('click', function (e) {
        alert(feature.properties.popupContent);
        //or
        alert(feature.properties.id);
    });
}