Draw a line chart dynamically using sql server database using highchart.js - c#

Not able to generate dynamic line chart with x-axis and series dynamically
I want month wise count for different destination.
I have done like this
function GetDestinationData() {
$.ajax({
async: false,
type: "POST",
url: "DataAnalysis.aspx/getDestination",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess1_,
error: OnErrorCall1_
});
}
function OnSuccess1_(response) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < response.d.length; i++) {
var items = response.d[i];
var XcategoreisItem = items.Month;
var seriesData = items;
if ($.inArray(XcategoreisItem, Xaxis) == -1) {
Xaxis.push(XcategoreisItem);
}
dataseries.push(seriesData);
// console.log(dataseries);
}
drawLineChart(Xaxis, dataseries);
}
function drawLineChart(Xaxis, dataseries) {
//categories = seriesData.map(function (a) { return a.x; });
//categories = categories.filter(function (v, i) { return categories.indexOf(v) == i; });
var chart = Highcharts.chart('container', {
chart: {
type: 'line',
//zoomType: 'xy',
//panning: true,
//panKey: 'shift'
},
//chart: {
// renderTo: 'container',
// type: 'line',
// marginRight: 130,
// marginBottom: 25
//},
title: {
text: 'Destination Count Month Wise'
},
plotOptions: {
series: {
dataLabels: {
enabled: true,
format: '{y}',
}
}
},
xAxis: {
categories: Xaxis
},
yAxis: {
labels: {
formatter: function () {
return this.value ;
}
},
plotLines: [{
//value: 0,
width: 1,
color: '#808080'
}]
},
series: [{
//name: 'Id',
data: dataseries
}],
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle'
},
});
for (var i = 0; i < dataseries.length; i++) {
//dataseries = dataseries.filter(function (e) {
// return e.Month == dataseries[i].Month
//}
//);
chart.addSeries({
name: dataseries[i].destination,
data: [dataseries[i].A1ResultCount]
});
//chart.series[i].setData(dataseries[i].data);
}
//chart.redraw();
}
Rendered Chart

Maybe consider using a web-component that handles dynamic data?
Using highcharts-chart you could do:
const chart = $('#Chart')[0]
function OnSuccess1_(response) {
var Xaxis = [];//skapa tre olika array
var dataseries = [];
for (var i = 0; i < response.d.length; i++) {
var items = response.d[i];
var XcategoreisItem = items.Month;
var seriesData = items;
if ($.inArray(XcategoreisItem, Xaxis) == -1) {
Xaxis.push(XcategoreisItem);
dataseries.push({name: items.month, data: items.data_maybe})
}
chart.data = dataseries
}
}
//Example Data
chart.xAxis = {categories: ['Jan','Feb','Mar','Apr','May','Jun']}
chart.data = [43,81,52,84,53,45]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="import" href="https://user-content-dot-custom-elements.appspot.com/avdaredevil/highcharts-chart/v2.0.1/highcharts-chart/highcharts-chart.html">
<highcharts-chart id='Chart' title='Destination Count Month Wise' type='line' y-label='Destinations' x-label='Month'></highcharts-chart>
Note: Click Run code snippet to see the chart
Edit:
As I was writing this answer, I also realized you were setting categories for a line series? You don't need categories, instead, you need multiple series itself, each with their own name corresponding to the month.

Related

google pie charts with label(change the color of line of labels)

