I have created a named map that gets data from a private table. I can load it into a Leaflet map and can change its marker-fill color placeholder using layer.setParams.
However, I cannot get interactivity to work. I want to be able to hover or click on a feature and do something useful.[1]
What do I need to do to make hover or click events fire?
Here is the named map json file
{
"version": "0.0.1",
"name": "mynamedmap",
"auth": {
"method": "open"
},
"placeholders": {
"color": {
"type":"css_color",
"default":"blue"
}
},
"layergroup": {
"version": "1.0.1",
"layers": [{
"type": "cartodb",
"options": {
"cartocss_version": "2.1.1",
"cartocss": "#layer { marker-fill: <%= color %>; }",
"sql": "select * from mytable",
"interactivity": ["cartodb_id"]
}
}]
}
}
Here is the javascript to create the layer:
cartodb.createLayer(map, {
type: 'namedmap',
user_name: 'myusername',
options: {
named_map: {
name: 'myusername@mynamedmap'
}
}})
.addTo(map)
.done(function(layer) {
console.log(layer.getSubLayerCount()); //prints '0'
layer.setParams('color', 'green'); // works to change marker color
layer.on('featureClick', function(e, latlng, pos, data) {
console.log(e, latlng, pos, data); //this never gets called
});
});
[1] "Something useful" could be as simple as open infowindow and display cartodb_id and feature name. Or it could mean "get cartodb_id for feature, pass it to my proxy where I can use curl to run some custom sql against my private table, then return json to the map and update display"
Answer
I feel a bit of an idiot for not figuring this out sooner. Here is the solution that worked for me.
Add the following line to the namedmap definition: layers: [{}]
The call to createLayer then looks like this:
cartodb.createLayer(this.map.baseMap, {
type: 'namedmap',
user_name: 'myusername',
options: {
named_map: {
name: namedMap.name,
layers: [{}]
})
.done(function (layer) {
var subLayer = layer.getSubLayer(0);
subLayer.setInteraction(true);
});
After doing so, you can add event handling like:
subLayer.on('featureOver', function(e, latlon, pos, data, subLayerIndex) {
console.log("hovered over");
console.log(data);
});
It would have been very helpful for me, as I have commented in another post on this forum, for more thorough documentation - a response there indicated that it is coming, which is great news, as CartoDb is fantastic.
No comments:
Post a Comment