Skip to content Skip to sidebar Skip to footer

Leaflet Zoom On Locations Using Multiple Links

I just ran into another problem using Leaflet. I want to zoom into specific locations using Links provided underneath the maps. With one link I got it to work fine but more Links d

Solution 1:

First off, in the Fiddle, you have two elements with an id called map-navigation. That's invalid HTML. An id is not supposed to be used on multiple elements, that's what classnames are for.

Next, you're trying to bind the onclick event by quering for an element with id map-navigation. This will just bind the first element it finds with id map-navigation and will ignore the rest because getElementById will always return one element. Solution is to query all the elements with class map-navigation, since classes can be used on multiple elements using getElementsByClassname. An example:

HTML:

<a href="#" class="map-navigation" data-zoom="10" data-position="48.8567, 2.3508">Paris</a>
<a href="#" class="map-navigation" data-zoom="10" data-position="51.507222, -0.1275">London</a>

Javascript:

// Handler function
var handler = function (e) {
  var position = e.target.getAttribute('data-position');
  var zoom = e.target.getAttribute('data-zoom');
  if (position && zoom) {
    var location = position.split(',');
    map.setView(location, zoom, {
      animation: true
    });
  }
}

// Fetch all elements with class map-navigation
var elements = document.getElementsByClassName('map-navigation');

// Loop over nodelist and attach handler to onclick
for (var i = 0; i < elements.length; i++) {
  elements[i].onclick = handler;
}

Here's a working example on Plunker: http://plnkr.co/edit/hOwyeU?p=preview


Post a Comment for "Leaflet Zoom On Locations Using Multiple Links"