Coder Social home page Coder Social logo

leaflet / leaflet.draw Goto Github PK

View Code? Open in Web Editor NEW
1.9K 101.0 990.0 13.38 MB

Vector drawing and editing plugin for Leaflet

Home Page: https://leaflet.github.io/Leaflet.draw/docs/leaflet-draw-latest.html

License: MIT License

JavaScript 93.87% HTML 6.00% Shell 0.14%

leaflet.draw's Introduction

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.

leaflet.draw's People

Contributors

ajbeaven avatar boeckmt avatar boris-arkenaar avatar chugcup avatar danzel avatar davenquinn avatar davidepastore avatar ddproxy avatar e-avidan avatar frankrowe avatar iirvine avatar jacobtoye avatar jameslmilner avatar jmkelly avatar jonnyscholes avatar justinmanley avatar koppelbakje avatar larkinscott avatar leplatrem avatar michaelguild13 avatar mourner avatar nexushoratio avatar northerneyes avatar riboher avatar starefossen avatar tmcw avatar wattnpapa avatar yohanboniface avatar zakjan avatar zverik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

leaflet.draw's Issues

Trying to begin drawing new polygons over an existing polygon

Thanks for the great plug-in!

I recently upgraded to the latest master and the behaviour of the polygon drawing seems to have changed a little. You can no longer place new markers for polygons over an existing polygon. This introduces a little usability quirk in my application. We only allow users to draw one polygon at a time, the old shapes are removed once any new ones are completed.

Continue drawing

Are there any technical limitations within the leaflet framework which would prohibit a continue drawing feature?

Way to undo adding a vertex

For polylines & polygons it would be handy to be able to undo. This could be achieved via a key press (similar to cancel [ESC], maybe [CTRL+Z]) or by handling clicking on the vertex to remove.

Disable event fires before tool has cleaned up

When the tool is disabled, the disable event fires first and then the disable method is called.

In my case I want the polygon tool (enabled from a custom control) to remain active until the tool is toggled off. I'm listening for the disable event to fire so I can re-enable the tool, but since the previous polygon is never cleaned out I can't draw a new polygon because the tool thinks I'm continuing on the previous one.

Swapping the two lines in Handler.Draw.js fixes this for me.

Update shape feature

Hello,

Really great draw functionality support !

BTW, what about an 'update shape support' ?
It would be great to have a way for user to update an existing shape ? We could have a kind of 'Selector tool' which could then udpate shapes inside a LayerGroup (drawnItems layer group in library provided example)

May be this could be done in 3 steps process :

  1. the user click on a shape
  2. the shape shows 'anchor'
  3. the use drag'n'drop anchors to update the shape

Regards,

Bad reference to options in _disposeButton in Toolbar.js

Branch 0.2

The options object does not exist in the _disposeButton function in Toolbar.js:

_disposeButton: function (button) {
L.DomEvent
.off(button, 'click', L.DomEvent.stopPropagation)
.off(button, 'mousedown', L.DomEvent.stopPropagation)
.off(button, 'dblclick', L.DomEvent.stopPropagation)
.off(button, 'click', L.DomEvent.preventDefault)
.off(button, 'click', options.callback);
},

I think that you need something like

_disposeButton: function (button) {
L.DomEvent
.off(button, 'click', L.DomEvent.stopPropagation)
.off(button, 'mousedown', L.DomEvent.stopPropagation)
.off(button, 'dblclick', L.DomEvent.stopPropagation)
.off(button, 'click', L.DomEvent.preventDefault);
if (this.options.callback) {
L.DomEvent.off(button, 'click', this.options.callback);
}
},

destroy marker

Maybe you can suggest a good way to destroy all markers?
The desired behavior I'm after is when a user selects the draw box button, all existing boxes are destroyed, thus allowing only one box on the map at a time.

Polyline/polygon vertex markers useful?

Are these actually useful? For polylines the last marker is used to finish the line and for polygons the first marker. What about the rest of the markers.

Finding the first point when drawing a complex polygon can be confusing.

Marker can't be placed on the top of a polygon

  1. Draw a rectangle
  2. Try to place a marker inside the rectangle.

