Reputation: 519
I have a dataset with several points (latitude, longitude and some text for each), which I would like to show on a map, using Leaflet. Instead of using Leaflet built-in popups, I am trying to use leaflet-sidebar, which allows to open a sidebar when a marker is clicked.
If you are interested, you can see an example (with one single marker) here: https://github.com/Turbo87/leaflet-sidebar/blob/master/examples/index.html
As you can see, I correctly open a sidebar for each marker, but the content of each <div>
is shown also below the map.
This is due to the fact that I have the <div>
within a PHP while loop, as follows:
<?php
$i = 0;
while($result = mysql_fetch_array($objQuery)){
$i++;
$lat = $result['lat'];
$lon = $result['lon'];
$text = $result['some_text'];
?>
<div id="sidebar_<?=$i;?>" align="left">
<b>text</b>: <?=$some_text;?>
</div>
<script>
var sidebar_<?=$i;?> = L.control.sidebar('sidebar_<?=$i;?>', {
closeButton: true,
position: 'left'
});
map.addControl(sidebar_<?=$i;?>);
setTimeout(function () {
sidebar_<?=$i;?>.hide();
}, 500);
var marker = L.marker([<?php echo $lat;?>, <?php echo $lon;?>]).addTo(map).on('click', function () {
sidebar_<?=$i;?>.toggle();
});
</script>
<?php
}
?>
If I place the <div id="sidebar_<?=$i;?>">
outside the while loop, I can't collect each single marker lat/lon/text reference.
Do you have any tips on how to avoid this repetition below the map?
Upvotes: 1
Views: 737
Reputation: 519
I found a workaround!
On the plugin webpage there is a note to add contents to <div>
dynamically.
Basically, you need to leave the <div>
empty in the html, and add content in the script part, using setContent
:
<script>
var sidebar_<?=$i;?> = L.control.sidebar('sidebar_<?=$i;?>', {
closeButton: true,
position: 'left'
});
//HERE IT IS:
sidebar_<?=$i;?>.setContent('<b>categoria</b>: <?=$categoria;?><br><br><b>problema</b>: <?=$descrizione;?><br><br><b>proposta</b>: <?=$soluzione;?><br><br><div class="smaller">data segnalazione: <?=$giorno."/".$mese."/".$anno;?></div>');
map.addControl(sidebar_<?=$i;?>);
setTimeout(function () {
sidebar_<?=$i;?>.hide();
}, 500);
var marker = L.marker([<?php echo $lat;?>, <?php echo $lon;?>], {icon: iconarossa}).addTo(map).on('click', function () {
sidebar_<?=$i;?>.toggle();
});
</script>
Now it looks as I wished.
Upvotes: 2
Reputation: 2618
You need to add display: none
to the style of the sidebar <div>
-
<div id="sidebar_<?=$i;?>" align="left" style="display:none">
<b>text</b>: <?=$some_text;?>
</div>
You can probably do it a neater way with classes, but this should get you going.
Upvotes: 1