Leaflet中根据点击的标记更改侧边栏信息

3

由于无法根据点击的标记获取到的数据更改侧边栏中的信息,我在完成项目时遇到了困难。以下是我的代码:

基本的 json:

paradas = {
    "type" : "FeatureCollection",
    "name" : "paradas",
    "crs": {
        "type": "name",
        "properties": {
          "name": "urn:ogc:def:crs:OGC:1.3:CRS84"
        }
    },
    "features" : [
        { 
            "type" : "Feature", 
            "properties" : {  
                "nome" : "Parada 1", 
                "imagem" : "<img src='1.jpg' alt='maptime logo gif' width='350px'/>",
                "descricao" : "Test."
            }, 
            "geometry" : { 
                "type" : "Point", 
                "coordinates" : [
                    -38.55222702026367,
                    -3.7864725817550275
                ] 
            }
        },
       (... repeat json)

我的侧边栏的HTML代码:

<div class="sidebar">
            <div class="nome"></div>
            <div class="imagem"></div>
            <div class="descricao"></div>
    </div>

我的JS:

var rotas = L.geoJSON(paradas, {

}).addTo(map);

仅使用it,我可以显示标记,但无法继续进行。当我单击任何一个并更改侧边栏的信息时,我知道逻辑,但由于缺乏知识而无法实现:( 很抱歉有这样基本的疑问,但你能帮我这一次吗?谢谢!

1个回答

6

您应该添加处理onEachFeature点击的函数。假设您正在使用jquery(最简单的解决方案):

var rotas = L.geoJSON(paradas, {
  onEachFeature: onEachFeature
}).addTo(map);

function onEachFeature(feature, layer) {
  layer.on('click', function(e) {
    $(".nome").html(feature.properties.nome);
    $(".imagem").html(feature.properties.imagem);
    $(".descricao").html(feature.properties.descricao);
  });
}

在Codepen上的工作示例:https://codepen.io/dagmara223/pen/BVBGKG


1
顺便提一下,您还可以在“rotas”图层组上“委托”事件监听器。 - ghybs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接