Time slider to move automatically using setInterval() - javascript

I am trying to make a Mapbox map that would show data chronologically for a given year, and I am trying to make the year be specified automatically in sequence.
However, I am having a problem using setInterval to move the time slider in the following script automatically, and it gives me a [object HTMLLabelElement] without the slider moving.
Am I setting the setInterval to the wrong function?
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.map-overlay {
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
position: absolute;
width: 25%;
top: 0;
left: 0;
padding: 10px;
}
.map-overlay .map-overlay-inner {
background-color: #fff;
box-shadow:0 1px 2px rgba(0, 0, 0, 0.20);
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
.map-overlay h2 {
line-height: 24px;
display: block;
margin: 0 0 10px;
}
.map-overlay input {
background-color: transparent;
display: inline-block;
width: 100%;
position: relative;
margin: 0;
cursor: ew-resize;
}
</style>
<div id='map'></div>
<div class='map-overlay top'>
<div class='map-overlay-inner'>
<h2>Tel-Aviv Cinemas 1914-2016</h2>
<label id='Year'></label>
<input id='slider' type='range' min='0' max='102' step='1' value='0' />
</div>
<div class='map-overlay-inner'></div>
</div>
<script src="https://d3js.org/d3.v4.js"></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1Ijoia3Z5YiIsImEiOiJjaXUwMHEwcmgwMDAxMnlvM3NzMm0xbGozIn0.JL_eeNZL_lDoJxijNqFPoA';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/dark-v9',
center: [34.775981, 32.081287],
zoom: 11
});
var Years = ['1914', '1915', '1916', '1917', '1918', '1919', '1920', '1921', '1922', '1923', '1924', '1925', '1926', '1927', '1928', '1929', '1930', '1931', '1932', '1933', '1934', '1935', '1936', '1937', '1938', '1939', '1940', '1941', '1942', '1943', '1944', '1945', '1946', '1947', '1948', '1949', '1950', '1951', '1952', '1953', '1954', '1955', '1956', '1957', '1958', '1959', '1960', '1961', '1962', '1963', '1964', '1965', '1966', '1967', '1968', '1969', '1970', '1971', '1972', '1973', '1974', '1975', '1976', '1977', '1978', '1979', '1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987', '1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'];
function filterBy(Year) {
var filters = ['==', 'Year', Year];
map.setFilter('cinema-circles', filters);
map.setFilter('cinema-labels', filters);
// Set the label to the Year
document.getElementById('Year').textContent = Year;
}
map.on('load', function() {
// Data courtesy of https://earthquake.usgs.gov/
// Query for significant earthquakes in 2015 URL request looked like this:
// https://earthquake.usgs.gov/fdsnws/event/1/query
// ?format=geojson
// &starttime=2015-01-01
// &endtime=2015-12-31
// &minmagnitude=6'
//
// Here we're using d3 to help us make the ajax request but you can use
// Any request method (library or otherwise) you wish.
d3.json('https://cldex.net/visual/cinema_telaviv.geojson', function(err, data) {
if (err) throw err;
// Create a Year property value based on time
// used to filter against.
data.features = data.features.map(function(d) {
return d;
});
map.addSource('cinemas', {
'type': 'geojson',
'data': data
});
map.addLayer({
'id': 'cinema-circles',
'type': 'circle',
'source': 'cinemas',
'paint': {
'circle-color': {
property: 'sqrt',
stops: [
[0, '#f1f075'],
[1500, '#e55e5e']
]
},
'circle-opacity': 0.75,
'circle-radius': 20
}
});
map.addLayer({
'id': 'cinema-labels',
'type': 'symbol',
'source': 'cinemas',
'layout': {
'text-field': '{Cinema}',
'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
'text-size': 12
},
'paint': {
'text-color': 'rgba(0,0,0,0.5)'
}
});
// Set filter to first Year of the Year
// 0 = 1914
filterBy(1914);
document.getElementById('slider').addEventListener('input', function(e) {
var Year = window.setInterval(function() { parseInt(Years[e.target.value]) }, 1000);
filterBy(Year);
});
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mousemove', function(e) {
var features = map.queryRenderedFeatures(e.point, { layers: ['cinema-circles'] });
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = (features.length) ? 'pointer' : '';
if (!features.length) {
popup.remove();
return;
}
var feature = features[0];
// Populate the popup and set its coordinates
// based on the feature found.
popup.setLngLat(feature.geometry.coordinates)
.setHTML(feature.properties.Cinema+'<b> Cinema Information</b>'+'<br><b>Number: </b>'+feature.properties.Number+'<br><b>Number of Screens: </b>'+feature.properties.Screens+'<br><b>Number of Seats: </b>'+feature.properties.Seatss)
.addTo(map);
});
});
});
</script>
</body>
</html>
My Data can be found in a geojson: https://cldex.net/visual/cinema_telaviv.geojson

