javascript - 在未定义的传单 js ("cannot read property ' 上创建的图层上使用 dblclick 事件时出现问题”)

标签 javascript leaflet geojson

如果这是新手问题,我很抱歉。我也在论坛内搜索,但没有找到类似我的问题。

我正在使用 leaflet(mapbox js),我有一个全局变量,它在一个名为 inicializarMapa() 的函数中使用。然后调用该函数,最后我使用 layerName.on('dbclick',function(){ Do something})。但是控制台会触发一条消息,指出 “无法读取未定义的属性‘on’”

标记出现在我的 map 中。但我不知道为什么我不能做 dblclick 事件。

我希望你能帮我找出为什么变量会变成undefined,非常感谢你抽出时间:)。

var myLayer;
function inicializarMapa(){

$.ajax({                                      
      url: 'consulta4.php',                  
      data:{
            },                        
      method: 'POST',                               
      dataType:'json',                
      success: function(data)          
      {   
        for(var i in data)
        {

           var geojson = [{
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [data[i].longitude,data[i].latitude]
                        },

                "properties": {
                "title": "Emergencia: "+data[i].priority,
                "id":data[i].id_emergency,
                //"descripcion":"<button class='RE'>oisdjos</button>", Forma alternativa de añadir html   
                "icon": {
                "iconUrl": data[i].imagen,
                "iconSize": [50, 50], // size of the icon
                "iconAnchor": [25, 50], // point of the icon which will correspond to marker's location
                "popupAnchor": [0, -25], // point from which the popup should open relative to the iconAnchor
                "className": "dot"
                        }
                        }
                }];     //alert(data[i].longitude.valueOf());

                myLayer = L.mapbox.featureLayer().setGeoJSON(geojson).addTo(map);
                myLayer.on('click',function(e){
                   //console.log(e.layer.feature.properties.title);
                    map.panTo(e.layer.getLatLng());

                });
                myLayer.on('layeradd', function(e) {
                marcadorEMG[i]= e.layer;
                var feature = marcadorEMG[i].feature;
                marcadorEMG[i].setIcon(L.icon(feature.properties.icon));



                 /*var popupContent =  '<a target="_blank" class="popup" href="' + feature.properties.url + '">' +
                            '<img src="' + feature.properties.image + '" />' +
                            feature.properties.city +
                        '</a>';    */
                var popupContent='<div class="contenedor-min-principal"><div class="contenedor-info"><b>'+feature.properties.title+'</b><p>Id emergencia:'+feature.properties.id+'</p></div><div class="contenedor-btn"><button class="emg" value="'+data[i].id_emergency+'">Modificar</button><button class="reporte" value="'+data[i].id_emergency+'">Reporte</button><button class="asistida" value="'+data[i].id_emergency+'">Finalizar</button></div><div class="contenedor-emg"><form class="formamin-emg">Dirección:<input type="text" id="direccion-emg-min" maxlength="50">Prioridad<select id="prioridad-emg-min"></select>Tipo punto interés<select id="tipo-pto-interes-emg-min"></select><div class="btn-final-aceptar"><input type="submit" value="Aceptar"></div></form></div></div>';//IMPORTANTISIMO

                marcadorEMG[i].bindPopup(popupContent,{
                closeButton: true,
                   minWidth: 300,
                    maxwidth:300
                });

                contadorEmergencias++;
                });
                myLayer.setGeoJSON(geojson);
            contadorEMG=i;
          }  
      }
 });//Fin ajax emergencias
//////////////////////////////////////////////////////



}//fin inicializar mapa

inicializarMapa();
myLayer.on('dblclick',function(){alert("hi");});

最佳答案

发生这种情况是因为当您尝试将 dblclick 绑定(bind)到您的 myLayer 时,myLayer 还不包含 featureGroup 因为 inicializarMapa 仍在运行。您需要像处理 addlayerclick 事件一样绑定(bind)成功回调函数。

评论后编辑,这是你的成功方法,它在从 consulta4.php 加载完成后执行:

$.ajax({                                      
    url: 'consulta4.php',
    data: {},
    method: 'POST',
    dataType:'json',
    success: function (data) { // <- Start of your success method/function

    } // <- end of your success method/function
});

你现在在做什么:

var myLayer;

$.ajax({                                      
    url: 'consulta4.php',
    data: {},
    method: 'POST',
    dataType:'json',
    success: function (data) { // <- Start of your success method/function
        myLayer = L.mapbox.featureLayer();
    } // <- end of your success method/function
});

// This is called before the success method has finished, so calling
// 'on' will fail because it's a method of featureLayer, and myLayer
// doesn't hold a featureLayer yet
myLayer.on('dblclick, function () {...});

因此,在变量 myLayer 上定义了 featureLayer 之后,您需要在 success 方法中绑定(bind)到 dblclick 事件:

var myLayer;

$.ajax({                                      
    url: 'consulta4.php',
    data: {},
    method: 'POST',
    dataType:'json',
    success: function (data) { // <- Start of your success method/function
        myLayer = L.mapbox.featureLayer();
        myLayer.on('dblclick, function () {...});
    } // <- end of your success method/function
});

Edit²:您可以在 ajax 调用之前声明您的 featureLayer 并附加处理程序:

var featureLayer = L.mapbox.featureLayer().addTo(map);

featureLayer.on('dblclick', function () {});

$.ajax({                                      
    url: 'consulta4.php',
    data: {},
    method: 'POST',
    dataType:'json',
    success: function (data) {
        featureLayer.setGeoJSON(data);
    }
});

关于javascript - 在未定义的传单 js ("cannot read property ' 上创建的图层上使用 dblclick 事件时出现问题”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34215309/

相关文章:

java - 如果属性中有几何图形,则 Geojson 文件无法正确导入

python - 将整个 csv 转换为 json 文件- python

javascript - 如何从数据库获取时间后开始倒计时?

javascript - 如何使用 JSON 作为 contentType 制作 Kendo MVC Helpers 的 CRUD

r - 在 R 中的revealjs 演示文稿中加入传单 map

leaflet - 如何获取control.layers中选定的图层?

javascript - 操作 GeoJSON 数据 - 在 OpenLayers 中重新加载矢量图层

javascript - $parent.inState 不是 Knockout JS 的函数错误

javascript - div contenteditable 标签的 setStart

javascript - 使用 react 按钮更改传单 basemap