Skip to content

Instantly share code, notes, and snippets.

@andrewxhill
Created June 21, 2013 11:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewxhill/5830659 to your computer and use it in GitHub Desktop.
Save andrewxhill/5830659 to your computer and use it in GitHub Desktop.
Leaflet.draw control for CartoDB
function persistOnCartoDB(action,layers) {
var cartodb_ids=[];
var geojsons=[];
switch(action) {
case "UPDATE":
if(layers.getLayers().length<1)
return;
layers.eachLayer(function(layer) {
cartodb_ids.push(layer.cartodb_id);
geojsons.push("'"+JSON.stringify(layer.toGeoJSON())+"'");
});
break;
case "INSERT":
cartodb_ids.push(-1);
geojsons.push("'"+JSON.stringify(layers.toGeoJSON())+"'");
break;
case "DELETE":
layers.eachLayer(function(layer) {
cartodb_ids.push(layer.cartodb_id);
geojsons.push("''");
});
break;
}
var sql = "SELECT osm2_upsert_leaflet_data(ARRAY[";
sql += cartodb_ids.join(",");
sql += "],ARRAY[";
sql += geojsons.join(",");
sql += "]);";
console.log("persisting... " + sql );
$.ajax({
type: 'POST',
url: 'https://osm2.cartodb.com/api/v2/sql',
crossDomain: true,
data: {"q":sql},
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
console.log("Data saved");
if(action=="INSERT")
layers.cartodb_id = responseData.rows[0].cartodb_id;
},
error: function (responseData, textStatus, errorThrown) {
console.log("Problem saving the data");
}
});
}
@robertboensma
Copy link

Hi there, this works great, but there is an issue when you want to edit a drawn object without refreshing the page. It will give a "POST 400 (Bad Request)". I saw that it doesn't get the layer.cartodb_id when the page isn't refreshed first. Did you also receive these errors and do you maybe know a fix for this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment