Convert Figma logo to code with AI

Leaflet logoLeaflet.draw

Vector drawing and editing plugin for Leaflet

2,027
999
2,027
463

Top Related Projects

Draw tools for mapbox-gl-js

A library for building rich, web-based geospatial 2D & 3D data platforms.

Mapbox JavaScript API, a Leaflet Plugin

Quick Overview

Leaflet.draw is a plugin for the Leaflet mapping library that adds drawing and editing tools for creating and manipulating vector layers on interactive maps. It provides a user-friendly interface for drawing various shapes like polygons, polylines, rectangles, circles, and markers, as well as editing existing features on the map.

Pros

  • Easy integration with existing Leaflet maps
  • Intuitive user interface for drawing and editing shapes
  • Customizable controls and styling options
  • Supports multiple geometry types (points, lines, polygons)

Cons

  • Limited advanced editing features compared to full-fledged GIS software
  • Dependency on Leaflet library
  • May require additional plugins for more complex operations
  • Performance can degrade with large numbers of editable features

Code Examples

  1. Initialize the Leaflet.draw control:
var map = L.map('map').setView([51.505, -0.09], 13);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
    edit: {
        featureGroup: drawnItems
    }
});
map.addControl(drawControl);
  1. Handle drawn items:
map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;
    drawnItems.addLayer(layer);
});
  1. Customize draw options:
var drawControl = new L.Control.Draw({
    draw: {
        polygon: {
            allowIntersection: false,
            showArea: true
        },
        circle: false,
        rectangle: false
    }
});

Getting Started

  1. Include Leaflet and Leaflet.draw in your HTML:
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.7.1/dist/leaflet.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.css" />
<script src="https://unpkg.com/leaflet@1.7.1/dist/leaflet.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.4/leaflet.draw.js"></script>
  1. Create a map container in your HTML:
<div id="map" style="height: 400px;"></div>
  1. Initialize the map and add Leaflet.draw control:
var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);

var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);

var drawControl = new L.Control.Draw({
    edit: {
        featureGroup: drawnItems
    }
});
map.addControl(drawControl);

map.on(L.Draw.Event.CREATED, function (event) {
    var layer = event.layer;
    drawnItems.addLayer(layer);
});

Competitor Comparisons

Draw tools for mapbox-gl-js

Pros of mapbox-gl-draw

  • Better performance for large datasets and complex geometries
  • Seamless integration with Mapbox GL JS for vector tile rendering
  • More advanced styling options and customization capabilities

Cons of mapbox-gl-draw

  • Requires Mapbox GL JS, which may have licensing implications
  • Steeper learning curve compared to Leaflet.draw
  • Less extensive documentation and community support

Code Comparison

mapbox-gl-draw:

map.addControl(new MapboxDraw({
  displayControlsDefault: false,
  controls: {
    polygon: true,
    trash: true
  }
}));

Leaflet.draw:

var drawControl = new L.Control.Draw({
  draw: {
    polygon: true
  }
});
map.addControl(drawControl);

Both libraries offer similar functionality for drawing shapes on maps, but their implementation and integration differ. mapbox-gl-draw is tightly coupled with Mapbox GL JS, providing advanced features and performance optimizations. Leaflet.draw, on the other hand, is more lightweight and easier to integrate with various map providers.

The choice between these libraries depends on your specific project requirements, performance needs, and preferred mapping ecosystem. Consider factors such as data complexity, rendering performance, and ease of use when making your decision.

A library for building rich, web-based geospatial 2D & 3D data platforms.

Pros of TerriaJS

  • More comprehensive geospatial data visualization platform
  • Supports 3D globe views and time-based data
  • Includes built-in data catalog and sharing features

Cons of TerriaJS

  • Steeper learning curve due to increased complexity
  • Heavier and potentially slower for simple mapping tasks
  • Less flexibility for custom drawing tools

Code Comparison

TerriaJS (initialization):

const terria = new Terria({
    baseUrl: CONFIG.terriaBaseUrl,
    cesiumBaseUrl: CONFIG.cesiumBaseUrl
});
terria.start({
    // Configuration options
});

Leaflet.draw (initialization):

var map = L.map('map').setView([51.505, -0.09], 13);
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
    edit: { featureGroup: drawnItems }
});
map.addControl(drawControl);

TerriaJS is a more comprehensive geospatial platform with advanced features, while Leaflet.draw is a simpler, more focused drawing plugin for Leaflet maps. TerriaJS offers more out-of-the-box functionality but may be overkill for basic mapping needs, whereas Leaflet.draw provides a lightweight solution for adding drawing capabilities to Leaflet maps.

Mapbox JavaScript API, a Leaflet Plugin

Pros of mapbox.js

  • More comprehensive mapping solution with built-in geocoding and directions services
  • Extensive styling options and customizable map designs
  • Better performance for large datasets and complex visualizations

Cons of mapbox.js

  • Requires a Mapbox account and API key, which may have usage limits or costs
  • Less flexibility for using alternative map tile providers
  • Steeper learning curve compared to Leaflet.draw

