Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 778
LarsVegas Avatar asked Mar 29 '13 21:03

LarsVegas


2 Answers

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);
    });
}
like image 169
LarsVegas Avatar answered Nov 28 '22 08:11

LarsVegas


After trying the solution posted above without success, I got this version to work:

function onEachFeature(feature, layer) {
    layer.on('click', function (e) {
        alert(e.target.feature.properties.popupContent);
        //or
        alert(e.target.feature.properties.id);
    });
}
like image 32
DHCurrie Avatar answered Nov 28 '22 08:11

DHCurrie