Leaflet zoom on locations using multiple links

半城伤御伤魂 提交于 2019-12-11 09:17:37

问题


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:


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



来源:https://stackoverflow.com/questions/28076312/leaflet-zoom-on-locations-using-multiple-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!