首页 > 解决方案 > 如何将点击事件添加到我存储在数组中的任何标记

问题描述

我正在使用传单 js,我有一个数组,我在其中存储我的标记,这些标记在获得用户位置后自动添加到地图中。 问题是我想添加一个 onclick 侦听器,以便单击的任何标记都将运行一个函数。 请帮帮我,因为我现在被卡住了。

//objects for markers
var allMarkers=[];
var  AllMarkers = L.layerGroup(allMarkers);

var Allpoints=[{
    "latitudes":9.4258946,"longitudes":-0.8842213,              "names":"first", "eastings":556568, "northings":446445, "description": "aijaskj jnrkajra skjanjanek ", "elevations": 5668

},

    {
        "latitudes":9.4254946,"longitudes":-0.8812213,  "names":"second"},

        {
            "latitudes":9.4054946,"longitudes":-0.8802213,  "names":"third"},

            {
                "latitudes":9.4754946,"longitudes":-0.8712213,  "names":"fourth"},
        
    ];


//automatically plot all previous markers
var point = L.point(9.2754946, -0.8912213);
q = 0;
while(q< Allpoints.length){
    //create Marker here
    _newMarker = L.marker(
        
        [Allpoints[q].latitudes, Allpoints[q].longitudes], 

        {title: Allpoints[q].names,
            riseOnHover: true,           

        }  ).addTo(mymap);

    allMarkers.push(_newMarker);
    q++
}

//function to send back the details of the clicked marker to a paragraph in my index.htm


//PROBLEM
L.marker('click', markers, showMarkerDetails)   //however the code immediately above does not work

function showMarkerDetails(){
    $("#returnControlName").html(controlName);
    $("#returnControlLocation").html(`${controlLat.toFixed(4)} ,  ${controlLong.toFixed(4)} `);
    $("#returnControlEastings").html(controlEastings);
     $("#returnControlName").html(controlNorthings);
     $("#returnControlName").html(controlElevation);
     $("#returnControlName").html(controlDescription); 
}

标签: javascriptarraysobjectleafletmarkers

解决方案


随着L.marker()您向地图添加新的标记/点,您无法向它们添加类似的事件。( L.marker('click', markers, showMarkerDetails) )

将您的代码更改为:


//automatically plot all previous markers
var point = L.point(9.2754946, -0.8912213);
q = 0;
while(q< Allpoints.length){
    //create Marker here
    _newMarker = L.marker([Allpoints[q].latitudes, Allpoints[q].longitudes], 
        {title: Allpoints[q].names,
            riseOnHover: true,           

        }).addTo(mymap);
    _newMarker.informations = Allpoints[q]; // save the data to the marker to read it later out
    _newMarker.on('click',showMarkerDetails); // add click event to the markers
    allMarkers.push(_newMarker);
    q++
}

function showMarkerDetails(e){
    var layer = e.target // get the clicked marker
    var infos = layer.informations;
    console.log(infos.description);


    $("#returnControlName").html(controlName);
    $("#returnControlLocation").html(`${controlLat.toFixed(4)} ,  ${controlLong.toFixed(4)} `);
    $("#returnControlEastings").html(controlEastings);
     $("#returnControlName").html(controlNorthings);
     $("#returnControlName").html(controlElevation);
     $("#returnControlName").html(controlDescription); 
}

推荐阅读