[GIS] Loading Json properties in a popup using leafletjs

geojsonjavascriptleaflet

I have a geojson file (tide_gauges.geojson)

{
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },                                                                                
"features": [
{ "type": "Feature", "properties": { "NUMERO": "10569", "MAREGRAFO": "COCALZINHO", "FICHA": null }, "geometry": { "type": "Point", "coordinates": [ -4, -1 ] } },
{ "type": "Feature", "properties": { "NUMERO": "50240", "MAREGRAFO": "PONTA DE PARANAPUA", "FICHA": null }, "geometry": { "type": "Point", "coordinates": [ -4, -2 ] } }...

I retrieved this Json file in a variable:

var estacoes = new L.geoJson();
estacoes.addTo(map);

$.ajax({
dataType: "json",
url: "geojson/tide_gauges.geojson",
success: function(data) {
    $(data.features).each(function(key, data) {
        estacoes.addData(data);
    });
}
}).error(function() {});

I am in need to set all the feature properties (NUMERO,MAREGRAFO,FICHA,LATITUDE and LONGITUDE) in a popup that appears after a click over point feature on the map.

I tried the code below, but it is not enough:

var popupContent ="";
for (var k in feature.properties) {
    var v = String(feature.properties[k]);
    popupContent += k + '->' + v ;

Could someone give some tips on that, please?

Best Answer

Use onEachFeature option in L.GeoJSON constructor to bind popup to every feature in your GeoJSON. This function will be called for each feature and receive created L.Marker and original GeoJSON feature. You can change marker's options, bind popup, etc.

L.geoJson({
    onEachFeature: function(feature, layer) {
        //use feature.properties to construct popup html
        var popupContent = 'NUMERO: ' + feature.properties.NUMERO;
        layer.bindPopup(popupContent);
    }
})