Draw on 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
Here data is provided by OpenStreetMap
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
#map {
height: 400px;
}
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', {
maxZoom: 18
}).addTo(map);
// add a marker in the given location
L.marker(center).addTo(map);
var geojson = {"type":"MultiPolygon","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4326"}},"coordinates":[[[[46.709735944,13.381347656],[45.552525251,12.711181641],[45.259422036,14.183349609],[45.313529007,16.149902344],[46.301406154,16.754150391],[46.890231574,16.995849609],[47.144897486,16.160888672],[46.709735944,13.381347656]]]]}
var geoLayer = L.GeoJSON.geometryToLayer(geojson)
// Initialise the FeatureGroup to store editable layers
var editableLayers = new L.FeatureGroup();
map.addLayer(editableLayers);
editableLayers.addLayer(geoLayer)
// define custom marker
var MyCustomMarker = L.Icon.extend({
options: {
shadowUrl: null,
iconAnchor: new L.Point(12, 12),
iconSize: new L.Point(24, 24),
iconUrl: 'http://www.pdclipart.org/albums/Buildings/igloo.png'
}
});
var drawPluginOptions = {
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
}
},
},
edit: {
featureGroup: editableLayers, //REQUIRED!!
remove: false
}
};
// Initialise the draw control and pass it the FeatureGroup of editable layers
var drawControl = new...