How to set responsive for google charts in mvc - asp.net-mvc

<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
$(document).ready(function () {
google.setOnLoadCallback(drawChartCountry);
$("a[href='#tab11']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartCountry
});
});
$("a[href='#tab21']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartDevice
});
});
$("a[href='#tab31']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartVersion
});
});
function drawChartCountry() {
$.post('/AppDashboard/GetCountryChart', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Country');
tdata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart_country'));
chart.draw(tdata, options);
});
}
function drawChartDevice() {
$.post('/AppDashboard/GetDeviceChart', {},
function (data) {
var devicedata = new google.visualization.DataTable();
devicedata.addColumn('string', 'Device');
devicedata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
devicedata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-device'));
chart.draw(devicedata, options);
});
}
function drawChartVersion() {
$.post('/AppDashboard/GetVersionChart', {},
function (data) {
var versiondata = new google.visualization.DataTable();
versiondata.addColumn('string', 'Version');
versiondata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
versiondata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-version'));
chart.draw(versiondata, options);
});
}
});
I have set google chart inside a widget but the sad part is responsive is not working.When i resize it to mobile size the chart data exceeds my widget.Kindly help me with this and if you need more info lemme know,thanks in advance :)

Related

Highcharts low performance when adding yAxis dynamically

I am trying to add/delete yAxis dynamically but I observe performance issues. It takes more than a second (sometimes it goes upto 4 seconds) to dynamically add or remove a series into a new yAxis. I need to load end of day data (price point for each day) for 10 or more years in the chart.
Any advice in improving the performance will be much appreciated.
Few points to note -
I can use different type of charts (line, ohlc, candlestick, area etc.)
I need mouse tracking to be enabled as I am using click events on the series.
User will have option to either choose to apply data grouping or to not.
Below is my code sample to illustrate the problem.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation:false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
renderTo:'container'
},
navigator: {
outlineColor: '#0066DD',
outlineWidth: 1
},
xAxis: [{
gridLineWidth: 1,
gridLineColor: "#eaf5ff",
lineColor: '#FF0000',
lineWidth: 1
}],
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false);
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData);
updateAxisHeight();
index++;
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(){
var i=0;
$("#axisList > option").each(function() {
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 });
i++;
});
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>
You can significantly improve the performance in this case with one trick: when performing several consecutive operations that each require a redraw (add series, add axis, update axis height), don't redraw until you've told Highcharts about all the operations.
On my machine, this improves the performance of your add axis function by 5x-6x. See code and comments below.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
console.time("chart load");
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation: false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
alignTicks: false,
events: {
load: function () {
console.timeEnd("chart load");
}
},
renderTo:'container'
},
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var startTime = new Date().getTime();
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false, false); // don't redraw yet
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData, false); // don't redraw yet
updateAxisHeight(false); // don't redraw yet
index++;
// finally, redraw now
chart.redraw();
var endTime = new Date().getTime();
console.log("add axis took " + (endTime - startTime) + " msec");
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(redraw){
// set redraw to true by default, like Highcharts does
if (typeof redraw === 'undefined') {
redraw = true;
}
var i=0;
$("#axisList > option").each(function() {
// don't redraw in every iteration
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 }, false);
i++;
});
// redraw if caller asked to, or if the redraw parameter was not specified
if (redraw) {
chart.redraw();
}
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>

when mouseover or out change icon marker

What i want is when user do mouseover (hover) then the icon change. My code is below:
handler = Gmaps.build("Google", {
markers: {
maxRandomDistance: null
}
});
handler.buildMap({
provider: {},
internal: {
id: "map-canvas"
}
}, function() {
var markers;
markers = handler.addMarkers(ar);
_.each(ar, function(json, index) {
json.marker = markers[index];
$(".location-" + json.id).on("mouseover", function() {
json.picture = {
url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
width: 36,
height: 36
};
json.marker.setMap(handler.getMap());
json.marker.panTo();
handler.removeMarker(json.marker);
handler.addMarker(json);
}).on("mouseout", function() {
json.picture = '';
handler.removeMarker(json.marker);
handler.addMarker(json);
});
});
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
Using this code, the color of the marker can change from red to green. However, when the user remove their mouse from the hover area, the color does not change back to the original color. Please can anyone suggest me on this issue?
Thanks
Hai thank for #apneadiving answer. I modify my code to this
hoverPicture = {
url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
width: 33,
height: 33
};
handler = Gmaps.build("Google", {
markers: {
maxRandomDistance: null
}
});
handler.buildMap({
provider: {},
internal: {
id: "map-canvas"
}
}, function() {
var markers;
markers = handler.addMarkers(ar);
_.each(ar, function(json, index) {
var gr;
json.marker = markers[index];
gr = {};
gr.marker = void 0;
$(".location-" + json.id).on("mouseover", function() {
gr = {
lat: json.lat,
lng: json.lng,
picture: hoverPicture
};
json.marker.panTo();
handler.removeMarker(json.marker);
gr.marker = handler.addMarker(gr);
}).on("mouseout", function() {
handler.removeMarker(gr.marker);
json.marker = handler.addMarker(json);
});
});
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
So the new icon need to insert to variable after addMarker
Try something like:
_.each(ar, function(json, index) {
var json.marker = markers[index];
var initialPicture = json.picture;
var hoverPicture = {
url: "http://maps.google.com/mapfiles/ms/icons/green-dot.png",
width: 36,
height: 36
}
$(".location-" + json.id).on("mouseover", function() {
json.picture = hoverPicture;
json.marker.setMap(handler.getMap());
json.marker.panTo();
handler.removeMarker(json.marker);
handler.addMarker(json);
}).on("mouseout", function() {
json.picture = initialPicture;
handler.removeMarker(json.marker);
var newMarker = handler.addMarker(json);
json.marker = newMarker;
});
});

Hi I am trying to push the run time values that i am getting from the odata services through ajax calls to the highcharts

Following is the code that I have developed:
<body>
<div id="container"></div>
</body>
$(function(){
var options = {
chart: {
renderTo: 'container',
type: 'line'
},
xAxis: {
categories: [],
labels: {
y: 20,
rotation: -45,
align: 'right'
}
},
series: []
};
var oDataUrlEntity = serviceUrl;
$.ajax({
type: "GET",
dataType: "json",
url: oDataUrlEntity,
username: "xxxx",
password: "xxxx",
async: false,
cache: false,
timeout: 5000,
error: function(jqXHR, textStatus, errorThrown) {
debugger;
},
success: function(data, textStatus, jqXHR) {
debugger;
data_poRequest = {
rootNode: []
};
for (var i = 0; i < data.d.results.length; i++) {
var obj = data.d.results[i];
data_poRequest.rootNode.push({
key1: obj.fieldName1,
key2: obj.fieldName2
});
}
for (var i = 0; i < data_poRequest.rootNode.length; i++) {
debugger;
options.xAxis.categories.push(data_poRequest.rootNode[i]['fieldName']);
series = {
data: []
};
series.data.push(data_poRequest.rootNode[0]);
options.series.push(series);
//
}
debugger;
chart = new Highcharts.Chart(options);
}
});
});
The problem is now on the highcharts I am getting only one value out of the 24 values in the cateogies array.Also only the legend is coming with 24 series.
Also,in the debugger i can see values inside options.xAxis.categories & also inside series.data,But they are not getting reflected on the Highcharts.
Could anyone help me with this.Thanks in advance.
The problem is that you are creating every time new series. Won't you have instead one series?
So change:
for (var i = 0; i < data_poRequest.rootNode.length; i++) {
debugger;
options.xAxis.categories.push(data_poRequest.rootNode[i]['fieldName']);
series = {
data: []
};
series.data.push(data_poRequest.rootNode[0]);
options.series.push(series);
//
}
To:
series = {
data: []
};
for (var i = 0; i < data_poRequest.rootNode.length; i++) {
options.xAxis.categories.push(data_poRequest.rootNode[i]['fieldName']);
series.data.push(data_poRequest.rootNode[0]);
}
options.series.push(series);

get instance of map in jquery ui map

i want to make the markers clustered with markerClusterer but i cannot get the map instance with jquery ui map . js
tried:
var map = $('#map_canvas').gmap('getMap');
or
var map = $('map_canvas').gmap('get', 'map');
and after:
var markerCluster = new MarkerClusterer(map, allMarkers);
but with errors
Thank you
Tried this . No Errors but no clusters...
$('#map_canvas').gmap({ 'callback': function () {
var self = this;
$.getJSON('Data/markers.json', function (data) {
$.each(data.markers, function (i, marker) {
self.addMarker({ 'position': new google.maps.LatLng(marker.latitude,marker.longitude)}).click(function () {
$.ajax({
type: "GET",
url: "/LocoMap/LocoMap/InfoMobilePartialView/",
data: { latitude: marker.latitude, longitude: marker.longitude},
success: function (data) {
$("#marker-info").remove();
$(document.body).append("<div id='marker-info' data-role ='page'> </div>");
var $contentDiv = $("#marker-info");
$contentDiv.html(data).trigger('create');
$.mobile.changePage("#marker-info", { changeHash: false, type: "get", transition: 'pop',rel:"external" });
},
error: function (errorData) { onError(errorData); }
});
});
});
});
self.set('MarkerClusterer', new MarkerClusterer(this.get('map'), this.get('markers')));
}});
$('#map_canvas').gmap({'zoom': 2, 'disableDefaultUI':true}).bind('init', function(evt, map) {
$.getJSON( 'Data/markers.json', function(data) {
$.each( data.markers, function(i, m)
$('#map_canvas').gmap('addMarker', { 'position': new google.maps.LatLng(m.latitude, m.longitude), 'bounds':true } );
});
});
$('#map_canvas').gmap('set', 'MarkerClusterer', new MarkerClusterer(map,$(this).gmap('get', 'markers')));
});
with no errors and no clusters
it seems **$(this).gmap('get', 'markers')));** returns Array[0]

Highchart duplicates data on chart instead of refreshing it

I am using the highcharts library to collect data from a csv file every 2 minutes and dispaly it in the graph.
Instead of refreshing the data, the function just duplicates the data and my browser ends up crashing. Can some one help ? i am running out of ideas. Below is my code. I have removed all the xAxis,Yaxis,legend from the code to make it shorter
<script type="text/javascript">
var chart;
var options = {
chart: {
renderTo: 'container',
defaultSeriesType: 'spline',
events: {
load: function() {
setInterval(function(){
refresh('file.csv');
}, 120000);
}
}
},
tooltip: {
valueSuffix: ' Views'
},
legend: {
layout: 'left'
},
series : []
};
function refresh(file) {
if(chart) chart.destroy();
$.get(file, function(data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var series = {
data: []
};
$.each(items, function(itemNo, item) {
if (itemNo == 0) {
series.name = item;
} else {
series.data.push(parseFloat(item));
}
});
options.series.push(series);
});
chart = new Highcharts.Chart(options);
});
}
$(document).ready(function() {
refresh('file.csv');
});
</script>
<div id="container"></div>
Instead of destroy chart, you can use setData / addSeries function which allows to manipulate data. http://api.highcharts.com/highcharts#Chart.addSeries
http://api.highcharts.com/highcharts#Series.setData

Resources