This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Leaflet plugin: Leaflet.draw


With Leaflet's draw plugin, you can give your users the power to draw their own points, lines, and polygon shapes on the map. After all, why should you do all the work?

Start with a map using Leaflet 0.6 (currently it's the dev version).

Add the CSS, JS, and spritesheet image for the Leaflet.draw plugin. You can download these from the dist folder on  GitHub and upload them to your own server, or use the ones I uploaded on http://mapmeld.appspot.com/leaflet.draw.js and http://mapmeld.appspot.com/leaflet.draw.css  If you are using jsFiddle, it should be easy. Just click on 'External Resources', paste in each URL, and then click the + button to add it.

To add a draw toolbar, just revise the line where you create a map using L.Map:

map = new L.Map('mymap', {drawControl: true});
 

Check it out: http://jsfiddle.net/8QHFe/348/

------------

 

Once you create an object, though, it doesn't stick around. How can you see when a user finishes drawing a shape, and add it to the map permanently?

Add this code after you've created the map:

 

map.on('draw:created', function (e) {
   map.addLayer( e.layer ); 
});

This tells the map to watch out for when the plugin's special "draw:created" event occurs. The object e gives this function information about the drawing. The property which we use here, e.layer, is a ready-to-use layer which we can add to the map with map.addLayer.  Another property, e.layerType, can be "marker" "polyline" "polygon" "rectangle" or "circle".

Try it: http://jsfiddle.net/8QHFe/349/

-----

You can also use this function to look at what points were selected, and to send a message to a server (look for hotels inside this area, add this park to the map, etc).  This is a sample program which uses alert( ) to show the latitude and longitude whenever someone creates a marker, the last item in the draw toolbar.

 

map.on('draw:created', function (e) {
    if(e.layerType == "marker"){
       map.addLayer( e.layer );
       pt = e.layer.getLatLng();
       alert( pt.lat + "," + pt.lng );
    }
});
 
The latitude and longitude have a lot of decimal places. After six decimal places, the location you're giving is so precise, that you can't detect it with GPS.  Let's make it a bit easier to read by using JavaScript's toFixed function for numbers.
 
map.on('draw:created', function (e) {
    if(e.layerType == "marker"){
       map.addLayer( e.layer );
       pt = e.layer.getLatLng();
       alert( pt.lat.toFixed(6) + "," + pt.lng.toFixed(6));
    }
});
 

 

Task Discussion