I am working on an webpage that uses Leaflet. The users can currently place a marker on the map when they click a specific area. I was wondering if there is a way to add a toggle so that the user can enable and disable placing markers when they click on the map.

I can't seem to find anything, but I could have missed it. I am new to HTML and Leaflet so I apologize if this has a simple solution. Below is my current HTML file:

<!DOCTYPE html>
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" 
          integrity="sha256-kLaT2GOSpHechhsozzB+flnD+zUyjE2LlfWPgU04xyI=" crossorigin="" 
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js" integrity="sha256- 
            WBkoXOwTeyKclOHuWtc+i2uENFpDZ9YPdf5Hf+D7ewM=" crossorigin=""></script>
        #map {
            position: absolute;
            top: 0;
            bottom: 0;
            left: 0;
            right: 0;
    <div id="map"></div>
        var map = L.map('map').setView([0, 0], 1)

                  key=TUHtC4pfxR178kXfCmqg', {
                  attribution: '<a href="https://www.maptiler.com/copyright/" 
                  target="_blank">&copy; MapTiler</a> <a 
                  href="https://www.openstreetmap.org/copyright" target="_blank">&copy; 
                  OpenStreetMap contributors</a>'

        var markerOptions = {
            draggable: false

        map.on("click", function (e){
            var marker = new L.Marker([e.latlng.lat, e.latlng.lng], 

1 Answer 1


For creating toggle button control you can use L.EasyButton Leaflet plugin (see https://github.com/CliffCloud/Leaflet.EasyButton).

To differentiate between toggle states you can for example set button background color to yellow when adding markers is activated.

Relevant part of the code could then look something like this:

.disable-markers-active {
  background-color: #FFFF99 !important;


var markerOptions = {
  draggable: false

function createMarkerOnClick(evt) {
  L.marker([evt.latlng.lat, evt.latlng.lng], markerOptions).addTo(map);
var toggle = L.easyButton({
  states: [{
    stateName: 'enable-markers',
    icon: 'fa-map-marker',
    title: 'Enable markers on click',
    onClick: function(control) {
      map.on('click', createMarkerOnClick);
  }, {
    icon: 'fa-map-marker',
    stateName: 'disable-markers',
    title: 'Disable markers on click',
    onClick: function(control) {
      map.off('click', createMarkerOnClick);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.