How to Redraw HighChart After Dropdown Value is selected - javascript

I have a drop down menu called info and I want to update my highchart everytime a user selects a value through the info menu.
Here is the code:
$('#info').on('change', function() {
add_info(this.value);
});
The add_info() method simply gets data via ajax and this is how I am processing it after getting the response back:
if(chart=='stacked_chart'){
console.log(JSON.stringify(response));
var series = [{name:'Coached',data:[]},{name:'Non Coached',data:[],stack: 'yes'},{name:'Delta',data:[],stack: 'yes'}],
year, month, day;
for(var i=0; i<response.length;i++){
var d = response[i].date.split(",");
year = parseFloat(d[0]);
month = parseFloat(d[1])-1; //date.utc method starts month 0-11
day = parseFloat(d[2]);
var coached = +(parseFloat(response[i].coached).toFixed(3));
var non_coached = +(parseFloat (response[i].non_coached).toFixed(3));
var delta = +(parseFloat (response[i].delta).toFixed(3));
series[0].data.push([Date.UTC(year,month,day),coached]);
series[1].data.push([Date.UTC(year,month,day),non_coached]);
series[2].data.push([Date.UTC(year,month,day),delta]);
console.log(Date.UTC(year,month,day));
}
console.log(series);
if(series.length){
stacked_chart.userOptions.series = series;
var chart = new Highcharts.Chart(stacked_chart.userOptions);
console.log(chart.series[0].data[0].options);
console.log(chart.series[1].data[0].options);
console.log(chart.series[2].data[0].options);
}
}
I can see it brings back the new data but It doesn't redraw. I have looked at here but couldn't redraw the chart. Any ideas how to reset the chart every time a user selects a new value from the drop down?

Related

How to match up category labels with multiple series?

