According to my own question
i have tried something, and my fiddle is link
But i want to be output as like below
i.e x axis contains monthly reports
my ajax code is
$.ajax({
url: "/echo/json/",
data: data,
type: "POST",
success: function(point) {
var chartSeriesData = [];
var chartCategory = [];
$.each(point, function(i, item) {
var series_name = item.resultDate;
var series_data = item.y;
var cagory = series_name;
var series = {
name: series_name,
data: item.y
};
chartSeriesData.push(series);
chartCategory.push(series_name);
});
var chartingOptions = {
chart: {
renderTo: 'container',
defaultSeriesType: 'spline'
},
xAxis: {
categories: chartCategory
},
series: chartSeriesData
};
chartingOptions = $.extend({}, jugalsLib.getBasicChartOptions(), chartingOptions);
chart = new Highcharts.Chart(chartingOptions);
}
});
Thanking you....
In your parser, you create many series, because you initialize series in points loop. So you should prepare series earlier than points loop. Then add points to correct serie (in this case first or second serie).
Related
I am trying to make a dynamic google chart using information from MYSQL DB, I have to pages one draws the information from the DB using json and the other should use the information and create the chart
$query = "SELECT * FROM woodford_fuel";
$result = $conn->query($query);
$jsonArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['reg'];
$jsonArrayItem['value1'] = $row['consump_100'];
array_push($jsonArray, $jsonArrayItem);
}
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
With this I get the following Result, the values I am getting is correct
[{"label":"ND230819","value1":"50.55"},{"label":"ND866941","value1":"51.15"}]
I am trying to load the Chart with the following script
function drawLineChart() {
$.ajax({
url: "chart_data.php",
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrSales = [['label', 'value1']]; // Define an array and assign columns for the chart.
// Loop through each data and populate the array.
$.each(data, function (label, value1) {
arrSales.push([value.label, value.value1]);
});
// Set chart Options.
var options = {
title: 'Average Consumption',
curveType: 'function',
legend: { position: 'bottom', textStyle: { color: '#555', fontSize: 14} } // You can position the legend on 'top' or at the 'bottom'.
};
// Create DataTable and add the array to it.
var figures = google.visualization.arrayToDataTable(arrSales)
// Define the chart type (LineChart) and the container (a DIV in our case).
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(figures, options); // Draw the chart with Options.
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
It is not showing me any chart at all
my first time using chart.js and am running into a small bug that I can't seem to work around it. Below is my code, however, its just displaying the labels but not rendering the pie chart itself.
Am following samples from the chart.js documentation here http://www.chartjs.org/docs/#doughnut-pie-chart-example-usage
Your help will be appreciated.
<canvas id="myChart" width="200" height="200"></canvas>
$(document).ready(function () {
/*
-> #47A508 = green (wins)
-> #ff6a00 = orange (losses)
-> #ffd800 = yellow (draws)
*/
var DataArray = [];
var ctx = document.getElementById("myChart");
$.ajax({
url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
dataType: 'json',
type: 'GET',
}).done(function (result) {
$.each(result.standing, function () {
var name = "Manchester United FC";
if (this.teamName == name) {
DataArray.push([this.wins, this.losses, this.draws]);
}
});
var myChart = new Chart(ctx, {
type: 'pie',
data: {
label: 'Manchester United Current Form',
labels: [
"Wins",
"Losses",
"Draws"
],
datasets: [
{
data: DataArray,
backgroundColor: [
"#47A508",
"#ff6a00",
"#ffd800"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
"#FFCE56"
]
}]
},
options: { responsive: true }
});
});
}
maybe it is because of the jquery each, it fills DataArray async and the array is not ready, when you want to use it as chart data.
Change the $.each to a simple js for loop
for(var i = 0; i < result.standing; i++){
var name = "Manchester United FC";
var team = result.standing[i];
if (team.teamName == name) {
DataArray.push(team.wins, team.losses, team.draws);
}
}
try callbacks for you ajax or do the below (which is a dirty solution):
$.ajax({
url: 'http://api.football-data.org/v1/competitions/426/leagueTable',
dataType: 'json',
cache: false, //add this
async: false, //add this
type: 'GET',
Also
the result of your ajax could be returned using the below code instead of using an array.
jQuery.parseJSON(result);
The issue lies in your DataArray. The way it is implemented is is an array with a single entry. Which is another array itself.
[[<wins>, <losses>, <draws>]]
instead of
[<wins>, <losses>, <draws>]
That is because you instantiate an array and then push into it an array object.
To fix this try using the following function:
(...)
$.each(result.standing, function () {
var name = "Manchester United FC";
if (this.teamName == name) {
DataArray = ([this.wins, this.losses, this.draws]);
console.log("This team name");
}
});
(...)
I got this solved, well sadly, with no magic at all to brag about. There was nothing wrong with the code initially, however, it was a problem with the DOM rendering performance. Thank you #alwaysVBNET and #Aniko Litvanyi for your inputs as well.
This link helped me out, hopefully it does to someone out there.
I wanted to lock the first few columns of my grid and provide horizontal scrolling for the rest of the columns. Am making use of column header gruping.
I have used locked : true property and set a static width to those columns. Yet nothing is happening. I have checked all possible docs. Not sure where the mistake lies. Could someone please help me?
Code is as given below
View.js'
Ext.define('MyModel.view.graphPanel', {
extend: 'Ext.grid.Panel',
layout:'border',
alias: 'widget.graphPanel',
name:'graphPanel',
title: 'Tests',
store: 'MyModel.store.settingStore',
viewConfig: {
stripeRows: true
},
columnLines: true,
split:true,
frame: true
});
Controller.js
Ext.define('MyModel.controller.myController', {
extend:'Ext.app.Controller',
models:['MyModel.model.settingModel'],
stores:['MyModel.store.settingStore'],
init: function() {
Ext.Ajax.request({
url: 'Sample.xml',
success: function(response, opts) {
var txt = response.responseText;
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
var columnArr = [];
var outercolumnarr = [];
var fieldArr = [];
modelfieldArr = [];
completeDataArr=[];
//This builds all locked set of columns
var headerArr = xmlDoc.getElementsByTagName('HEADER1');
Ext.each(headerArr[0].getElementsByTagName('HEADER2'), function(header, index) {
columnArr.push({
text: header.getAttribute('TEXT'),
dataIndex: header.getAttribute('DATAINDEX'),
locked:true,
width:100,
forceFit: true
});
});
outercolumnarr.push({
text:"General data",
width:400,
columns:columnArr,
locked:true
});
//Building scrollable columns
var days = ['Sun','Mon',Tue'];
Ext.each(days, function(day, index) {
columnArr = [];
Ext.each(headerArr[1].getElementsByTagName('HEADER2'), function(innerHeader, index) {
columnArr.push({
text: innerHeader.getAttribute('TEXT'),
dataIndex: innerHeader.getAttribute('DATAINDEX')
});
});
outercolumnarr.push({
text:day,
columns:columnArr,
});
});
//outercolumnarr contains the final column array
//Similarly build data array, model and field array for stores and models.
var store = Ext.data.StoreManager.lookup('MyModel.store.settingStore');
store.setFields(modelfieldArr);
store.setData(completeDataArr);
//Reconfigure the grid
var gridview = Ext.ComponentQuery.query('graphPanel')[0];
gridview.reconfigure(store,outercolumnarr);
}
});
}
});
Because you are adding columns using reconfigure, enableLocking is not enabled implicitly. You must enable it manually. You may enable it in MyModel.view.graphPanel definition, but probably you'll also need to add empty column definition (columns: []), because I've had error from framework without that.
Working sample: http://jsfiddle.net/nj4nk/11/
I would like to use leaflet.draw to create outlines of regions. I have managed to get this working ok: https://www.mapbox.com/mapbox.js/example/v1.0.0/leaflet-draw/
Now I'd like to save the data for each polygon to a mysql table. Am a little stuck on how I would go about exporting the data and the format I should be doing it in.
If possible I'd like to pull the data back into a mapbox/leaflet map in the future so guess something like geojson would be good.
So you could use draw:created to capture the layer, convert it to geojson then stringify it to save in your database. I've only done this once and it was dirty but worked.
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
If you want to collect the coordinates, you can do it this way:
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
// Process them any way you want and save to DB
...
});
var getShapes = function(drawnItems) {
var shapes = [];
drawnItems.eachLayer(function(layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes.push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes.push([layer.getLatLng()]);
}
});
return shapes;
};
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var shape = layer.toGeoJSON()
var shape_for_db = JSON.stringify(shape);
});
// restore
L.geoJSON(JSON.parse(shape_for_db)).addTo(mymap);
#Michael Evans method should work if you want to use GeoJSON.
If you want to save LatLngs points for each shape you could do something like this:
map.on('draw:created', function (e) {
var type = e.layerType;
var layer = e.layer;
var latLngs;
if (type === 'circle') {
latLngs = layer.getLatLng();
}
else
latLngs = layer.getLatLngs(); // Returns an array of the points in the path.
// process latLngs as you see fit and then save
}
Don't forget the radius of the circle
if (layer instanceof L.Circle) {
shapes.push([layer.getLatLng()],layer.getRadius())
}
PS that statement may not get the proper formatting but you see the point. (Or rather the radius as well as the point ;-)
Get shares as associative array + circle radius
map.on('draw:created', function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('Call Point!');
}
drawnItems.addLayer(layer);
var shapes = getShapes(drawnItems);
console.log("shapes",shapes);
});
var getShapes = function (drawnItems) {
var shapes = [];
shapes["polyline"] = [];
shapes["circle"] = [];
shapes["marker"] = [];
drawnItems.eachLayer(function (layer) {
// Note: Rectangle extends Polygon. Polygon extends Polyline.
// Therefore, all of them are instances of Polyline
if (layer instanceof L.Polyline) {
shapes["polyline"].push(layer.getLatLngs())
}
if (layer instanceof L.Circle) {
shapes["circle"].push([layer.getLatLng()])
}
if (layer instanceof L.Marker) {
shapes["marker"].push([layer.getLatLng()],layer.getRadius());
}
});
return shapes;
};
For me it worked this:
map.on(L.Draw.Event.CREATED, function (e) {
map.addLayer(e.layer);
var points = e.layer.getLatLngs();
puncte1=points.join(',');
puncte1=puncte1.toString();
//puncte1 = puncte1.replace(/[{}]/g, '');
puncte1=points.join(',').match(/([\d\.]+)/g).join(',')
//this is the field where u want to add the coordinates
$('#geo').val(puncte1);
});
For me it worked this:
after get coordinates send to php file with ajax then save to db
var drawnItems = new L.FeatureGroup();
map.addLayer(drawnItems);
// Set the title to show on the polygon button
L.drawLocal.draw.toolbar.buttons.polygon = 'Draw a polygon!';
var drawControl = new L.Control.Draw({
position: 'topright',
draw: {
polyline: true,
polygon: true,
circle: true,
marker: true
},
edit: {
featureGroup: drawnItems,
remove: true
}
});
map.addControl(drawControl);
map.on(L.Draw.Event.CREATED, function (e) {
var type = e.layerType,
layer = e.layer;
if (type === 'marker') {
layer.bindPopup('');
}
drawnItems.addLayer(layer);
shape_for_db = layer.getLatLngs();
SEND TO PHP FILE enter code hereWITH AJAX
var form_data = new FormData();
form_data.append("shape_for_db",shape_for_db);
form_data.append("name", $('#nameCordinate').val());
$.ajax({
url: 'assets/map_create.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (php_script_response) {
var tmp = php_script_response.split(',');
alert(tmp );
}
});
});
map.on(L.Draw.Event.EDITED, function (e) {
var layers = e.layers;
var countOfEditedLayers = 0;
layers.eachLayer(function (layer) {
countOfEditedLayers++;
});
console.log("Edited " + countOfEditedLayers + " layers");
});
L.DomUtil.get('changeColor').onclick = function () {
drawControl.setDrawingOptions({rectangle: {shapeOptions: {color: '#004a80'}}});
};
The following code works:
var options1 = {
chart: {
renderTo: 'container1'
},
series: [{}]
};
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
var chart = new Highcharts.Chart(options1);
});
I want to be able to add a number of data series, so I am trying to take the reference to ‘new Highcharts’ out of the getJSON, but I don't seem to get it right. This following code does not work:
$.getJSON('tokyo.jsn', function(data){
options1.series[0].data = data;
});
var chart = new Highcharts.Chart(options1);
I have also tried tackling it a different way but again the following code does not work:
var chart1 = new Highcharts.Chart({
chart: {
renderTo: 'container1'
},
series: [{}]
});
$.getJSON('tokyo.jsn', function(data){
chart1.series[0].data = data;
});
Can anyone point me in the correct direction. I need to be able to support multiple data series by doing a second getJSON call like the following:
$.getJSON('sydney.jsn', function(data){
options1.series[1].data = data;
});
The JSON code I'm using is as follows:
[ 7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6 ]
Thanks
$.getJSON is an asynchronous request. Once you receive the data, then you can pass it to Highcharts, thus you have to call that code from within the callback function of $.getJSON().
Try this, use a helper function to process your data and draw the chart, see drawChart() below:
var options1 = {
chart: {
renderTo: 'container1'
},
series: []
};
var drawChart = function(data, name) {
// 'series' is an array of objects with keys:
// - 'name' (string)
// - 'data' (array)
var newSeriesData = {
name: name,
data: data
};
// Add the new data to the series array
options1.series.push(newSeriesData);
// If you want to remove old series data, you can do that here too
// Render the chart
var chart = new Highcharts.Chart(options1);
};
$.getJSON('tokyo.jsn', function(data){
drawChart(data, 'Tokyo');
});
$.getJSON('sydney.jsn', function(data){
drawChart(data, 'Sydney');
});
See fiddle: http://jsfiddle.net/amyamy86/pUM7s/
You can use solution used by Highcharts in that example: http://www.highcharts.com/stock/demo/compare
Or first create empty chart, without any series, and then use addSeries() function in each callback, see: http://api.highcharts.com/highcharts#Chart.addSeries()