Created
June 21, 2013 11:39
-
-
Save andrewxhill/5830659 to your computer and use it in GitHub Desktop.
Leaflet.draw control for CartoDB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?