Skip to content

Instantly share code, notes, and snippets.

@elenatorro
Created April 23, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elenatorro/52e6a73e67a94f04fbd3b893bc8aefab to your computer and use it in GitHub Desktop.
Save elenatorro/52e6a73e67a94f04fbd3b893bc8aefab to your computer and use it in GitHub Desktop.
viewportFeatures example
<!DOCTYPE html>
<html>
<head>
<title>Viewport Features Example | CARTO</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="UTF-8">
<script src="https://libs.cartocdn.com/carto-vl/v1.2.4/carto-vl.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.js"></script>
<link href="https://api.tiles.mapbox.com/mapbox-gl-js/v0.52.0/mapbox-gl.css" rel="stylesheet" />
<style>
html,
body {
margin: 0;
}
.toolbox {
position: absolute;
z-index: 2;
top: 30px;
right: 30px;
}
button {
border-radius: 5px;
border: 1px solid silver;
padding: 1em;
box-shadow: none;
font-size: 16px;
}
#map {
position: absolute;
width: 100%;
height: 100%;
z-index: 1;
}
</style>
</head>
<body>
<div id="map"></div>
<aside class="toolbox">
<div class="box">
<button id="change-color">Change Country Color</button>
</div>
</aside>
<div id="loader">
<div class="CDB-LoaderIcon CDB-LoaderIcon--big">
<svg class="CDB-LoaderIcon-spinner" viewBox="0 0 50 50">
<circle class="CDB-LoaderIcon-path" cx="25" cy="25" r="20" fill="none"></circle>
</svg>
</div>
</div>
<script>
const map = new mapboxgl.Map({
container: 'map',
style: carto.basemaps.voyager,
center: [0, 30],
zoom: 1.5,
scrollZoom: false
});
const nav = new mapboxgl.NavigationControl({
showCompass: false
});
map.addControl(nav, 'top-left');
// Define user
carto.setDefaultAuth({
username: 'cartovl',
apiKey: 'default_public'
});
// Define layer
const source = new carto.source.Dataset('world_borders');
const viz = new carto.Viz(`
@list: viewportFeatures($name)
color: opacity(BlueViolet, 0.5)
strokeColor: opacity(BlueViolet, 0.8)
`);
const layer = new carto.Layer('layer', source, viz);
layer.addTo(map, 'watername_ocean');
layer.on('loaded', hideLoader);
const changeColorButton$ = document.getElementById('change-color');
changeColorButton$.addEventListener('click', () => {
const features = viz.variables.list.value;
const featureSpain = features.find(feature => feature.properties.name === 'Spain');
if (featureSpain) {
featureSpain.color.blendTo('red');
}
});
function hideLoader() {
document.getElementById('loader').style.opacity = '0';
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment