Tenz Tenz - 1 year ago 271
Javascript Question

Leaflet: Autoscroll sidebar on marker 'mouseclick'

The Example on Fiddle

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

function onMapClick(e) {
var marker = new L.Marker(e.latlng);
marker.on('click', onMarkerClick);
markers[marker._leaflet_id] = marker;
'<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

// Remove the link

$('.item').on("mouseover", function () {
for (var mark in markers){
var mid = $(this).attr('id');
var LatLng = markers[mid].getLatLng();
var offset = map._getNewTopLeftPoint(LatLng).subtract(map._getTopLeftPoint());

function markerFunction(id){

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 Source

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 }}">

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()) {
      scrollTop: scrollTo.offset().top - padding
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download