簡體   English   中英

傳單:如何模擬鼠標點擊? fireevent('click') 不會觸發彈出窗口

[英]Leaflet: How can I simulate a mouse click? fireevent('click') does not trigger the popup

我想用傳單在javascript中模擬鼠標點擊。

我有一張有幾個不同圖層的地圖。 一些激活彈出窗口。 當我用鼠標單擊一個項目時,會出現一個彈出窗口。

當我嘗試執行以下代碼時,它似乎在所需位置“單擊”但沒有彈出窗口。

map.fireEvent('click', {
    latlng: L.latLng(lat, lng)
});

只有當圖層收到單擊事件時,圖層的彈出窗口才會打開。

當您執行map.fire('click') ,只有地圖獲取事件,而不是其上的圖層,即使它們位於您指定的緯度/經度位置。

為了找到哪些圖層位於指定的緯度/經度位置,您可以使用例如leaflet-pip插件(多邊形中的點):

 var map = L.map('map').setView([48.86, 2.35], 11); var geoJSONdata = { type: 'Feature', geometry: { type: 'Polygon', coordinates: [ [ [2.3, 48.85], [2.3, 48.87], [2.4, 48.87], [2.4, 48.85], [2.3, 48.85] ] ] } } var geoJsonLayerGroup = L.geoJSON(geoJSONdata, { onEachFeature: function(feature, layer) { layer.bindPopup('Popup') } }).addTo(map); document.getElementById('pipClick').addEventListener('click', function() { var latlng = L.latLng([48.86, 2.35]); // Use Mapbox Leaflet PIP (point in polygon) library. var foundLayers = leafletPip.pointInLayer(latlng, geoJsonLayerGroup); foundLayers.forEach(function(layer) { layer.fire('click', { latlng: latlng }); }); }); document.getElementById('mapClick').addEventListener('click', function() { map.fire('click', { latlng: L.latLng([48.86, 2.35]) }); }); L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map);
 <link rel="stylesheet" href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" integrity="sha512-Rksm5RenBEKSKFjgI3a41vrjkw4EVPlJ3+OiI65vTjIdo9brlAacEuKOiQ5OFh7cOI1bkDwLqdLw3Zg0cRJAAQ==" crossorigin="" /> <script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet-src.js" integrity="sha512-IkGU/uDhB9u9F8k+2OsA6XXoowIhOuQL1NTgNZHY1nkURnqEGlDZq3GsfmdJdKFe1k1zOc6YU2K7qY+hF9AodA==" crossorigin=""></script> <script src="https://unpkg.com/leaflet-pip@1.1.0/leaflet-pip.js"></script> <button id="mapClick">Click on Map</button> <button id="pipClick">Find layers with PIP and click them</button> <div id="map" style="height: 170px"></div>

添加到@ghybs 答案:Leaflet 圖層有一個fireEvent方法,您可以使用它來觸發圖層事件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM