Skip to content

Instantly share code, notes, and snippets.

@oriolbx
Created May 8, 2018 12:39
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/a48e8dc6b9424cad7f4fef8e853c1a35 to your computer and use it in GitHub Desktop.
Save oriolbx/a48e8dc6b9424cad7f4fef8e853c1a35 to your computer and use it in GitHub Desktop.
CARTO.js v4: Tile aggregation cluster of points
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0" />
<meta charset="utf-8" />
<!-- Include Carto.js -->
<script src="https://cartodb-libs.global.ssl.fastly.net/carto.js/v4.0.2/carto.min.js"></script>
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.2.0/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.2.0/dist/leaflet.css" rel="stylesheet" />
<style>
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
const map = L.map('map').setView([30, 0], 3);
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 *, 1 as count from stormevents_locations_2014
`);
// Aggregation option
const aggregation = new carto.layer.Aggregation({
threshold: 1,
resolution: 32,
placement: carto.layer.Aggregation.placement.SAMPLE,
columns: {
total_agg: {
aggregateFunction: carto.layer.Aggregation.operation.SUM,
aggregatedColumn: "count"
}
}
});
// define CartoCSS code to style data on map
const style = new carto.style.CartoCSS(`
#layer {
marker-fill: red;
marker-width: ramp([total_agg], 5,20 , quantiles);
}
#layer::labels {
text-name: [total_agg];
text-face-name: 'DejaVu Sans Book';
text-size: 10;
text-fill: #FFFFFF;
text-label-position-tolerance: 0;
text-halo-radius: 1;
text-halo-fill: #6F808D;
text-allow-overlap: true;
text-placement: point;
text-placement-type: dummy;
}
`);
// create CARTO layer from source and style variables
// and defining the interactivity of columns
// when featureOver and featureClick events are executed
const cartolayer = new carto.layer.Layer(source, style, { aggregation });
// add CARTO layer to the client
client.addLayer(cartolayer);
// get tile 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