Jakub Kohn
Jakub Kohn

Reputation: 11

dynamic content in sidebar in Leaflet

I'm trying to create a map with sidebar plugin. I can make a map with many markers and plugin from "demo example", but I don't know, how to create a "dynamic" content in slidebar which shows atributes from each marker separately.

My simple code:

<script>
var map = L.map('map');

L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    maxZoom: 18,
    attribution: 'Map data &copy; OpenStreetMap contributors'
}).addTo(map);

var sidebar = L.control.sidebar('sidebar', {
    closeButton: true,
    position: 'left'
});
map.addControl(sidebar);
sidebar.setContent('aaaaaaa');   

setTimeout(function () {
    sidebar.show();
}, 500);
var marker = L.marker([49.46, 17.11]).addTo(map).on('click', function () {
    sidebar.toogle()
    marker.bindPopup("<b>Hello world!</b><br />I am a popup.").openPopup();
sidebar.setContent('aaaaaaa');   

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

map.setView([49, 17], 5);

Upvotes: 1

Views: 4066

Answers (1)

Arturo Volpe
Arturo Volpe

Reputation: 3627

You need to create the content manually, and update the sidebar every time the data changes, check this example.

First, create a function to update your data, you can use map.eacheLayer to get all the layers, something like this:

function updateDataInSidebar() {
    var newData = '<div id="layer-data">';
    map.eachLayer(function (layer) { 
        if (layer.options.id) {
            newData += 'Marker' + layer.options.id + '<br />'; 
        }
    });
    sidebar.setContent(newData + '</div>')
}

You can store arbitrary data in options, like this:

marker = createMarker(lat, lng);
marker.options.id = '123';

You can use the data stored in the options to populate your sidebar, to get the current position of your marker, user getLatLng;

Upvotes: 1

Related Questions