Your usage of setInterval is incorrect currently, and you have a few syntax errors.
Where you currently have this:
var Year = set.Interval(function() { parseInt(Years[e.target.value] }, 1000);
Try this instead:
var Year = window.setInterval(function() { parseInt(Years[e.target.value]) }, 1000);
You may still have some issues elsewhere, but I was having difficulty getting your data endpoint parsing correctly in d3. It may help to post up a codepen or something of this to get more help if you need it.
Edit:
I've created a codepen from your current setup, which may help you to tinker around a little easier: http://codepen.io/anon/pen/EZjKqM
As you can see I've made a few more changes, such as adding something to increment through the array of years which uses your filterBy function. It doesn't work perfectly, but you can see how it's parsing the data correctly and changing the year by the second.
This is achieved by using the following JS:
// Automatically cycle through years.
var yearSlider = document.getElementById('slider');
var curYearIndex = -1;
function advanceYear() {
++curYearIndex;
if (curYearIndex >= years.length) {
curYearIndex = 0;
}
return years[curYearIndex];
}
var cycleYears = window.setInterval(function() {
var currentYear = advanceYear();
filterBy(parseInt(currentYear));
}, 1000);
Unfortunately this is probably as far as I'll get with this, as I've other things to work on, but it perhaps gives you a bit of a starting point.

#Wakeuphate, this is an awesome solution (up-voted accordingly). I was able to implement quickly for my project.
It seems the missing item was moving the slider as well. I was able to achieve this by simply adding the following line:
document.getElementById('slider').value = currentYear;
So that the full function looks like:
var cycleYears = window.setInterval(function() {
var currentYear = advanceYear();
filterBy(parseInt(currentYear));
document.getElementById('slider').value = currentYear;
}, 1000);

Related

Adjust the zoom scale in Cytoscape.js trigered by the mouse wheel

I am using Cytoscape.js, to draw a Graph.
The problem is I want to adjust the zooming scale that the zoom event receives which the mouse wheel triggers.
Now when I scroll forward or backward the zoom increases or decreases more than expected... resulting in a bad user experience...
I couldn't find in the docs how to achieve or set this scale values...
I know that the wheel sensitivity is configurable but is not recommended to set.
Is there any way to establish how to scale in each wheel scroll?
The property you're looking for is wheelSensitivity. Adjust his value to change the zooming scale. Be careful with it because it can sometimes affect the render.
I put it at 0.4 in the example below:
<!DOCTYPE>
<html>
<head>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>
<style>
body {
font-family: helvetica;
font-size: 14px;
}
#cy {
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
z-index: 999;
}
h1 {
opacity: 0.5;
font-size: 1em;
}
</style>
<script>
window.addEventListener('DOMContentLoaded', function(){
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
boxSelectionEnabled: false,
autounselectify: true,
wheelSensitivity: 0.4,
style: [
{
selector: 'node',
style: {
'background-color': '#11479e'
}
},
],
elements: {
nodes: [
{ data: { id: 'n0' } },
{ data: { id: 'n1' } },
{ data: { id: 'n2' } },
],
edges: [
{ data: { source: 'n0', target: 'n1' } },
{ data: { source: 'n1', target: 'n2' } },
{ data: { source: 'n0', target: 'n2' } }
]
}
});
});
</script>
</head>
<body>
<div id="cy"></div>
</body>
</html>
You can use the cy.minZoom() and cy.maxZoom() to set the values. The zoom levels shall be maintained between this range on mouse and touch zoom. My example below is to set zoom on click event
cy.on("click","node",function(event) {
cy.minZoom(0.5)
cy.maxZoom(2.5)

The graph fly out of screen when the child number per node is greater than 5

I learned cytoscape.js and related extension some days and tried its many amazing features.
I find that when the number of children is greater than 5 and expand a node, the whole graph fly out of screen.
I constructed more complex data which own 3 parent nodes and 5 child nodes per parent node. There is a connection between any two child nodes.
So there are 3 parent nodes, 15 children nodes and 14+13+12..1 links.
To sum up, when there are more links, the layout behavior looks abnormal.
See my demo below.
You can modify parameters of my function getInitData() to see the effect.
document.addEventListener('DOMContentLoaded', function(){
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
ready: function(){
var api = this.expandCollapse({
layoutBy: {
name: "cose-bilkent",
animate: 'end',
randomize: false,
fit: false,
idealEdgeLength : 150
},
fisheye: false,
animate: true,
undoable: false
});
api.collapseAll();
},
style: [
{
selector: 'node',
style: {
'background-color': '#ad1a66'
}
},
{
selector: ':parent',
style: {
'background-opacity': 0.333
}
},
{
selector: "node.cy-expand-collapse-collapsed-node",
style: {
"background-color": "darkblue",
"shape": "rectangle"
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ad1a66'
}
},
{
selector: 'edge.meta',
style: {
'width': 2,
'line-color': 'red'
}
},
{
selector: ':selected',
style: {
"border-width": 3,
"border-color": '#DAA520'
}
}
],
elements : getInitData(3, 5)
});
var api = cy.expandCollapse('get');
var elements = null;
});
function getInitData(parentNum, childrenNum){
var data = [], children = [], i, j, n;
for(i = 0; i < parentNum; i++){
n = "parent"+i;
data.push({"group":'nodes',data:{"id":n}});
for(j = 0; j < childrenNum; j++){
children.push({"group":'nodes',data:{"id":n+"_child_"+j, parent:n}});
}
}
var s,t;
for(i = 0; i < children.length - 1; i++){
s = children[i].data.id;
for(j = i+1; j < children.length; j++){
t = children[j].data.id;
data.push({"group":'edges',data:{"id":s+"_"+t, source:s, target:t}});
}
}
return data.concat(children);
}
body {
font-family: helvetica neue, helvetica, liberation sans, arial, sans-serif;
font-size: 14px;
}
#cy {
z-index: 999;
width: 100%;
height: 100%;
}
h1 {
opacity: 0.5;
font-size: 1em;
font-weight: bold;
}
<script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://unpkg.com/cytoscape#3.1.0/dist/cytoscape.min.js"></script>
<!-- for testing with local version of cytoscape.js -->
<!--<script src="../cytoscape.js/build/cytoscape.js"></script>-->
<script src="https://unpkg.com/cytoscape-cose-bilkent#4.0.0/cytoscape-cose-bilkent.js"></script>
<script src="https://unpkg.com/cytoscape-expand-collapse#3.1.1/cytoscape-expand-collapse.js"></script>
<div id="cy"></div>
Solution one:
Your graph doesn't have any fitting logic. You can implement that yourself with the two methods cy.center(), which centers the graph to the current viewport and cy.fit(), which zooms the graph to the right position. You would have to call these mehtods everytime you change your graph, e.g. when you add a node, remove a node or, like in your case, expand and collapse. You can do that by binding these events and calling the said methods there.
Binding, as you know from the last question works like this:
cy.unbind('event');
cy.bind('event', 'target', function (event) {...});
Solution two:
You can alternatively, if possible (not all layouts can do this), set the method to fit: true,, which fits the graph with cy.fit(); and cy.center(); internally.
Additional problem and solution for that:
You said, that your graph looks bad when you only have one node in it, so to circumvent that, you can set the padding property of 'cose-bilkent' to a higher number. You can do that at the initialization in the options.
document.addEventListener('DOMContentLoaded', function() {
var padding = 10;
var cy = window.cy = cytoscape({
container: document.getElementById('cy'),
layout: {
name: 'cose-bilkent',
animate: false,
randomize: true
},
style: [{
selector: 'node',
style: {
'background-color': '#ad1a66'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ad1a66'
}
}
],
elements: [{
"data": {
"id": "glyph9"
}
}]
});
document.getElementById("add").addEventListener("click", function() {
padding += 10;
var layout = cy.layout({
name: 'cose-bilkent',
animate: false,
padding: padding
});
layout.run();
});
});
body {
font: 14px helvetica neue, helvetica, arial, sans-serif;
}
#cy {
height: 90%;
width: 100%;
position: absolute;
float: left;
}
button {
margin-right: 10px;
}
<!DOCTYPE>
<html>
<head>
<title>cytoscape-cose-bilkent.js demo</title>
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">
<script src="https://code.jquery.com/jquery-2.0.3.min.js"></script>
<script src="https://unpkg.com/cytoscape#3.1.0/dist/cytoscape.min.js"></script>
<!-- for testing with local version of cytoscape.js -->
<!--<script src="../cytoscape.js/build/cytoscape.js"></script>-->
<script src="https://unpkg.com/cytoscape-cose-bilkent#4.0.0/cytoscape-cose-bilkent.js"></script>
<script src="https://unpkg.com/cytoscape-expand-collapse#3.1.1/cytoscape-expand-collapse.js"></script>
</head>
<body>
<button id="add" type="button">Add padding</button>
<div id="cy"></div>
</body>
</html>