I'm working on a project to brush up on my JS, and I'm finding Highcharts rather challenging. What I've done is set up project that pulls in current JSON data from an API, and displays results on a map. When you click on a state, you can view the historical data for that state. if you shift click, you can view more than one state.
My x-axis is formatted with dates from each state, as not each state began tracking data at the same time. When multiple states are selected, the information is incorrect because even though they all have the same date for the most recent data point (today), the first data point in the date array varies. For instance, if you click New York, their first data point starts on 3/04, but if you click Connecticut, the first data point starts on 3/07.
Is there a way I can reconcile this? Can I have my categories start from the most recent data point and work backwards, so the data points for today are concurrent?
Here's my pen: https://codepen.io/maxpalmer/pen/rNVRzVX?editors=0010
Stackoverflow is requiring I post some code, so here is the function I wrote that reassembles the api data into an array for each state for the area chart:
for (i = 0; i < stateAbbrevs.length; i++){
var values = new Array(), categories = new Array();
// var categories = new Array();
var state = stateAbbrevs[i];
var stateObj = jsonData.filter(obj => obj.state == state);
for (x = 0; x < stateObj.length; x++) {
var value = stateObj[x].positive;
var date = formatDate(stateObj[x].date);
var name = stateNames[i];
values.push(value);
categories.push(date);
}
values.reverse();
categories.reverse();
historicData[state] = {
name: name,
data: values,
categories: categories
};
}
}```
Ah, found it in the myriad Highcharts documentation. Comes down to reversing my data array, and then reversing it in the highcharts x-axis options.
https://api.highcharts.com/highcharts/xAxis.reversed

Passing angular scope variable to javascript

I have angular scope variable which is being used in ng-repeat as well. I want to create a chart starting from a date and ending at a certain date with the current day marker. I am using javascript loader.js for drawing the charts but since I need to draw multiple charts inside ng-repeat.
My code looks like this:
$scope.items = [{"title1":"start_day: 01-01-2017", "end_day:15-02-2018"},
{"title2":"start_day: 05-10-2017", "end_day:10-01-2019"}];
and javascript code from google charts:
anychart.onDocumentReady(function () {
// create data tree on our data
var treeData = anychart.data.tree(getData());
// create resource gantt chart
var chart = anychart.ganttResource();
// set container id for the chart
chart.container('container');
// set data for the chart
chart.data(treeData);
// set start splitter position settings
chart.splitterPosition(150);
var now = (new Date()).getTime();
var sec = 1000;
var min = 60*sec;
var hour = 60*min;
var day = 24*hour;
// create linemarkers
var tl = chart.getTimeline();
tl.lineMarker(0).value("current");
// get chart data grid link to set column settings
var dataGrid = chart.dataGrid();
// initiate chart drawing
chart.draw();
// zoom chart to specified date
chart.fitAll();
});
function getData() {
var now = (new Date()).getTime();
var sec = 1000;
var min = 60*sec;
var hour = 60*min;
var day = 24*hour;
return [
{
"periods": [
{"id": "1_1", "start": now - 365*day, "end": now + 100*day }]
},
];
}
I want to pass the dates from angularjs scope variable to javascript code here which will replace the existing data of start and end, also I need to convert the dates difference.
Thanks in advance! :)
I would recommend to use another JS object that stores common data for both angular and js.
var DATES = [{"title1":"start_day: 01-01-2017", "end_day:15-02-2018"},
{"title2":"start_day: 05-10-2017", "end_day:10-01-2019"}];
...
//in agular
$scope.items = DATES;
...
//in loader
function getData() {
...
return DATES;
}
You can also store an angular $scope into a variable and then use it as a usual variable into JS code, var ctrl = $scope but I would recommend to go with the first option.
--
Regarding to dates difference. Try to use standard Date class.
For example:
var deltaMS = new Date("02-15-2018") - new Date("01-01-2017");
var deltaDays = delta / 1000 / 60/ 60 / 24;
//410 days

Make google chart work with large amounts of data

What I have done
I have added google charts to my page. The data is populated based on the date and duration the user selects. (The duration can be any amount of hours).
What I need to do
I need to ensure that the chart can accommodate the duration selected. By spacing the gant data and making the chart movable.
The problem
Is that I cannot get the chart to accomodate large sets of data without cramping the data. I need the data spaced out and thus make the chart movable (responsive) based on the amount of data searched for.
The Code
function drawChart() {
var data = [];
var header = ['Activity', 'Start Time', 'End Time'];
data.push(header);
for(var i =0; i < $scope.timelineArr.length;i++){
var year = $scope.timelineArr[i].thumbnail_date.substring(0,4);
var month = $scope.timelineArr[i].thumbnail_date.substring(5,7) -1;
var day = $scope.timelineArr[i].thumbnail_date.substring(8,10);
var hour = $scope.timelineArr[i].thumbnail_time.substring(0,2);
var min = $scope.timelineArr[i].thumbnail_time.substring(3, 5);
console.log(year+ " "+month+ " "+day);
var tmp = [];
tmp.push(""+$scope.timelineArr[i].cam_name, new Date(year, month, day, hour, min), new Date(year, month, day, hour, min));
data.push(tmp);
}
$scope.data = google.visualization.arrayToDataTable(data);
var options = {
'legend':'left',
'title':'Camera Events',
'is3D':true,
tooltip: {
isHtml: true
},
'width':1000,
'height':400
}
$scope.chart = new google.visualization.Timeline(document.getElementById('chart_div'));
$scope.chart.draw($scope.data, options);
//////////
google.charts.load('current', {'packages':['timeline']});
google.charts.setOnLoadCallback(drawChart);
I also included what it looks like now.As you can see the data is cramped, imagine if I choose more hours. Thank you.
Is there a way to make the timeline ZOOMABLE?

Replace data set every min

I'm trying to have my Highstock chart update every minute, by replacing its existing data set with one that is extracted from a url request (which would have different data at different times).
So far I'm not even able to get the data to refresh based on manual changes.
Work so far: https://jsfiddle.net/Lz8gLw8j/
I'm trying to test changing data and then updating it with:
varData = [[0,0],[1,2]]
$('#chart2').highcharts().redraw();
Which does nothing.
You can set the new data to highchart in following way:
var newData = [
[1251763200000, 23.61],
[1251849600000, 23.60],
[1251936000000, 23.79]
]
var chart = $('#chart2').highcharts();
chart.series[0].setData(newData);
$('#chart2').highcharts().redraw();
Updated fiddler:
https://jsfiddle.net/Lz8gLw8j/5/
It looks like there is a load event that you can use
chart : {
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], true, true);
}, 1000);
}
}
}
Here's a fiddle: https://jsfiddle.net/jjwilly16/Lz8gLw8j/6/
FYI: I pulled this from an example off of the Highcharts website: http://jsfiddle.net/gh/get/jquery/1.9.1/highslide-software/highcharts.com/tree/master/samples/stock/demo/dynamic-update/
You can add data to the existing series using the addPoint method and replace the dataset using the setData method. The second option argument for both of the methods allows you to redraw the chart. The data should be an array of arrays. The nested array contains the actual data that is plotted. The first elements of the inner, nested array is the epoch (x) while the second is the actual value (y). The epoch is the number of seconds since January 1, 1970 Midnight GMT/UTC. I have updated the fiddle to allow you to add data points as well as reset the data.
The main change are these lines:
$('#updateButton').click(function() {
var date = $('#newDate').val();
var epoch = Math.round(new Date(date).getTime());
var value = parseInt($('#newValue').val());
var chart = $('#chart2').highcharts();
chart.series[0].addPoint([epoch, value], true);
});
$('#resetChart').click(function() {
var chart = $('#chart2').highcharts();
chart.series[0].setData(null, true);
});
https://jsfiddle.net/Lz8gLw8j/7/

Open Layers 3 get geojson data from specific time date?

I'm trying to figure out the best approach to fetch data from a geojson file by date. Each feature point has a time parameter and I need to show the points in the map that match a specific date and time.
I also have a date select picker which will show the points in the map based on the date selected.
Any ideas? This is how I envision the code process would look like:
// 1. Geojson data:
{ 'type':'FeatureCollection',
'crs': {...},
'features': {
'type': 'Feature',
'geometry': {...},
'properties': {
'reportStartTime': '2015-12-04T00:55:00Z',
'id': '3421',
...
}
}
}
// 2. Get current date
var now = new Date(new Date());
var hour = now.getHours();
var nextHour = hour + 1; // I need to know when the next hour starts
var hourDiff = // I need to get the hours from 00:00 to 00:59min
// 3. Show points in the map that match the current date
function fetchData(feature, timeSelected) {
var reportStartTime = feature.get('reportStartTime');
if(reportStartTime == timeSelected){
return // Show the map points
}
}
fetchData(feature, hourDiff);
// 4. Filter date picker (using bootstrap date picker)
var newTimeSelected = $('#datetimepicker1').find('input').val(); // i.e returns 12/10/2015 11:57 AM
// 5. Change the map points that match the date selected from the date picker
$('button').submit(function() {
fetchData(feature, newTimeSelected);
});

Categories

Resources