Tenz Tenz - 1 month ago 25
Javascript Question

Leaflet: Autoscroll sidebar on marker 'mouseclick'

The Example on Fiddle

map.on('click', onMapClick);
function onMarkerClick(e) {
$('div').removeClass('active');
$('div #' + e.target._leaflet_id).addClass('active');
for (var mark in markers){
markers[mark].setIcon(smallIcon);}
var offset = map._getNewTopLeftPoint(e.target.getLatLng()).subtract(map._getTopLeftPoint());
map.panBy(offset);
}

function onMapClick(e) {
var marker = new L.Marker(e.latlng);
marker.on('click', onMarkerClick);
map.addLayer(marker);
marker.bindPopup("Marker");
markers[marker._leaflet_id] = marker;
$('#overlay').append(
'<div class="item" id="' + marker._leaflet_id + '">Marker ' + marker._leaflet_id + ' - <a href="#" class="remove" id="' + marker._leaflet_id + '">remove</a></div>');

// Remove a marker
$('.remove').on("click", function () {
// Remove the marker
map.removeLayer(markers[$(this).attr('id')]);

// Remove the link
$(this).parent('div').remove();
});

$('.item').on("mouseover", function () {
$('div').removeClass('active');
$(this).addClass('active');
for (var mark in markers){
markers[mark].setIcon(smallIcon);}
markerFunction($(this).attr('id'))
markers[$(this).attr('id')].setIcon(bigIcon);
var mid = $(this).attr('id');
var LatLng = markers[mid].getLatLng();
var offset = map._getNewTopLeftPoint(LatLng).subtract(map._getTopLeftPoint());
map.panBy(offset);
});
}

function markerFunction(id){
markers[id].openPopup();
}


show how to add markers onto sidebar. If user hover on any item on the sidebar, the marker will auto-span in the middle of the map. If user click on any marker, the sidebar's item will be highlighted.

However, if there are tons of markers on the map, how can I make the sidebar autoscroll. (E.g the highlighted item on the sidebar can be shown when user click on marker without manually scrolling down the sidebar to find where is the highlighted item on the sidebar

Answer

Something like this ? http://www.franceimage.com/map/

I used jquery animation here: https://github.com/franceimage/franceimage.github.io/blob/master/map/explore.js#L458

What you need to do is to tag the items in your sidebar with a unique id that links them with their corresponding marker.

<div class="postContent" data-post_id="{{ guid }}">
</div>

When a marker is clicked, you have to locate the corresponding item and scroll to it. That is where jQuery is handy, but you could do it another way I guess.

var container = $("html,body");
var padding = parseInt($("#page").css("padding-top")) + parseInt($(".postContent").css("margin-top"));
var scrollTo = $("div.postContent[data-post_id=" + selectedPostId + "]");

if(scrollTo.offset()) {
   container.animate({
      scrollTop: scrollTo.offset().top - padding
   });
}