1

I want to click on a link in a navigation div in order to zoom to a location within my leaflet map.

Html:

<div class="sidebar-nav">
     <div class="story" data-point="40.7451, -73.949">First link</div>
     <div class="story" data-point="40.7451, -73.949">Second link</div>
</div>

<div id="map">
</div>

Javascript:

//initialize map
var map = L.map('map', {
  zoomControl: true
}).setView([40.7451, -73.9459], 16);

var osm = new L.TileLayer('http://{s}.tile.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
  maxZoom: 19
}).addTo(map);

//click and zoom        
$('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;

    // set the view
    map.setView([lat, lng], zoom);
  })

I am using: jQuery v3.2.1 leaflet v0.7.7

When I click on the div nothing happens. Forgive me if there is an obvious solution, I have brand-new to java-script.

I'm attempting to use a solution originally posted here: Leaflet.js map - Pan too and Zoom in on point

1 Answer 1

2

Your leaflet code along with jquery needs just one modification.

Just add a dot in on click function (as you are using a class name) as below:

$('.story').on('click', function(){

I would recomment you to use a trim() function in your latlng[] array i.e, latlng[0].trim() and latlng[1].trim(). Now it will work as your code has been tested.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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