4

I am using leaflet and leaflet-draw on a page that I'm working on. I want to use my own off-map buttons instead of the classic leaflet-draw controls that are on the map. I can't find an example of how this is done or if it's even possible. How do I link the functionality that is normally on the buttons on the map to my own OFF-MAP buttons?

So basically I would have a button below the map (not on the map) that zooms in for example (I assume the same method would also be applicable to the leaflet-draw controls). This feels like it should be really easy but like I say I can't figure out how.

enter image description here

kboul
  • 13,836
  • 5
  • 42
  • 53
MarkusAfricanus
  • 113
  • 1
  • 16
  • So someone already answered this question. https://stackoverflow.com/questions/15775103/leaflet-draw-mapping-how-to-initiate-the-draw-function-without-toolbar/17144318#17144318 – MarkusAfricanus Feb 14 '19 at 06:50

2 Answers2

2

As you already mentioned the answer is already there. Only thing that remains to be done is to addEventListeners and create relevant functions. Here is an example if you would like to trigger a polyline draw and cancel it respectively:

html

<div id="map"></div>
<button id="drawPolyline">Draw</button>
<button id="cancelDraw">Cancel Draw</button>

js

// add an event listener to trigger polyline draw
document
  .getElementById("drawPolyline")
  .addEventListener("click", e => drawPolyline(e));

// add an event listener to cancel polyline draw
document
  .getElementById("cancelDraw")
  .addEventListener("click", e => cancelDraw(e));

// declare a global variable to store a reference
let polylineDrawHandler;

// store the polyline draw instantiation to a variable to be able 
// to disable it later
const drawPolyline = e => {
  polylineDrawHandler = new L.Draw.Polyline(map, drawControl.options.polyline);
  polylineDrawHandler.enable();
};

const cancelDraw = e => polylineDrawHandler.disable();

Demo

kboul
  • 13,836
  • 5
  • 42
  • 53
0

JS Fiddle for Random Zoom!

The code attaches a click handler to call a method for the map:

document.querySelector("#zoom").onclick = function() {
    map.setZoom(Math.ceil(18*Math.random()));
}

From the documentation, there are a lot of functions that can modify the state of the map. Hope this helps!

Sunny Pun
  • 726
  • 5
  • 14
  • Thanks Sunny Pun for your answer. Yes that will definitely work work for the zoom but what about using the leaflet-draw controls? – MarkusAfricanus Feb 14 '19 at 06:48