You can bind custom functions to layer events by adding listeners and callbacks to the async portions of the CARTO.js library. Active layer events are triggered by layers on your webpage that are already loaded (Tip: these are the createLayer
and createVis
functions that return the done event. For details, see Loading Events). Each event requires the layer to include an interactivity layer. This is useful for integrating your website with your maps, adding events for mouseovers and click events.
Note: Be mindful of using these events, as these functions can get costly if you have a lot of features on a map.
Triggered when the user mouse hovers on any feature.
Name | Description |
---|---|
event | Browser mouse event object. |
latlng | Array with the LatLng ([lat,lng]) where the layer was clicked. |
pos | Object with x and y position in the DOM map element. |
data | The CARTO data of the clicked feature with the interactivity param. |
layerIndex | the layerIndex where the event happened. |
1
2
3
layer.on('featureOver', function(e, latlng, pos, data, subLayerIndex) {
console.log("mouse over polygon with data: " + data);
});
Triggered when the user hovers out any feature. For example, you might want to use this event if you highlight polygons on mouseover and need a way to know when to remove the highlighting after the mouse has left.
1
2
3
layer.on('featureOut', function(e, latlng, pos, data, layer) {
console.log("mouse left polygon with data: " + data);
});
Triggered when when the user clicks on a feature of a layer.
1
2
3
layer.on('featureClick', function(e, latlng, pos, data, layer) {
console.log("mouse clicked polygon with data: " + data);
});
Same as featureOver
.
Triggered when the mouse enters in any feature. Useful to change the cursor while hovering.
Triggered when the mouse leaves all the features. Useful to revert the cursor after hovering.
1
2
3
4
5
6
7
layer.on('mouseover', function() {
cursor.set('hand')
});
layer.on('mouseout', function() {
cursor.set('auto')
});
Triggered when the layer or any of its sublayers are about to be loaded. This is also triggered when any properties are changed but not yet visible.
1
2
3
4
5
6
layer.on("loading", function() {
console.log("layer about to load");
});
layer.getSubLayer(0).set({
cartocss: "#export { polygon-opacity: 0; }"
});
Triggered when the layer or its sublayers have been loaded. This is also triggered when any properties are changed and visible.
1
2
3
4
5
6
layer.on("load", function() {
console.log("layer loaded");
});
layer.getSubLayer(0).set({
cartocss: "#export { polygon-opacity: 0; }"
});
Same as layer.featureOver()
but sublayer specific.
Same as layer.featureOver()
.
Same as layer.featureClick()
but sublayer specific.
Same as layer.featureClick()
.
Same as layer.mouseover()
but sublayer specific.
Same as layer.mouseover()
but sublayer specific.