[GIS] Leaflet.js map – Pan too and Zoom in on point

leaflet

This is the first time I am using Leaflet.js. I am trying to create a story map but have come across an issue.

Currently I have a map with a scrolling text bar on the left hand side. I would like users to be able to scroll through the text on the left and when they click on a part of the text it will automatically pan too and zoom in on the correct area on the map, at the same time displaying the marker.

Best Answer

Here is a pattern that may be useful. Data attributes provide a kind of 'self-configuring' behavior. The example here uses jQuery:

HTML

<div class="story" data-point="37.000,-120.652">First story. Click to zoom</div>
<div class="story" data-point="35.232,-118.334">Another story. Click to zoom</div>
<div class="story" data-point="35.232,-118.334">Another story. Click to zoom</div>

JavaScript

// basic map setup. include other options as needed, refer to the docs
var map = L.map('map');

// bind click event to the story divs, add a marker and zoom to that story's location. Remember to add dot before story as it is classname
$('.story').on('click', function(){
    // parse lat and lng from the divs data attribute
    var latlng = $(this).data().point.split(',');
    var lat = latlng[0];
    var lng = latlng[1];
    var zoom = 10;

    // add a marker
    var marker = L.marker([lat, lng],{}).addTo(map);
    // set the view
    map.setView([lat, lng], zoom);
})
Related Question