Leaflet draw add name and save to file
Leaflet draw: easy and simle way to add name/description to created features and save to file
by falqn
HTML
<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css">
<script src="https://leaflet.github.io/Leaflet.draw/leaflet.draw.js"></script>
<link rel="stylesheet" href="https://leaflet.github.io/Leaflet.draw/leaflet.draw.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://lizardtechblog.github.io/Leaflet.OpacityControls/lib/jquery/jquery-1.9.1.js"></script>
<link rel="stylesheet" href="https://lizardtechblog.github.io/Leaflet.OpacityControls/lib/jquery/jquery-ui-1.10.3.custom.min.css">
<script src="https://lizardtechblog.github.io/Leaflet.OpacityControls/lib/jquery/jquery-ui-1.10.3.custom.min.js"></script>
<div id="map"></div>
<a href='#' id='export'>Export Features</a>
CSS
#map {
height: 500px;
width: 90%;
}
#export {
position: absolute;
top: 20px;
left: 50px;
background: yellow;
color: black;
padding: 6px;
border-radius: 4px;
font-size: 16px;
text-decoration: none;
}
JavaScript
var osm = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
});
var map = L.map('map').setView([19.04469, 72.9258], 12).addLayer(osm);
//Leaflet.draw
var drawnItems = L.featureGroup().addTo(map);
var drawControl = new L.Control.Draw({
draw: {
circle: false,
rectangle: false,
polyline: false,
polygon: false
},
edit: {
featureGroup: drawnItems
}
}).addTo(map);
map.on('draw:created', function(e) {
var type = e.layerType;
var layer = e.layer;
var idIW = L.popup();
var content = '<span><b>Shape Name</b></span><br/><input id="shapeName" type="text"/><br/><br/><span><b>Shape Description<b/></span><br/><textarea id="shapeDesc" cols="25" rows="5"></textarea><br/><br/><input type="button" id="okBtn" value="Save" onclick="saveIdIW()"/>';
idIW.setContent(content);
idIW.setLatLng(layer.getLatLng());
idIW.openOn(map);
drawnItems.addLayer(layer)
});
function saveIdIW() {
var sName = $('#shapeName').val();
var sDesc = $('#shapeDesc').val();
var drawings = drawnItems.getLayers(); //drawnItems is a container for the drawn objects
drawings[drawings.length - 1].title = sName;
drawings[drawings.length - 1].content = sDesc;
map.closePopup();
};
//Export
document.getElementById('export').onclick = function(e) {
// Extract GeoJson from featureGroup
var data = drawnItems.toGeoJSON();
// Stringify the GeoJson
var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
// Create export
document.getElementById('export').setAttribute('href', 'data:' + convertedData);
document.getElementById('export').setAttribute('download', 'drawnItems.geojson');
}