Uncaught TypeError: Cannot read property 'addPoint' of undefined ( Highstock live data)

As I posted a previous question, I am using Highcharts to consume a REST API (Spring app) (http://85614a50.ngrok.io/api/devices) with 2 series (axes)
The first series is memory vs time, so the object contains (Memory usage, timestamp).
The second series is CPU vs time, so the object contains (CPU Usage, timestamp).
This data is static right now, but I want it to be dynamic.
I created a function which does a call to the REST API every 5 seconds and an event function inside the Chart refreshing every 5 seconds.
I tried to declare variables inside the event function with series, but it gives me this error:
Uncaught TypeError: Cannot read property 'addPoint' of undefined
Code Pen example: https://codepen.io/anon/pen/eLEyGb
Home.blade.php
#extends('index.app')
#section('main')
<style type="text/css">
#container{
width: 100%;
margin: 0 auto;
}
.col-lg-4 {
margin-bottom: 10%;
min-width: 40%;
max-width: 100%;
margin: 1em auto;
height: 400px;
}
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 10%; /* Location of the box */
padding-right: 10%;
padding-left: 10%;
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
#container.modal{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background: rgba(0, 0, 0, 0.5);
display:block;
}
</style>
<h2 class="text-center" >{{$user->first_name}} Charts </h2>
<div id="container">
<div class="row"></div>
</div>
<script type="text/javascript">
$(function () {
setInterval(getHighChart, 10000); //30 seconds onload="getHighChart()"
});
function getHighChart() {
$.getJSON( "http://localhost:8000/api/devices", function( data ) {
console.log(data);
var mappedClientsAllias = _.map(_.uniqBy(data, "clientName"), "clientAllias");
var mappedClients = _.map(_.uniqBy(data, "Id_client"), "Id_client");
var devices= [];
_.forEach(mappedClients, function(Id_client, clientName) {
var tempClient = {
Allias: mappedClientsAllias[clientName],
name: Id_client,
data: [],
memory:[]
};
tempClient2=tempClient;
_.forEach(data, function(tempData) {
if (clientId === tempData.clientId) {
_.forEach(tempData.clientData, function(clientData) {
tempClient.data.push([
clientData.timestamp,
clientData.cpuUsage,
]);
tempClient.memory.push([
clientData.timestamp,
clientData.memoryUsage,
]);
});
}
});
devices.push(tempClient);
});
console.log("devices", devices);
var chart = _.forEach(devices, function(device) {
$('<div class="col-lg-4">')
.css("position", "relative")
.appendTo("#container")
.highcharts("StockChart", {
marker: {
states: {
enabled: true
}
},
time: {
timezoneOffset: -5 * 60
},
exporting: {
buttons: {
customButton3: {
text: 'Zooming',
//make fullscreen of chart with size change
onclick: function(b) {
var w = $(window).width();
var h = $(window).height();
$(b.target).closest('#container').toggleClass('modal');
if($(b.target).closest('#container').hasClass('modal')) {
$('.col-lg-4').hide();
$(b.target).closest('.col-lg-4').show();
$('.col-lg-4').css({
'width': w * .9,
'height': h * .9
});
} else {
$('.col-lg-4').show();
$('.col-lg-4').css({
'width': '',
'height': ''
});
}
$(b.target).closest('.col-lg-4').highcharts().reflow();
}
}
}
},
rangeSelector: {
y: 15,
buttons: [
{
count: 1,
type: "minute",
text: "Sec"
},
{
count: 1,
type: "hour",
text: "Min"
},
{
count: 1,
type: "day",
text: "Hours"
},
{
type: "all",
text: "All"
}
],
title: "hours",
inputEnabled: true,
_selected: 1
},
title: {
text: device.Allias
},
yAxis: [{
labels: {
enabled: true,
align: 'right',
x: -3
},
title: {
text: 'CPU'
},
height: '50%',
lineWidth: 2,
color: 'red'
}, {
labels: {
align: 'right',
x: -3
},
title: {
text: 'Memory'
},
top: '70%',
height: '50%',
offset: 0,
lineWidth: 2,
}],
xAxis: {
tickInterval: 1,
title: {
enabled: true,
text: "Client usage"
},
top: '20%',
type: "datetime",
dateTimeLabelFormats: {
second: "%H:%M:%S",
minute: "%H:%M",
hour: "%H:%M",
day: "%e. %b",
week: "%e. %b",
day: "%Y.%b-%d"
}
},
plotOptions: {
series: {
marker: {
enabled: false,
}
}
},
series: [{
name: "Memory USAGE",
data: device.memory.sort()
}, // Add a new series
{
name: "Cpu USAGE",
yAxis: 1,
color: 'red',
data: device.data.sort()
}],
chart: {
renderTo: "container",
height:400,
events: {
load: function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime(), // current time
y = Math.round(Math.random() * 100);
series.addPoint([x, y], false, true);
}, 1000);
}
}
},
});
});
});
}
</script>
#endsection
Layouts.app
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Master thesis application</title>
<!-- Jquery -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<!-- Import css file-->
<link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css"/>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
</head>
<body>
#include('file.hed')
#include('file.bar')
<script>
window.onscroll = function() {myFunction()};
var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;
function myFunction() {
if (window.pageYOffset >= sticky) {
navbar.classList.add("sticky")
} else {
navbar.classList.remove("sticky");
}
}
</script>
<div class="container">
#include('file.info')
#yield('main')
</div> <!-- /container -->
#include('file.down')
</body>
</html>
You've got the error because of this part of code:
events: {
load: function (series) {
var memory=client.memory.sort();
setInterval(function () {
var x = memory;
series[0].addPoint([x], true, true);
}, 5000);
}
}
There you are passing the series argument to event function, which actually isn't the series. It's just the event. If you want to refer to the series array, please do it like below:
events: {
load: function () {
var memory = client.memory.sort(),
series = this.series;
setInterval(function () {
var x = memory;
series[0].addPoint([x], true, true);
}, 5000);
}
}
BTW. I don't quite understand why you are adding the new chart every 5 seconds, instead of updating old ones.
Live example: https://codepen.io/anon/pen/oPGYoZ

