fcr fcr - 9 months ago 220
jQuery Question

Leaflet onEachFeature table info into a Div?

Im trying to get a table from a

geojson
extracted with
onEachFeature
function, it works displaying it with an alert, but I tried
getElementsByClassName
,to get it inside a Div but nothing shows

I'm using leaflet with leaflet sidebar plugin

Thanks

var tbl1 = "";

var proy = L.geoJSON(json_Obras, {
onEachFeature: function(feature, layer) {
tbl1 = '<table><tr><th scope="row">OBRA </th><td>' + (feature.properties['OBRA'] !== null ? Autolinker.link(String(feature.properties['OBRA'])) : '') + '</td></tr>'

}
}).addTo(map);


proy.on('click', function () {
sidebar.show();

})
map.on('click', function () {
sidebar.hide();
});

document.getElementsByClassName('t1').innerHTML = tbl1;


The div displays with a button click

<input id="btn" class="gral" type="button" name="answer" value="DATA" />
<div id="tabla" class="t1" style="display:none;">
</div>


jquery click function

$('.gral').click(function() {
$('.t1').toggle('slow', function() {

});
});


UPDATE

I managed to find out how to do this, based on a previous question:

var sidebar = L.control.sidebar('sidebar', {
closeButton: false,
position: 'left'
});

map.addControl(sidebar);

var ptsty = {
radius: 8,
fillColor: "#ff7800",
color: "#000",
weight: 1,
opacity: 1,
fillOpacity: 0.8
};

function onEachFeature(feature, layer) {
layer.on({
click: openSidebar
});
}

var lay1 = L.geoJson(json_Obras,{
pointToLayer: function (feature, latlng) {
return L.circleMarker(latlng, ptsty)
},
onEachFeature: onEachFeature
}).addTo(map);


function openSidebar(e) {
sidebar.toggle();
sidebar.setContent('<div id="sidebarin"><h2>' + e.target.feature.properties.OBRA + '</h2></div>');
}

Answer Source

First of all you are setting content of your div before the callback onEachFeature gets called. So the content is empty. Instead it is better to add content directly to element (sidebar or div), or add it when you toggle the sidebar.

onEachFeature: function (feature, layer) {
    var popupContent = "<p>I started out as a GeoJSON " +
     feature.geometry.type + ", but now I'm a Leaflet vector!</p>";

    if (feature.properties && feature.properties.popupContent) {
      popupContent += feature.properties.popupContent;
    }
    $('#sidebar>.sidebar_content').html(popupContent);
    $('.custom-div').html(popupContent);
}

I have prepared small demo which is working and you can get an idea how it can be implemented.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download