javascript - 根据使用 Leaflet 单击的标记更改侧边栏上的信息

标签 javascript json onclick leaflet geojson

我很难完成一个项目,因为无法根据单击标记根据通过 json 获得的数据更改侧边栏中的信息。我的代码是:

基本的 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);

有了它,我可以显示标记,但当我单击任何内容并更改侧边栏的信息时,我无法继续。我知道的逻辑,但由于缺乏知识我无法实现:( 对于基本的疑问,我很抱歉,但是这次你能帮我吗?谢谢!!

最佳答案

您应该添加处理 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

关于javascript - 根据使用 Leaflet 单击的标记更改侧边栏上的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50571549/

相关文章:

php - 如何禁用 php 或 javascript 中的文本框回发

javascript - 如何正确地将javascript嵌入到wordpress中

javascript - jQuery:在新选项卡/窗口中打开链接时不调用单击处理程序

javascript - jQuery:可点击行的问题

android - 为什么 Android 应用程序在添加启动新 Activity 的按钮后会崩溃?

javascript - 在 Ajax 表单中设置 Google Analytics 事件

javascript - 有没有办法过滤 Google Chrome 控制台中的输出?

javascript跨域请求 iframe VS jsonp

javascript - 将 javascript 对象转换为 ruby​​ 哈希值

java - 为什么我在尝试将 JSON 数据加载到 RecyclerView 时收到 NullPointerException?