受到这个经常被引用的问题的启发:https ://gis.stackexchange.com/questions/211496/leaflet-draw-add-attributes-and-save-to-file 我想做类似的事情,但不是创建一个文件为了下载,我想把它保存在服务器上。
我已经把一些东西放在一起,控制台中没有错误,但服务器上的 GeoJSON 文件仍然是空的。很可能我以某种方式错误地使用了ajax。
我认为代码的关键部分是:
/*
=============================================================================
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);
注意:这是一个虚构的地图,如果这有什么不同的话。但我认为它最多应该导致标记的点坐标错误,而不是一个完全空的文件。如果您认为有帮助,我会发布整个代码,但我不想让它太长,其余的基本上是上一个问题的代码https://gis.stackexchange.com/questions/360207/map-slightly- off-center-with-simple-cartesian-crs-and-tilelayer-in-leaflet加上传单绘制控件。