clickable

by pkeller3

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.1/leaflet-src.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.1/leaflet.css">
<div id='map'></div>
<button id='button'>Click me</button>

CSS

#map {
    height: 250px;
}
button {
    margin-top:5px;
}

JavaScript

var map;

function initMap() {
    // set up the map
    map = new L.Map('map');

    // create the tile layer with correct attribution
    var osmUrl = 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
    var osmAttrib = 'Map data © <a href="http://openstreetmap.org">OpenStreetMap</a> contributors';
    var osm = new L.TileLayer(osmUrl, {
        minZoom: 8,
        maxZoom: 15,
        attribution: osmAttrib
    });

    // start the map 
    map.setView(new L.LatLng(51.503, -0.06), 13);
    map.addLayer(osm);
}

initMap();

var polygon = L.polygon([
    [51.509, -0.08],
    [51.503, -0.06],
    [51.51, -0.047]
]).addTo(map);
var added = true;

function myFunction() {
    if (added) {
        map.removeLayer(polygon);
        added = false;
    } else {
        polygon.setStyle({clickable:!this.noClickable});
        polygon.addTo(map);
        added = true;
    }
}

document.getElementById("button").addEventListener("click", myFunction);