首页 > 解决方案 > map.on('singleclick',function(evt){}); 调用单击时正在注册多次

问题描述

我第一次调用这个函数并单击它,它工作正常,但如果我再次单击调用相同的函数映射,那么它会注册多次(我使用警报检查);

var flagforClick = false;
function getData() {
    if (flagforClick == false) {
        flagforClick = true;
    }
    else {
        flagforClick = true;
    }
    map.on('singleclick', function (evt) {
        alert("called");
        if (flagforClick == true) {
            document.getElementById("tab_content").innerHTML = "";
            document.getElementById("dataGrid_tab").innerHTML = "";
            totalLayerDataSelectionSelection = [];
            totalheaderSelectionSelection = [];
            var headerdataSelection = [];
            var infodataSelection = [];
            layerSelectionforList = [];
        }
    });
}

标签: openlayers

解决方案


当单击像素处具有特征时,您可以在事件内部调用getData()函数。singleclick希望这个样本对您有所帮助。

var map = new ol.Map({
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM()
        })
    ],
    target: 'map',
    view: new ol.View({
        projection: 'EPSG:4326',
        center: [49, 40],
        zoom: 8
    })
});

var layer = new ol.layer.Vector({
    source: new ol.source.Vector({
        features: [new ol.Feature({
            geometry: new ol.geom.Point([49, 40]),
            id: 1,
            name: 'My Point',
            day: (new Date()).getDay(),
            month: (new Date()).getMonth(),
            year: (new Date()).getYear()

        })]
    }),
    style: new ol.style.Style({
        image: new ol.style.Circle({
            radius: 15,
            fill: null,
            stroke: new ol.style.Stroke({ color: 'red', width: 1 })
        })
    })
});
map.addLayer(layer);

map.on('singleclick', function (event) {
    // getData(event.coordinate);

    map.forEachFeatureAtPixel(event.pixel, function (feature, layer) {
        getData(feature.getProperties());
        // getData(layer.getProperties());
    }, {
            hitTolerance: 5
    });
});

function getData(data) {
    console.log(data);
    console.log(data.id);
}

推荐阅读