Trigger click on leaflet marker

后端 未结 1 591
轮回少年
轮回少年 2021-01-12 01:48

I have a bunch of leaflet markers on the map. Each marker is held in array markers. The markers are created dynamically (during an ajax call).

v         


        
相关标签:
1条回答
  • 2021-01-12 02:19

    To emulate a mouse click, you can use the fire method (inherited from Evented.fire) on the marker :

    marker.fire('click');
    

    And a demo

    var map = L.map('map').setView([0, 0], 12);
    
    var icon = L.icon({
      iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-green.png'
    });
    var marker = L.marker([0, 0], {icon: icon})
      .addTo(map);
      
      
    var myHoverIcon = L.icon({
      iconUrl: 'http://leafletjs.com/examples/custom-icons/leaf-red.png'
    });
      
      
    marker.on('click', function(e) {
      marker.setIcon(myHoverIcon);
    });
    
    document.querySelector('button').addEventListener('click', function() {
      marker.fire('click');
    });
    html, body {
      height: 100%;
      margin: 0;
    }
    #map {
      width: 100%;
      height: 100%;
    }
    
    button {position: absolute; left:10 px; top: 70px;}
    <link rel="stylesheet" href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" integrity="sha512-M2wvCLH6DSRazYeZRIm1JnYyh22purTM+FDB5CsyxtQJYeKq83arPe5wgbNmcFXGqiSH2XR8dT/fJISVA1r/zQ==" crossorigin=""/>
    
    <script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js" integrity="sha512-lInM/apFSqyy1o6s89K4iQUKg6ppXEgsVxT35HbzUupEVRh2Eu9Wdl4tHj7dZO0s1uvplcYGmt3498TtHq+log==" crossorigin=""></script>
       
    <div id='map'></div>
    <button>Click me</button>

    0 讨论(0)
提交回复
热议问题