Create a Year property value based on year field in json

I am working with this example: https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/
And I am trying to make this code:
// Create a Year property value based on time
// used to filter against.
data.features = data.features.map(function(d) {
d.properties.Year = new Date(d.properties.Year).getYear();
return d;
});
Work with my json file which does not have a date datatype as a field, but simply a Year value.
Like in the example below:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [ 34.7615574,32.0638934 ]
},
"properties": {
"Cinema":"אביב",
"Number of Records":"1",
"Number":1,
"Screens":1,
"Seatss":0,
"Year":1948
}
},
I need this code to return a value that can be used for my filter by year slider.
I am new to D3 and Mapbox, so any suggestion would be greatly appreciated.
Here is the full code that I am trying to use:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.29.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.map-overlay {
font: 12px/20px 'Helvetica Neue', Arial, Helvetica, sans-serif;
position: absolute;
width: 25%;
top: 0;
left: 0;
padding: 10px;
}
.map-overlay .map-overlay-inner {
background-color: #fff;
box-shadow:0 1px 2px rgba(0, 0, 0, 0.20);
border-radius: 3px;
padding: 10px;
margin-bottom: 10px;
}
.map-overlay h2 {
line-height: 24px;
display: block;
margin: 0 0 10px;
}
.map-overlay input {
background-color: transparent;
display: inline-block;
width: 100%;
position: relative;
margin: 0;
cursor: ew-resize;
}
</style>
<div id='map'></div>
<div class='map-overlay top'>
<div class='map-overlay-inner'>
<h2>Cinema Tel-Aviv</h2>
<label id='Year'></label>
<input id='slider' type='range' min='0' max='101' step='1' value='0' />
</div>
<div class='map-overlay-inner'></div>
</div>
<script src="https://d3js.org/d3.v4.js"></script>
<script>
mapboxgl.accessToken = 'pk.eyJ1Ijoia3Z5YiIsImEiOiJjaXUwMHEwcmgwMDAxMnlvM3NzMm0xbGozIn0.JL_eeNZL_lDoJxijNqFPoA';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/light-v9',
center: [31.4606, 20.7927],
zoom: 0.5
});
var Years = ['1914', '1915', '1916', '1917', '1918', '1919', '1920', '1921', '1922', '1923', '1924', '1925', '1926', '1927', '1928', '1929', '1930', '1931', '1932', '1933', '1934', '1935', '1936', '1937', '1938', '1939', '1940', '1941', '1942', '1943', '1944', '1945', '1946', '1947', '1948', '1949', '1950', '1951', '1952', '1953', '1954', '1955', '1956', '1957', '1958', '1959', '1960', '1961', '1962', '1963', '1964', '1965', '1966', '1967', '1968', '1969', '1970', '1971', '1972', '1973', '1974', '1975', '1976', '1977', '1978', '1979', '1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987', '1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995', '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016'];
function filterBy(Year) {
var filters = ['==', 'Year', Year];
map.setFilter('cinema-circles', filters);
map.setFilter('cinema-labels', filters);
// Set the label to the Year
document.getElementById('Year').textContent = Years[Year];
}
map.on('load', function() {
// Data courtesy of https://earthquake.usgs.gov/
// Query for significant earthquakes in 2015 URL request looked like this:
// https://earthquake.usgs.gov/fdsnws/event/1/query
// ?format=geojson
// &starttime=2015-01-01
// &endtime=2015-12-31
// &minmagnitude=6'
//
// Here we're using d3 to help us make the ajax request but you can use
// Any request method (library or otherwise) you wish.
d3.json('https://cldex.net/visual/cinema_telaviv.geojson', function(err, data) {
if (err) throw err;
// Create a Year property value based on time
// used to filter against.
data.features = data.features.map(function(d) {
d.properties.Year = new Date(d.properties.Year).getYear();
return d;
});
console.log(data.features.Year)
map.addSource('cinemas', {
'type': 'geojson',
'data': data
});
map.addLayer({
'id': 'cinema-circles',
'type': 'circle',
'source': 'cinemas',
'paint': {
'circle-color': '#FCA107',
'circle-opacity': 0.75,
'circle-radius': 20
}
});
map.addLayer({
'id': 'cinema-labels',
'type': 'symbol',
'source': 'cinemas',
'layout': {
'text-field': '{Cinema}',
'text-font': ['Open Sans Bold', 'Arial Unicode MS Bold'],
'text-size': 12
},
'paint': {
'text-color': 'rgba(0,0,0,0.5)'
}
});
// Set filter to first Year of the Year
// 0 = 1914
filterBy(0);
document.getElementById('slider').addEventListener('input', function(e) {
var Year = parseInt(e.target.value, 101);
filterBy(Year);
});
});
});
</script>
</body>
</html>
The map filter is expecting the year value and getting something else.
The year can be parsed in the slider event.
var Year = parseInt(Years[e.target.value]);
The filter function is updated to handle the parsed year.
function filterBy(Year) {
var filters = ['==', 'Year', Year];
map.setFilter('cinema-circles', filters);
map.setFilter('cinema-labels', filters);
// Set the label to the Year
document.getElementById('Year').textContent = Year;
}
The json is left as-is
data.features = data.features.map(function(d) {
return d;
});
Initial year is updated.
filterBy(1914);
Also:
Because getYear() does not return full years ("year 2000 problem"), it is no longer used and has been replaced by the getFullYear() method.
plnkr: http://plnkr.co/edit/QhWXHUmkSApyfynpmGzN?p=preview

