javascripthtmlleafletsidebarlocate

HTML code for using locate via onclick


I am trying to get the locator plugin to activate when clicking on the marker icon in my html sidebar. I would like it to use the locator function when clicked without adding the locator plugin to the map. This code below adds the fa-map-marker icon to the sidebar and, when you click on the icon, it adds the locator control to the leaflet map. Once you click on the added icon, it uses the L.control.locate function. Instead of adding the locator plugin to my map, can I somehow use the locator's function through onclick? End result will allow the user to directly get his location by clicking the fa-map-marker icon.

Sidebar-v2: https://github.com/Turbo87/sidebar-v2

L.control.locate: https://github.com/domoritz/leaflet-locatecontrol

<div class="sidebar-tabs">
  <ul role="tablist">
    <li>
      <a 
       title="Geolocate" role="tab" target="_blank" onClick="L.control.locate().addTo(map);" <i class="fa fa-map-marker"> </i>
      </a>
    </li>
  </ul>
</div>

Solution

  • Let me copy-paste from the leaflet-locatecontrol documentation...

    You can call start() or stop() on the locate control object to set the location on page load for example.

    // create control and add to map
    var lc = L.control.locate().addTo(map);
    
    // request location update and set location
    lc.start();
    

    Want to attach that to the click event of some DOM element? No problem...

    <a href='' id='foobar'>Try to get my location</a>
    

    var lc = L.control.locate().addTo(map);
    L.DomEvent.on( document.getElementById('foobar'), 'click', lc.start );
    

    Note the lack of () on lc.start - this is because L.DomEvent.on() needs a reference to a function, not the result of a function call.