I am new with Google pie charts. I want to change the style of label like line color of label match with the color of slice if slice is blue then line color should be blue.
And some slice are not showing its label like the yellow and purple slice.
var data3 = google.visualization.arrayToDataTable(ClaimSubmissionStatus);
var options = {
legend: { textStyle: { color: 'black', fontSize: 14 }, position: 'labeled', alignemnt: 'center' },
//is3D: true,
// legend: { position: 'labeled' },
chartArea: { backgroundColor: '#FFFFFF', left: '5%', top: '15', width: '85%' }
};
var charta = new google.visualization.PieChart(document.getElementById('divClaimSubmission'));
charta.draw(data3, options);
google.visualization.events.addListener(charta, 'select', function () {
debugger;
var selectedItem = charta.getSelection()[0];
if (selectedItem) {
var status = data3.getValue(selectedItem.row, 0);
CLAIMSUBMISSIONSTATUSPIECHARTDetail(status);
}
});
there is no documented option for changing the color of the legend marker line,
but you can change manually on the chart's 'ready' event
also, the only solution for ensuring a line exists for each slice is to increase the height of the chart
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Billed', 19],
['Paid Up', 9],
['Not Billed', 2],
['Ready for Review', 15],
['Not Paid Up', 1]
]);
var options = {
chartArea: {
left: 12,
top: 12,
width: '85%'
},
colors: ['#3366cc', '#dc3912', '#ff9900', '#109618', '#990099', '#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4caf50', '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107', '#ff9800', '#ff5722', '#795548', '#9e9e9e', '#607d8b', '#000000', '#ffffff'],
legend: {
position: 'labeled'
}
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.PieChart(container);
var drawCount = 0;
var drawMax = 100;
google.visualization.events.addListener(chart, 'ready', function () {
var observer = new MutationObserver(function () {
var svg = container.getElementsByTagName('svg');
if (svg.length > 0) {
var legend = getLegend(svg[0]);
// check number of markers
if (legend.length !== data.getNumberOfRows()) {
// increase height & redraw chart
options.height = parseFloat(svg[0].getAttribute('height')) + 32;
drawCount++;
if (drawCount < drawMax) {
chart.draw(data, options);
}
} else {
// change legend marker colors
var colorIndex = 0;
legend.forEach(function (legendMarker) {
legendMarker.path.setAttribute('stroke', options.colors[colorIndex]);
if (legendMarker.hasOwnProperty('circle')) {
legendMarker.circle.setAttribute('fill', options.colors[colorIndex]);
}
colorIndex++;
if (colorIndex > options.colors.length) {
colorIndex = 0;
}
});
}
}
});
observer.observe(container, {
childList: true,
subtree: true
});
});
// get array of legend markers -- {path: pathElement, circle: circleElement}
function getLegend(svg) {
var legend = [];
Array.prototype.forEach.call(svg.childNodes, function(child) {
var group = child.getElementsByTagName('g');
Array.prototype.forEach.call(group, function(subGroup) {
var path = subGroup.getElementsByTagName('path');
if (path.length > 0) {
if (path[0].getAttribute('fill') === 'none') {
var legendMarker = {
path: path[0]
};
var circle = subGroup.getElementsByTagName('circle');
if (circle.length > 0) {
legendMarker.circle = circle[0];
}
legend.push(legendMarker);
}
}
});
});
return legend;
}
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
notes:
1) need to use custom colors in order to keep the slice and line color in sync
2) a MutationObserver is required, the chart will revert on interactions, such as hover or select
3) manual changes will not be reflected when using chart method getImageURI

In hight chart how can i show yAxis value on xAxis?

.SetXAxis(new XAxis
{
Categories = xyzList.ToArray(),
Labels = new XAxisLabels
{
// Formatter = "function() { return this.labels; }",
Style = "color: 'Black',fontSize: '10px',fontFamily: 'Arial'",
UseHTML = true,
//formatter with image is
Formatter = "function() { return '<div class=\"ImageDiv\" style=\"height:25px; background-image:url(../../Themes/Images/'+ this.value+'.jpg)\"/>';}",
// Formatter = "function() { return this.y;}",
}
})
i want to display YAxis value in to xAsix but it shows undefined.
How can i access YAxis value on the XAXis?
The answer depends on data format you are using. Possible solution: http://jsfiddle.net/3bQne/1036/
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
xAxis: {
categories: ['01/02/2012', '01/03/2012', '01/04/2012', '01/05/2012', '01/06/2012', '01/07/2012'],
labels: {
formatter: function () {
var index = this.axis.categories.indexOf(this.value);
var points = this.axis.series[0].options.data;
return points[index];
}
}
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0]
}]
});

C# ASP.NET MVC Project and Google Maps: How to fill JavaScript array with values from C# List<>

I have a Class like this:
public class Markers
{
public double latitude { get; set; }
public double longitude { get; set; }
//Constructors and Methods
//(...)
}
On my Controller I have an ActionResult with a List of Markers and I add latitude and longitude like this
List<Markers> listM = new List<Markers>(); //NOTE: this is outside of my ActionResult, no problem with that.
//(...)
listM.Add(new Markers(value[0], value[1])); //NOTE: value[0] is my lat and value[1] is my longitude
//(...)
And at the end i return my list to the View:
return (listM);
Now on the View, I need to access the data and fill an array so I can display the markers on my google map.
How to fill the array with markers in position lat, long from my list?
#using ProjectName.Models
#model List<Markers>
<html>
<head>...</head>
<body>...</body>
<script type="text/javascript">
//How can I add a GoogleMap Marker ?
var markersArray = [];
#foreach(var item in Model)
{
//can't use google.maps.Marker inside this foreach =(
}
</script>
</html>
NOTE: This is how I add a marker on that array with a click on the map.
function addMarker(location) {
var marker = new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: location,
title: 'Bomb',
map: map,
icon: bomb
});
markersArray.push(marker);
}
Question 2:
Markers still doesn't show on map after #Leo Solution!
<script type="text/javascript">
var map;
var geocoder;
var markersArray = [];
var geoMarker;
var bomb = new google.maps.MarkerImage('Content/Images/Pins/bomb.png',
new google.maps.Size(32, 37),
new google.maps.Point(0, 0),
new google.maps.Point(22, 44)
);
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(41.287739, -7.738992),
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
#foreach(var item in Model)
{
<text>
var locations = google.maps.LatLng('#item.latitude', '#item.longitude', false);
addMarker(locations);
</text>
}
geocoder = new google.maps.Geocoder();
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(map);
}
geoMarker = new GeolocationMarker(map);
geoMarker.setCircleOptions({ fillColor: '#808080' });
google.maps.event.addListenerOnce(geoMarker, 'position_changed', function () {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(geoMarker, 'geolocation_error', function (e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
geoMarker.setMap(map);
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'click', function (event) {
addMarker(event.latLng);
});
google.maps.event.addListener(map, 'zoom_changed', function () {
var zoomLevel = map.getZoom();
//map.setCenter(myLatLng);
document.getElementById('mapzoom').innerHTML = 'Zoom: ' + zoomLevel;
});
}
function showAddress() {
alert("Vai navegar para outro endereço!");
var address = document.getElementById('txtAddress').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: mp,
position: results[0].geometry.location
});
} else {
alert('error: ' + status);
}
});
}
function addMarker(location) {
var marker = new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: location,
title: 'Bomba',
map: map,
icon: bomb
});
markersArray.push(marker);
}
function setAllMap(map) {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(map);
}
}
function clearMarkers() {
setAllMap(null);
}
function showMarkers() {
setAllMap(map);
}
function deleteMarkers() {
clearMarkers();
markersArray = [];
}
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&' +
'callback=initialize';
document.body.appendChild(script);
}
window.onload = loadScript;
if (!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
</script>
Try this.....
<script>
var markersArray = [];
var _map = null;
var _c = null;
#foreach(var item in Model)
{
<text>
markersArray.push(new google.maps.Marker({
draggable: true,
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng('#item.latitude', '#item.longitude', false),
title: 'Whatever title',
map: _map
}));
</text>
}
</script>
Second Question
I had to carefully look at your code and found 3 problems...one of them you've already mentioned it. The other ones are that you are duplicating variable names and you are not instantiating a new object. Now change this....
#foreach(var item in Model)
{
<text>
var locations = google.maps.LatLng('#item.latitude', '#item.longitude', false);
addMarker(locations);
</text>
}
to this....
#foreach(var item in Model)
{
<text>
addMarker(new google.maps.LatLng(parseFloat('#item.latitude'), parseFloat('#item.longitude')));
</text>
}
Let me know how it goes

Javascript populate Telerik MVC combobox from an array

my application is MVC4; I am trying to populate a Telerik MVC using json, the result is an array; however I get only one item; here is my script:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
var dropDownList = $('#ComboBox').data('tComboBox');
dropDownList.dataBind([
{ Text: start[i] + "-" + end[i], Value: start[i] + "-" + end[i] }]);
dropDownList.select(0);
}
},
error: function () {
}
});
When I add [i] after start and end, I get undefined! without [i] I get the correct value however just one item. Would appreciate your suggestions, thanks in advance.
Hope the following link will help
http://www.telerik.com/community/forums/aspnet-ajax/mvc/radcombobox-populate-on-client-side.aspx
Here you can see
<telerik:RadComboBox ID="radProject" runat="server" Skin="Default" Width="300px"
EnableLoadOnDemand="true" Filter="Contains" OnClientItemsRequesting="getProjects"
EmptyMessage="Select Project" />
in the above code EnableLoadOnDemand is set to true and Filter is set to contains and the event bound to OnClientItemsRequesting.
function getProjects(sender, args) {
itemsRequesting(sender, args);
$.getJSON(
'<%= Url.Action("GetProjects", "Capital") %>',
{ facility: GetFacility().get_value() },
function(data) {
fillCombo(sender, data);
sender.highlightAllMatches(sender.get_text());
});
}
the above javascript method is executing a ajax call using get JSON with parameters and the sub methods fillCombo is filling the combo box.
// Use this for all of your RadComboBox to populate from JQuery
function fillCombo(combo, result) {
combo.clearItems();
var items = result.d || result;
// This just lets your users know that nothing was returned with their search
if (items.length == 0) {
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text("Nothing found");
comboItem.set_value("null");
combo.get_items().add(comboItem);
combo.set_text("");
}
for (var i = 0; i < items.length; i++) {
var item = items[i];
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text(item.Text);
comboItem.set_value(item.Value);
combo.get_items().add(comboItem);
}
}
Now in order to cancel the default behavious of RADComboBox you can use the following code
// This cancels the default RadComboBox behavior
function itemsRequesting(sender, args) {
if (args.set_cancel != null) {
args.set_cancel(true);
}
if (sender.get_emptyMessage() == sender.get_text())
sender.set_text("");
}
I hope the above solution will solve your problem
Here is how I solved the problem:
function CheckWord() {
var wordtocheck = $('#Cword').val();
alert(wordtocheck);
$.ajax({
url: '/Home/CheckWord',
type: 'POST',
data: {
cword: wordtocheck
},
success: function (data) {
var listData = [];
for (var i = 0; i < data.array.length; ++i) {
var myString = data.array[i];
var mySplitResult = myString.split("-->");
var hms = mySplitResult[0];
var a1 = hms.split(',');
var a2 = a1[0];
var a = a2.split(':');
var start = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
var hms1 = mySplitResult[1];
var b1 = hms1.split(',');
var b2 = b1[0];
var b = b2.split(':');
var end = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);
listData[i] = { Text: myString, Value: start };
}
var dropDownList = $('#ComboBox').data('tComboBox');
// debugger;
dropDownList.dataBind(listData);
dropDownList.select(0);
},
error: function () {
}
});
}
Hope this will be helpful to others.

