简体   繁体   中英

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.

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);
    });
}

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);
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM