Inspired by this often cited question: https://gis.stackexchange.com/questions/211496/leaflet-draw-add-attributes-and-save-to-file I wanted to do something similar myself, but instead of creating a file for download, I'd like to save it on the server.
I've put something together and I get no errors in the console but the GeoJSON file on the server remains empty. Most likely I'm using the ajax wrong somehow.
I think the critical part of the code is this:
/*
=============================================================================
Open Editable Popup
=============================================================================
*/
map.on('draw:created', function (event) {
var layer = event.layer,
feature = layer.feature = layer.feature || {}; // Intialize layer.feature
feature.type = feature.type || "Feature"; // Intialize feature.type
var props = feature.properties = feature.properties || {}; // Intialize feature.properties
props.title = "my title";
props.content = "my content";
var idIW = L.popup();
var content = '<span><b>Name</b></span><br/><input id="shapeName" type="text"/><br/><br/><span><b>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();
};
/*
=============================================================================
Add Button to save the changes to GeoJSON
=============================================================================
*/
//button generated by the leaflet easy-button plugin. icon by font awesome - inclusion see html file
var saveButton = L.easyButton('fa-save', function(btn, map){
// Extract GeoJson from drawnItems
var data = drawnItems.toGeoJSON();
// Stringify the GeoJson
var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data));
$.ajax({
type: 'POST',
url: "data/markers.geojson", //url of receiver file on server
data: convertedData, //data container
success: function(data) {
alert(data);
}, //callback when ajax request finishes
dataType: "json"
});
}).addTo(map);
Note: this is a fictional map if that makes any difference. But I think at most it should result in wrong point coordinates for the markers, not a completely empty file. I post the whole code if you think it helps, but I did not want to make this too long and the rest is basically the code from a previous question https://gis.stackexchange.com/questions/360207/map-slightly-off-center-with-simple-cartesian-crs-and-tilelayer-in-leaflet plus the leaflet draw controls.