How to call Html.RenderAction() with parameters declarated in jscript?

I have a javascript in *.cshtml file
$(function () {
sliderDiv.slider({
range: true,
min: minVal,
max: maxVal,
values: [minVal, maxVal]
});
sliderDiv.bind("slidechange", function (event, ui) {
var d = "min=" + ui.values[0] + "&max=" + ui.values[1];
$.ajax({
type: "POST",
url: '#Url.Action("Update", "Default")',
data: d,
success: function (result, ajaxObj) {
alert('ok');
alert(result.min + " - " + result.max);
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
},
error: function (ajaxObj, message, exceptionObj) { alert('no'); }
});
});
}
And Controller:
public ActionResult Update(int? min, int? max)
{
if(min == null) min = 1;
if(max == null) max = 1;
var s = new SliderModel()
{
min = (int)min * 1000,
max = (int)max * 1000
};
return new JsonResult
{
Data = s,
ContentEncoding = Encoding.UTF8,
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "json"
};
}
I want to use this line
$("#ajaxresult").html('#{Html.RenderAction("Update", "Default");}');
to send ui.values[0] and ui.values[1] as min and max parameters to Html.RenderAction("Update", "Default")
Something like $("#ajaxresult").html('#{Html.RenderAction("Update", "Default", new {min = ui.values[0], max = ui.values[1]});}');
How can I do something like that???
var url = '#Url.Action("Update", "Default")';
url += '/?min=' + ui.values[0] + '&max=' + ui.values[1];
$("#ajaxresult").load(url);
load docs:
Description: Load data from the server and place the returned HTML into the matched element.

Categories