Draw polygons on a map with Leaflet.js and leaflet.draw
Leaflet is an an open-source JavaScript library for mobile-friendly interactive maps http://leafletjs.com/ Leaflet.draw is a leaflet plugin for drawing on a map. Leaflet.draw code is from: https://github.com/Leaflet/Leaflet.draw https://github.com/Leaflet/Leaflet.draw Map data is provided by OpenStreetMap
by Chris Bao
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0-beta.2.rc.2/leaflet.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet.draw/0.2.3/leaflet.draw.css">
<div id="map"></div>
CSS
html, body {
height: 100%;
}
#map {
height: 100%;
}
JavaScript
// center of the map
var center = [-33.8650, 151.2094];
// Create the map
var map = L.map('map').setView(center, 6);
// Set up the OSM layer
L.tileLayer(
'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
attribution: 'Data © <a href="http://osm.org/copyright">OpenStreetMap</a>',
maxZoom: 18
}).addTo(map);
// add a marker in the given location
L.marker(center).addTo(map);
/* // Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
var drawPluginOptions = {
position: 'topright',
draw: {
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: '#97009c'
}
},
// disable toolbar item by setting it to false
polyline: true,
circle: true, // Turns off this drawing tool
rectangle: true,
marker: true,
},
edit: {
featureGroup: editableLayers, //REQUIRED!!
remove: false
}
};
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new L.Control.Draw(drawPluginOptions);
map.addControl(drawControl); */
// FeatureGroup is to store editable layers
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
var drawControl = new L.Control.Draw({
draw: {
marker: false
},
edit: {
featureGroup: drawnItems
}
});
map.addControl(drawControl);
map.on('draw:created', function(e) {
console.log('11111', e.layer._latlngs)
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('A popup!');
}
map.addLayer(layer);
});