cartodb/lib/assets/javascripts/cdb/examples/time_slider.html

104 lines
3.4 KiB
HTML
Raw Normal View History

2020-06-15 10:58:47 +08:00
<!DOCTYPE html>
<html>
<head>
<title>Time Slider | CartoDB.js</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<link rel="shortcut icon" href="http://cartodb.com/assets/favicon.ico" />
<style>
html, body, #map {
height: 100%;
padding: 0;
margin: 0;
}
#slider {
position: absolute;
bottom: 40px;
right: 40px;
left:40px;
}
#legend {
font-family: serif;
font-size: 27px;
position: absolute;
bottom: 80px;
left: 40px;
}
</style>
<link rel="stylesheet" href="https://libs.cartocdn.com/cartodb.js/v3/3.15/themes/css/cartodb.css" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
</head>
<body>
<div id="map"></div>
<div id="slider"></div>
<div id="legend"></div>
<!-- include cartodb.js library -->
<script src="https://libs.cartocdn.com/cartodb.js/v3/3.15/cartodb.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script>
function changeLegend(start, end) {
$('#legend').html("US post offices built " + new Date(start).getFullYear() + " - " + new Date(end).getFullYear())
}
function addTimeSlider(sublayer) {
var sql = cartodb.SQL({ user: 'documentation' })
// fetch time range
sql.execute('select max(built), min(built) from us_po_offices', function(data) {
var range = data.rows[0];
var max = new Date(range.max).getTime()
var min = new Date(range.min).getTime()
// update slider with range
$("#slider").slider({
range: true,
min: min,
max: max,
values: [ min , (min + max)/2 ],
slide: function(event, ui) {
// give feedback to the user on slide change
changeLegend(ui.values[0], ui.values[1]);
},
stop: function( event, ui ) {
// when user selects the dates, update the layer with the range
var start = new Date(ui.values[0]).toISOString()
var end = new Date(ui.values[1]).toISOString();
// build sql
sublayer.setSQL("select * from us_po_offices where built >= '" + start + "' and built <= '" + end + "'");
}
});
changeLegend(min, (min + max)/ 2);
});
}
function main() {
var map = new L.Map('map', {
zoomControl: false,
center: [36.66841891894786, -96.96533203125],
zoom: 5
});
L.tileLayer('http://{s}.api.cartocdn.com/base-light/{z}/{x}/{y}.png', {
attribution: 'CartoDB · OSM data'
}).addTo(map);
cartodb.createLayer(map, 'http://documentation.cartodb.com/api/v2/viz/d1e06c70-5dce-11e3-bda9-0e6bd0b8aae4/viz.json', { legends: false })
.addTo(map)
.on('done', function(layer) {
// add time slider on change
addTimeSlider(layer.getSubLayer(0));
}).on('error', function() {
cartodb.log.log("some error occurred");
});
}
// you could use $(window).load(main);
window.onload = main;
</script>
</body>
</html>