Thursday 22 August 2019

javascript - Can individual feature properties be retrieved from the CartoDB.js API?



I'm building an application that uses CartoDB to show users how a proposed redistricting plan would affect them. The user enters an address and that fires a ST_Intersects query to CartoDB, the result of which is always two polygons: one is the old ward, one is the proposed ward. Type "40 Bradley Street, Burlington, VT" into the search box to see how this works.


appscreen


I'd like to push answers to the indicated questions (e.g. "Where will my polling place be?") as well. However, this requires the ability to retrieve individual attribute values from the query results, and I can't figure out how to do this. Here is the structure I'm trying to use after running cartodb.createLayer();


var 1990ward = cartodbproperty.ward[1];
var 2010ward = cartodbproperty.ward[0];

if (1990ward == 2010ward) {
$('#wardchange').text("No. You will remain in ward " + 2010ward + " under the proposed plan.");
}
else {

$('#wardchange').text("Yes. You are currently in ward " + 1990ward + ", but you would be in ward " + 2010ward + " under the proposed plan.");
}

$('#distchange').text("The " + cartodbproperty.district + " District");
$('#pollchange').text(cartodbproperty.pollingplace);

The "cartodbproperty" variables are dummies because I can't figure out how I would use the cartodb.js API to select the "ward" attribute value of the query-result feature where "year" = 2010.


I believe I could pull this off with a parallel call to the SQL API - which could then be parsed as JSON - but that seems horribly inefficient. How can I get this data from the CartoDB.js API?


Thanks as always for the great toolset!



Answer




If I understand your question correctly, I think you are missing a few important bits. Right now you are doing,


cartodb.createLayer(map, {
user_name: 'geosprocket',
type: 'cartodb',
sublayers: [{
sql: "somesql",
cartocss: "somestyle"
}]
})


but you also need to tell it you want interaction,


cartodb.createLayer(map, {
user_name: 'geosprocket',
type: 'cartodb',
sublayers: [{
sql: "somesql",
cartocss: "somestyle",
interactivity: 'cartodb_id, column_2, column_3'
}]
})


Then, in your function, you can get at that data with the feature events. You can wire them up after adding your layers to the map, e.g.


.done(function(layer){
var sublayer = layer.getSubLayer(0);
sublayer.bind('featureOver', function(e, latlon, pxPos, data, layer) {
console.log(data.cartodb_id);
});
});

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...