Get started with leaflet.draw CDN

MIT licensed

Leaflet.draw: Leaflet.js plugin for map drawing and editing.

Tags:
  • maps
  • leaflet
  • client
  • vector
  • drawing
  • draw

Stable version

Copied!

How to start using leaflet.draw CDN


// Include required libraries
L.DomEvent.addDomListener(window, 'load', function() {
  // Initialize a map in an element with id 'mapid'
  const map = L.map('mapid').setView([51.505, -0.09], 13);

  // Include Leaflet Draw plugin from CDN
  L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
  }).addTo(map);

  // Initialize the draw control and add it to the map
  const drawControl = new L.Control.Draw({
    draw: {
      polyline: false,
      polygon: false,
      rectangle: false,
      circle: false,
      marker: true,
      circlemarker: false
    },
    position: 'topright'
  });

  map.addControl(drawControl);

  // Save the drawn features to a GeoJSON object
  let features = [];
  drawControl.on('draw:created', function(e) {
    const layer = e.layer;
    features.push(layer.toGeoJSON());
  });

  // Save the features to the local storage
  function saveFeatures() {
    localStorage.setItem('features', JSON.stringify(features));
  }

  // Load the features from the local storage
  function loadFeatures() {
    const storedFeatures = localStorage.getItem('features');
    if (storedFeatures) {
      features = JSON.parse(storedFeatures);
      L.geoJSON(features).addTo(map);
    }
  }

  // Call the functions to initialize the map with any previously saved features
  loadFeatures();
  saveFeatures();
});
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!
Copied!

All versions