When the mouse is clicked, the marker is not "released". It's working fine if the marker is placed directly on the map. But doesn't work when placing the marker over the rectangle.

Ability to cancel drawing

Currently the user can press Esc to cancel drawing. Should also add a button that cancels as well. Could appear only when user has selected a drawing tool.

Making GeoJSON layers 'editable'

My use-case is an application that receives a GeoJSON feed of features, renders them on the map, and then the user can edit these features. I guess this is more of a question / looking for advice on best practice, sorry if this is not the best place to post, I could not find a mailing list, etc. so I'm assuming this is okay :-)

I currently accomplish this by using code that looks roughly like this:

$.getJSON(url, {}, function(feed) {
    var features = feed.features;
    features.forEach(function(feature) {
        var geometry = L.GeoJSON.geometryToLayer(feature.geometry);
        geometry.on("click", function(e) {
            e.target.editing.enable();
        });
        geometry.addTo(someLayerOnMap);
    });
});

This works, but is awkward, and I would much rather use a GeoJSON layer . However, I tried hooking into the onEachFeature callback to the layer to try and enable editing of features there, but had no luck.

Just wondering if there's something really basic I'm missing - I'm also really happy to work on this aspect / try to generalize editing of GeoJSON layers a bit if that's possible if anyone has any ideas. Thank you so much for a wonderful tool.

Possible bug fixed

If you create a rectangle you retrieve 5 coordinates but if you create a polygon with 4 vertex you retrieve only 4 coordiantes and that it is a problem if you use GeoJSON because with the rectangle works but with polygon doesn´t work.

Typo in onRemove function in Control.Draw.js

Branch 0.2

The variable tolbarId in the array index in

onRemove: function (map) {
    for (var toolbarId in this._toolbars) {
        this._toolbars[tolbarId].removeToolbar();
    }
},

should be toolbarId

Version

Hello,

I want to create a Drupal 7 Leaflet Draw input field. In this I want to use the libraries API (http://drupal.org/project/libraries). A requirement for this is a version string inside a file. Could you add a version to the readme or to one of the source files, so I can use the libraries API.

error internet explorer 8

Hi, in internet explorer 8, if you click in the "square icon" and then click on the "polygon icon" the browser throws an exception or simply dont draw polygon.

Message: 'this._shape' is null or is not an object
Line: 6
Character: 11567
Código: 0
URI: http://localhost:27131/js/leaflet/leaflet.draw.js

Thanks.

It will be cool that while you are creating a polygon you could redimension that poligon dragging over their vertex.

Edit existing shapes

Is there a way to edit existing shapes? For example, change the center and radius of an existing circle, add/remote points to/from a polyline, etc.?

Thanks!

Is it possible to style edit marker icons?

Is any way to change the style of the marker icons in a polyline when it is in edit mode?

When instantiating the drawControl I know that this it is possible:

var drawControl = new L.Control.Draw({
    polyline: {
        icon: new L.DivIcon({
            iconSize: new L.Point(10, 10),
            className: 'leaflet-div-icon leaflet-editing-icon my-own-class'
        })
    }
});

However this only applies to drawing and the style reverts back to the "default" when entering edit mode. The only solution for achieving this when editing is to override the leaflet-editing-icon css class which is kind of a dirty hack.

Am I missing something?

Add touch support

Methodology of drawing doesn't work at all for touch browsers :|

  • Polylines and ploygons: it is too hard to click on the close marker.
  • Rectangles and Markers:drawn by mousedown -> mousemove -> mouseup, this won't work on touch devices.

Update toolbar for Leaflet 0.5

I made some changes to before 0.5 release (probably tomorrow) so that common toolbar styles (used by zoom control) are extracted into separate classes. Please check it out and update the plugin if needed: Leaflet/Leaflet#1209

Possible to Use Drawing Functions Without the Control?

Hi,

Thanks for an awesome plugin.

Is it possible to, say, draw a rectangle without using the drawing control? We use our own controls to interact with the Leaflet map, and want to implement our own drawing toolbar.

For example, when you click the rectangle button in your implementation, the L.Handler.Draw.enable method is called, which looks like this:

enable: function() {
this.fire('activated');
this._map.fire('drawing', {drawingType: this.type});
L.Handler.prototype.enable.call(this);
}

I can already raise the map.drawing event, because I store a reference to the map. The this.fire() method is a little trickier, though. I assume the 'this' is a reference to the L.Handler.Draw object, so I'll need a reference to this object to call it from another class. Is it possible to get a reference to the current L.Handler.Draw object?

Thanks!

Aaron

Polyline edit events?

Would it be possible to add events to an editable polyline? Right now there is only the 'edit' event. It would be nice that the returned events let us know if a point has been moved, removed or added and at what index.

Similar to what google maps api has:

google.maps.event.addListener(GPS_Line.getPath(), 'remove_at', process_remove_at);
google.maps.event.addListener(GPS_Line.getPath(), 'set_at', process_set_at);
google.maps.event.addListener(GPS_Line.getPath(), 'insert_at', process_insert_at);

I need such a feature to update an array that has point attributes corresponding to the points of the polyline. Right now, I compare the lat/lon of each point between the new polyline and the array until I find the location of edit.

If this can already be accomplished with LL, let me know.

Thanks,

Nick,

Moved from Leaflet/Leaflet#1152 @nhinze

Enabling/customizing controls from outside the map

First of all, thank you very much for this plugin!

I'm quite new to leaflet, so I hope my question is relevant...
I need to build a user interface with several functions, allowing the user to add different kinds of markers, or to draw polylines.

I was wondering if it was possible to replace the drawControl by a custom-made toolbox ?
The idea would be to assign controls to specific DOM objects.
Exemple :
red polyline (activate Polyline.Draw)
green marker (activate Marker.Draw)
red marker (activate Marker.Draw)

Thanks :)