Code Comparison

Mapbox.js:

mapboxgl.accessToken = 'your-access-token';
var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/mapbox/streets-v11'
});

Leaflet.draw:

var map = L.map('map').setView([51.505, -0.09], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
    edit: { featureGroup: drawnItems }
});
map.addControl(drawControl);

The code comparison shows that mapbox.js requires an access token and uses a more concise setup, while Leaflet.draw offers more explicit control over map layers and drawing features. Mapbox.js provides a more streamlined approach for creating styled maps, whereas Leaflet.draw focuses on drawing and editing geometric shapes on the map.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

GitHub version npm version NPM Downloads Bower version Build Status Leaflet.draw Chat GitHub issues GitHub forks GitHub stars GitHub license

Leaflet.draw

Adds support for drawing and editing vectors and markers on Leaflet maps.

Supports Leaflet 0.7.x and 1.0.0+ branches.

Please check out our Api Documentation

Upgrading from Leaflet.draw 0.1

Leaflet.draw 0.2.0 changes a LOT of things from 0.1. Please see BREAKING CHANGES for how to upgrade.

In this readme

Customizing language and text in Leaflet.draw

Leaflet.draw uses the L.drawLocal configuration object to set any text used in the plugin. Customizing this will allow support for changing the text or supporting another language.

See Leaflet.draw.js for the default strings.

E.g.

    // Set the button title text for the polygon button
    L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a sexy polygon!';
    
    // Set the tooltip start text for the rectangle
    L.drawLocal.draw.handlers.rectangle.tooltip.start = 'Not telling...';

Common tasks

The following examples outline some common tasks.

Example Leaflet.draw config

The following example will show you how to:

  1. Change the position of the control's toolbar.
  2. Customize the styles of a vector layer.
  3. Use a custom marker.
  4. Disable the delete functionality.
    var cloudmadeUrl = 'http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png',
        cloudmade = new L.TileLayer(cloudmadeUrl, {maxZoom: 18}),
        map = new L.Map('map', {layers: [cloudmade], center: new L.LatLng(-37.7772, 175.2756), zoom: 15 });
    
    var editableLayers = new L.FeatureGroup();
    map.addLayer(editableLayers);
    
    var MyCustomMarker = L.Icon.extend({
        options: {
            shadowUrl: null,
            iconAnchor: new L.Point(12, 12),
            iconSize: new L.Point(24, 24),
            iconUrl: 'link/to/image.png'
        }
    });
    
    var options = {
        position: 'topright',
        draw: {
            polyline: {
                shapeOptions: {
                    color: '#f357a1',
                    weight: 10
                }
            },
            polygon: {
                allowIntersection: false, // Restricts shapes to simple polygons
                drawError: {
                    color: '#e1e100', // Color the shape will turn when intersects
                    message: '<strong>Oh snap!<strong> you can\'t draw that!' // Message that will show when intersect
                },
                shapeOptions: {
                    color: '#bada55'
                }
            },
            circle: false, // Turns off this drawing tool
            rectangle: {
                shapeOptions: {
                    clickable: false
                }
            },
            marker: {
                icon: new MyCustomMarker()
            }
        },
        edit: {
            featureGroup: editableLayers, //REQUIRED!!
            remove: false
        }
    };
    
    var drawControl = new L.Control.Draw(options);
    map.addControl(drawControl);
    
    map.on(L.Draw.Event.CREATED, function (e) {
        var type = e.layerType,
            layer = e.layer;
    
        if (type === 'marker') {
            layer.bindPopup('A popup!');
        }
    
        editableLayers.addLayer(layer);
    });

Changing a drawing handlers options

You can change a draw handlers options after initialisation by using the setDrawingOptions method on the Leaflet.draw control.

E.g. to change the colour of the rectangle:

drawControl.setDrawingOptions({
    rectangle: {
    	shapeOptions: {
        	color: '#0000FF'
        }
    }
});

Contributing

Testing

To test you can install the npm dependencies:

npm install

and then use:

jake test

Documentation

Documentation is build with Leafdoc, to generate the documentation use

jake docs

and the generated html documentation is saved to ./docs/leaflet-draw-latest.html

Thanks

Touch friendly version of Leaflet.draw was created by Michael Guild (https://github.com/michaelguild13).

The touch support was initiated due to a demand for it at National Geographic for their Map Maker Projected (http://mapmaker.education.nationalgeographic.com/) that was created by Michael Guild and Daniel Schep (https://github.com/dschep)

Thanks so much to @brunob, @tnightingale, and @shramov. I got a lot of ideas from their Leaflet plugins.

All the contributors and issue reporters of this plugin rock. Thanks for tidying up my mess and keeping the plugin on track.

The icons used for some of the toolbar buttons are either from http://glyphicons.com/ or inspired by them. <3 Glyphicons!

Finally, @mourner is the man! Thanks for dedicating so much of your time to create the gosh darn best JavaScript mapping library around.

NPM DownloadsLast 30 Days