You have to set the cartodb_id
interactivity in your layer_source
variable:
var layerSource = {
user_name: 'examples',
type: 'cartodb',
sublayers: [{
sql: 'select * from country_boundaries',
cartocss: '#layer { polygon-fill: #F00; polygon-opacity: 0.3; line-color: #F00; }',
interactivity: ['cartodb_id', 'abbrev']
}]
}
Then you can update your infowindow_fields
as ['cartodb_id']
. The infowindow will show the cartodb_id
of the selected feature.
UPDATE: after realizing it was a problem of scope, this is the code that will work:
jQuery(function($) {
//default infowindow fields
var infowindow_fields = ['abbrev'];
// create leaflet map and define some properties
var map = L.map('map', {
zoomControl: false,
center: [43, 0],
zoom: 3
})
// add a base layer to map
L.tileLayer('http://tile.stamen.com/toner/{z}/{x}/{y}.png', {
attribution: 'Stamen'
}).addTo(map);
// Create button to change infowindow field on click
// Put layer data into a JS object
var layerSource = {
user_name: 'examples',
type: 'cartodb',
sublayers: [{
sql: 'select * from country_boundaries',
cartocss: '#layer { polygon-fill: #F00; polygon-opacity: 0.3; line-color: #F00; }',
interactivity: ['cartodb_id', 'abbrev']
}]
}
var options = { https: true }
// add cartodb layer with one sublayer
cartodb.createLayer(map, layerSource, options)
.addTo(map)
.done(function(layer) {
var sublayer = layer.getSubLayer(0);
console.log(sublayer);
cartodb.vis.Vis.addInfowindow(map, sublayer, infowindow_fields);
var createSelector = function() {
console.log(sublayer)
var $options = $(".layer_selector").find("li");
$options.click(function(e) {
var $li = $(e.target);
selected = $li.attr('data');
infowindow_fields[0] = selected;
console.log(infowindow_fields[0]);
sublayer.setInteraction(false);
sublayer.off();
sublayer.setInteractivity(selected);
cartodb.vis.Vis.addInfowindow(map, sublayer, infowindow_fields);
});
}();
});
});