Leaflet zoom on locations using multiple links

2019-07-28 05:06发布

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 don't work. I figured out that the "getelementbyId" must be the problem because an ID is meant to be unique in an html page. But I don't have enough knowledge of JS to solve this any other way. Could somebody maybe help with this problem?

The locations are stored in tags:

<div id="map-navigation" class="map-navigation">
   <a href="#" data-zoom="12" data-position="48.06633,7.67268">
   Link 1
   </a>
</div>

The JS looks like this:

document.getElementById('map-navigation').onclick = function(abc) {
var pos = abc.target.getAttribute('data-position');
var zoom = abc.target.getAttribute('data-zoom');
if (pos && zoom) {
    var locat = pos.split(',');
    var zoo = parseInt(zoom);
    map.setView(locat, zoo, {animation: true});
    return false;
}
}      

You can check the whole thing out on jsfiddle: http://jsfiddle.net/chodid/ndznw6z7/2/

Thanks hell of a lot in advance for any advice!

1条回答
Juvenile、少年°
2楼-- · 2019-07-28 05:38

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

查看更多
登录 后发表回答