Created
October 24, 2018 08:02
-
-
Save VictorVelarde/389915ad36b59e7beb38d7fab9d5b7a9 to your computer and use it in GitHub Desktop.
[CARTO VL - viewportFeatures]
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="utf-8"> | |
<script src="../dist/carto-vl.js"></script> | |
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.js'></script> | |
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.50.0/mapbox-gl.css' rel='stylesheet' /> | |
<link rel="stylesheet" type="text/css" href="../examples/style.css"> | |
</head> | |
<body> | |
<div id="map"></div> | |
<script> | |
// Add basemap and set properties | |
const map = new mapboxgl.Map({ | |
container: 'map', | |
style: carto.basemaps.voyager, | |
center: [0, 30], | |
zoom: 2 | |
}); | |
// Add zoom controls | |
const nav = new mapboxgl.NavigationControl(); | |
map.addControl(nav, 'top-left'); | |
//** CARTO VL functionality begins here **// | |
// LAYER EVENTS & VARIABLES | |
// Add layer as usual | |
carto.setDefaultAuth({ username: 'cartovl', apiKey: 'default_public' }); | |
const source = new carto.source.Dataset('populated_places'); | |
// Viz using a dynamic variable | |
const viz = new carto.Viz(` | |
@name: $name | |
@popK: $pop_max / 1000.0 | |
@pop_min: $pop_min | |
@v_viewportFeatures: viewportFeatures($name, @pop_min) | |
filter: $pop_max > globalPercentile($pop_max, 99) | |
`); | |
const layer = new carto.Layer('Cities', source, viz); | |
layer.addTo(map); | |
// 1) viewportFeatures | |
const citiesInViewport = () => { | |
const features = viz.variables.v_viewportFeatures.value; | |
// console.log(`Now you can see ${features.length} cities`); | |
}; | |
layer.on('updated', citiesInViewport); | |
// 2) features in carto.Interactivity | |
const interactivity = new carto.Interactivity(layer); | |
interactivity.on('featureClick', featureEvent => { | |
featureEvent.features.forEach((feature) => { | |
const name = feature.variables.name.value; | |
const popK = feature.variables.popK.value.toFixed(0); | |
console.log(`You have clicked on ${name} with a population of ${popK}K`); | |
}); | |
}); | |
// Change style on 'featureEnter' | |
interactivity.on('featureEnter', featureEvent => { | |
featureEvent.features.forEach((feature) => { | |
feature.color.blendTo('rgba(0, 255, 0, 0.8)', 100); | |
feature.width.blendTo(20, 100); | |
}); | |
}); | |
// Reset to previous style on 'featureLeave' | |
interactivity.on('featureLeave', featureEvent => { | |
featureEvent.features.forEach((feature) => { | |
feature.color.reset(); | |
feature.width.reset(); | |
}); | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment