Skip to content

Instantly share code, notes, and snippets.

@oriolbx
Created February 11, 2020 08:35
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 oriolbx/b693884b8bb307415e533517379e4dd0 to your computer and use it in GitHub Desktop.
Save oriolbx/b693884b8bb307415e533517379e4dd0 to your computer and use it in GitHub Desktop.
CARTO.js v4: Change zoom level when click on geometry
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width">
<!-- Include Carto.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.2.0/carto.min.js"></script>
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.5.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.5.1/dist/leaflet.css" rel="stylesheet">
<style>
#map {
width: 100%;
height: 100vh;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = L.map('map').setView([41.38, 2.18], 11);
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
// define client
const client = new carto.Client({
apiKey: 'default_public',
username: 'oboix'
});
// define source of data using a SQL query
const source = new carto.source.SQL(`
SELECT * FROM districtes_barcelona
`);
// define CartoCSS code to style data on map
const style = new carto.style.CartoCSS(`
#layer{
polygon-fill: tomato;
}
`);
// create CARTO layer from source and style variables
const cartoLayer = new carto.layer.Layer(source, style, {
featureClickColumns: ['cartodb_id']
});
// when feature is clicked, change zoom to level 13
cartoLayer.on('featureClicked', function (featureEvent) {
let polygon_selected = featureEvent.data.cartodb_id;
map.setView(featureEvent.latLng, 13)
})
// add CARTO layer to the client
client.addLayer(cartoLayer);
// get tiles from client and add them to the map object
client.getLeafletLayer().addTo(map);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment