javascript 如何从地图外的链接打开传单标记弹出窗口?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17632359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:01:24  来源:igfitidea点击:

How to open leaflet marker popup from link outside of map?

javascriptmapleaflet

提问by Sam Healey

I have a leaflet map with several markers on.

我有一张传单地图,上面有几个标记。

Each of the markers have similar html to

每个标记都有类似的 html 到

 <img class="leaflet-marker-icon leaflet-clickable leaflet-zoom-animated" src="leaflet/dist/images/marker-icon.png" style="margin-left: -12px; margin-top: -41px; width: 25px; height: 41px; transform: translate(435px, 200px); z-index: 200;" title="location_1">

When the marker is clicked the popup opens above the marker.

单击标记时,会在标记上方打开弹出窗口。

What im trying to do is add links outside of the map, relating to each marker.

我想做的是在地图之外添加与每个标记相关的链接。

Each of the markers have a unique title. So could I just create a list of html links, with the title as an identifier such as

每个标记都有一个唯一的标题。那么我可以创建一个 html 链接列表,将标题作为标识符,例如

 <a class="location_1">location 1</a>
 <a class="location_2">location 2</a>

Then bind these links to the corresponding marker in the leaflet map?

然后将这些链接绑定到传单地图中的相应标记?

How would I best achieve this?

我将如何最好地实现这一目标?

回答by abenrob

if you add the markers to an array, it would be pretty straightforward to check them against attributes of your element.

如果将标记添加到数组中,根据元素的属性检查它们将非常简单。

For example:

例如:

var markers = [];
var marker1 = L.marker([51.497, -0.09],{title:"marker_1"}).addTo(map).bindPopup("Marker 1");
markers.push(marker1);
var marker2 = L.marker([51.495, -0.083],{title:"marker_2"}).addTo(map).bindPopup("Marker 2");
markers.push(marker2);
var marker3 = L.marker([51.49, -0.097],{title:"marker_3"}).addTo(map).bindPopup("Marker 3");
markers.push(marker3);

function markerFunction(id){
    for (var i in markers){
        var markerID = markers[i].options.title;
        if (markerID == id){
            markers[i].openPopup();
        };
    }
}

$("a").click(function(){
    markerFunction($(this)[0].id);
});

See it working in this fiddle

看到它在这个小提琴中工作