6

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.

  • 2
    What have you tried so far? where are you stuck? Have you tried the setView method on the map? – Devdatta Tengshe May 13 '15 at 8:51
  • SetView is what you are looking for, I think, as you haven't really stated what is the text being clicked on. – John Powell May 13 '15 at 14:37
8

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);
})
  • 3
    set view won't actually PAN the map to the point but will jump to it. panTo is what you want to use instead. Works just like setView but will pan to the place (if possible/not too far away, I think) instead of jumping – Daniele Ding May 14 '16 at 18:48
3

The answer is:

var marker = L.marker([lat, lng],{}).addTo(map);
map.flyTo([lat, lng], zoom);
1

As @Daniele Ding pointed out, you can use panTo to let the user navigates to the desired location smoothly, rather than jumping from point to point, which is considered more pleasant user experience.

Basic example:

map.panTo(latlng);

In my case, I needed to let the user to navigate to drawn shape on the map, and I used:

var layer = polygonsGroup.getLayers()[0];
var latlngs = layer.getLatLngs()[0];
var latlng = L.latLng(latlngs[0]);
MapEngine.map.panTo(latlng);
layer.setStyle({
    color: "#FFFF00",
    fillColor: "#FFFF7F"
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.