javascript or jquery function for deleting graph using onclick event

I have used rickshaw library for plotting graphs. In that the legend part is there. I have also used button on the legend to delete graph. That means when I click on close button the respected graph should get deleted. But I am unable to do this. Is there any JavaScript or jQuery function to do this? Please help me finding the solution for this. Onclick event.. JavaScript function for deletion of graph
This is my code for plotting graph using rickshaw library...
<html>
<head>
<title>Sample-Rickshaw example</title>
<link type="text/css" rel="stylesheet" href="rickshaw.min.css">
<script src="vendor/d3.min.js"></script>
<script src="vendor/d3.layout.min.js"></script>
<script src="rickshaw.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
// CSS part
<style>
#chart_container {
position: relative;
display: inline-block;
font-family: Arial, Helvetica, sans-serif;
}
#chart {
display: inline-block;
margin-left: 40px;
}
#y_axis {
position: absolute;
top: 0;
bottom: 0;
width: 40px;
}
#legend {
display: oneline-block;
vertical-align: top;
margin: 0 0 0 10px;
}
#close_box {
btn_size:large;
font-family: Verdana, Geneva, sans-serif;
font-size:small ; font-weight: bold;
float: right; color: #666;
display: block; text-decoration: none;
border: 2px solid #666;
padding: 0px 3px 0px 3px;
}
</style>
// actual code
<body>
<div id="chart_container">
<div id="y_axis"></div>
<div id="chart"></div>
</div>
</head>
<div id="chart">
</div>
<div id="legend">
<FORM>
<INPUT type="button" value="x" onclick="remove graph">Remove Graph
</FORM>
</div>
// script for plotting data//
<script>
var palette = new Rickshaw.Color.Palette();
var graph = new Rickshaw.Graph( {
element: document.querySelector("#chart"),
width: 550,
height: 250,
series: [
{
name: "Northeast",
data: [ { x: -1893456000, y: 25868573 }, { x: -1577923200, y: 29662053 }, { x: -1262304000, y: 34427091 }, { x: -946771200, y: 35976777 }, { x: -631152000, y: 39477986 }, { x: -315619200, y: 44677819 }, { x: 0, y: 49040703 }, { x: 315532800, y: 49135283 }, { x: 631152000, y: 50809229 }, { x: 946684800, y: 53594378 }, { x: 1262304000, y: 55317240 } ],
color: palette.color(),
}
]
} );
var x_axis = new Rickshaw.Graph.Axis.Time( { graph: graph } );
var y_axis = new Rickshaw.Graph.Axis.Y( {
graph: graph,
orientation: 'left',
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis'),
} );
var legend = new Rickshaw.Graph.Legend( {
element: document.querySelector('#legend'),
graph: graph
} );
graph.render();
// jquery function
$('#legend').on('click','.button',function(e){
$(this).remove(graph);
e.preventdefault
});
/*
$('#legend').on('click', function(e){
$('#legend').remove(); // or do something else
e.preventDefault();
}
*/
</script>
//Html tags
</body>
</html>
This is my whole code for plotting graph and respected legend.. commented part in the code is for deletion part.Is there any JavaScript or jQuery function to do this? Please help me finding the solution for this. Onclick event.. JavaScript function for deletion of graph`
The JavaScript error console complains about multiple things in your code. Perhaps take some time to find your errors yourself before you implement my changes. Always have the error console open when you are coding something in JavaScript!
To get your code working:
In the onclick-attribute something in JavaScript is expected. Instead of:
<!-- this is invalid, not a method call, not an initialization, in onclick ... -->
<INPUT type="button" value="x" onclick="remove graph">Remove Graph
put
<input type="button" value="x" onclick="removegraph()" />Remove Graph
Notice that I also ended the tag with />. Pay attention that all the tags are closed correctly!
When I analyzed the elements on the website, I noticed that the graph isn't printed in the graph div, but uses the chart_container. To change this behavior I edited the parameters of the graph:
var graph = new Rickshaw.Graph( {
element: $("#chart")[0], // I changed this line because this was obviously not working
width: 550,
height: 250,
series: [{
name: "Northeast",
data: [ { x: -1893456000, y: 25868573 }, { x: -1577923200, y: 29662053 }, { x: -1262304000, y: 34427091 }, { x: -946771200, y: 35976777 }, { x: -631152000, y: 39477986 }, { x: -315619200, y: 44677819 }, { x: 0, y: 49040703 }, { x: 315532800, y: 49135283 }, { x: 631152000, y: 50809229 }, { x: 946684800, y: 53594378 }, { x: 1262304000, y: 55317240 } ],
color: palette.color()
}]
});
Replace your method
// jquery function
$('#legend').on('click','.button',function(e){
$(this).remove(graph);
e.preventdefault // this line throws an error, because there is no ; and it is not a method-call nor an initialization or anything
});
with
// we've defined before, that this method is called when you click on the button X
function removegraph()
{
$("#chart").remove() ;
// uncomment the following lines, if you want to remove also the chart_container and the legend
// $("#chart_container").remove() ;
// $("#legend").remove() ;
}
Also pay attention that you open and close the tags in the correct order, for example:
<html>
<head>
</head>
<body>
</body>
</html>
This isn't correct in your code.

Categories

Resources