Inform user of key commands

Current there is a drawing tip that tells the user how to draw a shape. What is missing is information on cancelling and undoing.

Click and drag broken on Firefox and Leaflet 0.4

Environment:

http://jacobtoye.github.com/Leaflet.draw/
Firefox 15.0
Leaflet 0.4.4
Leaflet Draw 0.1

Expected behaviour:

Click and drag to draw a circle allows the creation of a circle.

Actual behaviour:

Click and drag to draw a circle picks up and drags a map tile.

Steps to reproduce:

  1. Navigate to http://jacobtoye.github.com/Leaflet.draw/ in Firefox
  2. Click the circle button
  3. Click and hold mouse to begin drawing circle
  4. Drag mouse to attempt to define circle size

Other information:

  • Works as expected on chrome.
  • The broken behaviour is only on the first attempt to click-and-drag. Subsequent attempts work as expected.
  • Click-and-click to define circle size works as expected.
  • Worked as expected with Firefox and Leaflet 0.3

How to make it AMD compatible

I am try to use requireJs to load it async and it doesn't load properly. Global "L" in leaflet-src isn't available by the time requireJs starts injecting leaflet.draw src.

wrapper class for leaflet-src
define(['../lib/leaflet/js/leaflet-src', '../lib/leaflet/js/leaflet.draw'], function () {
return {};
});

Widget - Select, remove and serialize features

Hey I've been working on a plugin that binds a Leaflet map to an HTML element (<input />, <textarea>, etc) and can read and write serialized GeoJSON features to and from the element. I am not sure what you have planned for Leaflet.draw but thought I'd bring this up here as aspects might potentially overlap.

The repository is here https://github.com/thegreat/Leaflet.widget.

I have developed with the intention of using it as wysiwyg-style input widget for a Drupal module but I figure it could be useful elsewhere too.

The plugin also comes with a 'select' control for selecting features. Selected features are managed by a handler and actions can be performed on the selected features. I have implemented a 'remove' action as an example but could see 'edit' (#31), 'group' and 'move' actions being useful.

The plugin is currently functional (will post a demo soon) but still pretty rough around the edges. There are also a few implementation aspects around layer management that feel a bit 'clunky' and I am not happy with. If you have time to review the code, I would greatly appreciate any feedback/insight you have.

Cheers,
Tom

(Sorry if I spammed you a little with updates, I accidentally submitted this a little early :P).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.