Skip to content

Instantly share code, notes, and snippets.

@ramiroaznar
Created August 24, 2018 10:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ramiroaznar/fdd5fffbc834c55911803d2dfa9523a1 to your computer and use it in GitHub Desktop.
Save ramiroaznar/fdd5fffbc834c55911803d2dfa9523a1 to your computer and use it in GitHub Desktop.
Time Series widget with Chart.js and CARTO.js v4 dataviews
<!DOCTYPE html>
<html>
<head>
<title>Time Series widget | CARTO</title>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
<!-- Include Leaflet -->
<script src="https://unpkg.com/leaflet@1.3.1/dist/leaflet.js"></script>
<link href="https://unpkg.com/leaflet@1.3.1/dist/leaflet.css" rel="stylesheet">
<!-- Include CARTO.js -->
<script src="https://libs.cartocdn.com/carto.js/v4.1.2/carto.min.js"></script>
<!-- Include Chart.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js"></script>
<style>
body, *{ margin: 0; padding: 0; }
#map {
position: absolute;
top: 0;
height: 50%;
width: 100%;
z-index: 0;
}
#widget {
position: absolute;
bottom: 0;
height: 50% !important;
z-index: 1000;
}
</style>
</head>
<body>
<div id="map"></div>
<canvas id="widget"></canvas>
<script>
const map = L.map('map').setView([40, -95], 5);
map.scrollWheelZoom.disable();
L.tileLayer('https://{s}.basemaps.cartocdn.com/rastertiles/voyager_nolabels/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
const client = new carto.Client({
apiKey: 'default_public',
username: 'cartojs-test'
});
const source = new carto.source.Dataset('railroad_data');
const style = new carto.style.CartoCSS(`
#layer {
marker-width: 5;
marker-fill: ramp([total_damage], cartocolor(Sunset), quantiles(7));
marker-line-color: #FFFFFF;
marker-line-width: 0.3;
}
`);
const layer = new carto.layer.Layer(source, style);
client.addLayer(layer);
client.getLeafletLayer().addTo(map);
const timeseriesDataview = new carto.dataview.TimeSeries(source, 'date', {
aggregation: carto.dataview.timeAggregation.AUTO,
offset: 1
});
timeseriesDataview.on('dataChanged', data => {
console.log(data.bins);
dateWidget.data.labels = data.bins.map(function (x){
let dt = new Date(x.start);
return dt.getFullYear() + "/" + (dt.getMonth() + 1) + "/" + dt.getDate();
});
dateWidget.data.datasets.forEach((dataset) => {
dataset.data = data.bins.map(x => x.freq);
});
dateWidget.update();
});
timeseriesDataview.on('error', error => {
alert(error.message);
});
client.addDataview(timeseriesDataview);
const widgetElement = document.getElementById("widget").getContext('2d');
const dateWidget = new Chart(widgetElement, {
type: 'bar',
data: {
labels: [],
datasets: [{
label: 'Count by Date',
data: [],
borderWidth: 1
}]
},
options:{
responsive: true,
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment