Hi trying to create this array dynamically. This is the static way:
var pieData = [
{
value: 300,
color:getRandomColor(),
highlight: getRandomColor(),
},
{
value: 50,
color: getRandomColor(),
highlight: "#fac878",
},
{
value: 100,
color: getRandomColor(),
highlight: getRandomColor(),
},
{
value: 120,
color: getRandomColor(),
highlight: getRandomColor(),
}
];
This is what I achieved:
$.ajax({
method: "POST",
url: "getPieChartData"
})
.done(function(data){
obj = $.parseJSON(data);
var pieData = []; i = 0;
$.each(obj, function(key, item) {
pieData[i].value = item.total + " - " + item.d_name;
pieData[i].color = getRandomColor();
pieData[i].highlight = getRandomColor();
i++;
});
});
I am getting value from my function that is not a problem. My issue is that I am getting in the console that this part:
pieData[i].value = item.total +" - " + item.d_name; TypeError: pieData[i] is undefined
What am I doing wrong? thx
You can simple use .push() method. No meed to use indexer.
The push() method adds one or more elements to the end of an array and returns the new length of the array.
$.each(obj, function(key, item) {
pieData.push({
value: item.total + " - " + item.d_name,
color : getRandomColor(),
highlight : getRandomColor()
});
});
You need to create the pieData[i] object first;
var pieData = []; i = 0;
$.each(obj, function(key, item) {
pieData[i] = {}; // added line
pieData[i].value = item.total + " - " + item.d_name;
pieData[i].color = getRandomColor();
pieData[i].highlight = getRandomColor();
i++;
});
Before pieData[i].value .., you should first have a line:
pieData[i] = {};
Related
I wrote my code down to a small fiddle: http://jsfiddle.net/V8dyd/266/
I am able to render region labels as strings on the map but unable to render them as HTML.
$(function(){
var Jsondata = {
LK: " Region : Asia, Feedback : 228, Good : 34.00%, Normal : 33.00%, Bad : 30.00% ",
IN: "Total Responses : 228"
};
var map = $('#map').vectorMap({
map: 'world_mill_en',
zoomMin: 1,
zoomMax: 1,
regionLabelStyle: {
initial: {
fill: '#B90E32'
},
hover: {
fill: 'black'
}
},
labels: {
regions: {
render: function (code) {
if (code==="LK") {
var a = Jsondata[code];
var array = a.split(',');
var s = "<html><body><div><small>" + array[0] +"</small><br><small>" + array[1] + "</small><br><small>" + array[2] + "</small><br><small>" + array[3] + "</small></div</body></html>";
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
return htmlObject;
// return s
}
}
}
}
});
});
The labels are rendered using svg TEXT-Tags and do not allow HTML.
In the current version this is not supported but i used a Hook in the Region Function for realize line breaks:
https://github.com/bjornd/jvectormap/blob/master/src/region.js
Like this:
jvm.Region = function(config){
var bbox,
text,
offsets,
labelDx,
labelDy;
this.config = config;
this.map = this.config.map;
this.shape = config.canvas.addPath({
d: config.path,
'data-code': config.code
}, config.style, config.canvas.rootElement);
this.shape.addClass('jvectormap-region jvectormap-element');
bbox = this.shape.getBBox();
myHook(bbox, text, offsets, config);
return false;
...
}
function myHook(bbox, text, offsets, config){
// Create your own Label like this
text = this.getLabelText(config.code);
if (this.config.label && text) {
offsets = this.getLabelOffsets(config.code);
this.labelX = bbox.x + bbox.width / 2 + offsets[0];
this.labelY = bbox.y + bbox.height / 2 + offsets[1];
this.label = config.canvas.addText({
text: text,
'text-anchor': 'middle',
'alignment-baseline': 'central',
x: this.labelX,
y: this.labelY,
'data-code': config.code
}, config.labelStyle, config.labelsGroup);
this.label.addClass('jvectormap-region jvectormap-element');
}
}
Thats not the best way but maybe it helps you!
I used this ,to multiply doughnut chart according as array(arr) has,but it can't change to object,(data has string type).So chart doesn't appear here..,how fix it
var arr=['HTML','CSS','JS'],i,data;
data ='[';
for(i=0;i<arr.length;i++){
if(i==arr.length-1){
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]}';
}
else{
data+='{value:"300",color:"#fff",highlight:"#aaa",label:arr[i]},';
}
}
data += ']';
var dat = data;
window.onload = function () {
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat,{
responsive: true,
});
};
//want like this
dat =[{value:"300",color:"#fff",highlight:"#aaa",label:"HTML"},
{value:"200",color:"#fff",highlight:"#aaa",label:"CSS"}];
You are creating your array as a String.
You need to create an array of objects [{},{},{}].
The method used to INSERT a new object in an array is PUSH().
Check the fiddle. Now it´s working OK (move the mouse on the screen to see the chart is there (you will only see it when mouse is over it):
window.onload = function() {
var arr = ['HTML', 'CSS', 'JS'],
i, data;
data = [];
for (i = 0; i < arr.length; i++) {
if (i == arr.length - 1) {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
} else {
data.push({
value: "300",
color: "#fff",
highlight: "#aaa",
label: arr[i]
});
}
}
var dat = data;
var ctx = document.getElementById("chart-area").getContext("2d");
window.myBar = new Chart(ctx).Doughnut(dat, {
responsive: true,
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/nnnick/Chart.js/master/Chart.js"></script>
<canvas id="chart-area"></canvas>
What I want to do: I want to display a diagram using Highcharts and the best code style.
Problem: My code is unreadable / hard to debug because I store it within variables.
Okay I have a Javascript-Object containing all the information I need for later use (categories, y axis value and the series itself which is split into positive, neutral and negative).
var testDia =
{
name : 'Testname',
'chartCategories': ['Golf', 'Polo', 'Passat'],
'chartSeries':
{
'positive': [
{y:341, url:'http://golf.com?q=positive'},
{y:487, url:'http://polo.com?q=positive'},
{y:180, url:'http://passat.com?q=positive'}
],
'neutral': [
{y:12, url:'http://golf.com?q=neutral'},
{y:3, url:'http://polo.com?q=neutral'},
{y:9, url:'http://passat.com?q=neutral'}
],
'negative': [
{y:222, url:'http://golf.com?q=negative'},
{y:115, url:'http://polo.com?q=negative'},
{y:321, url:'http://passat.com?q=negative'}
]
}
}
My approach is to loop over the categories and add positive, neutral and negative to seperate strings which I evaluate later on in the highcharts-setup.
var allPositiveData = '';
var allNeutralData = '';
var allNegativeData = '';
for(var i=0; i < categories.length; i++) {
var diaPositive = series['positive'][i]['y'];
var diaNeutral = series['neutral'][i]['y'];
var diaNegative = series['negative'][i]['y'];
urlPositive = series['positive'][i]['url'];
urlNeutral = series['neutral'][i]['url'];
urlNegative = series['negative'][i]['url'];
allPositiveData += "{'y': " + diaPositive + ", 'url': '" + urlPositive + "'}, ";
allNeutralData += "{'y': " + diaNeutral + ", 'url': '" + urlNeutral + "'}, ";
allNegativeData += "{'y': " + diaNegative + ", 'url': '" + urlNegative + "'}, ";
} // end of loop
allPositiveData = eval( "[" + allPositiveData.slice(0, -2) + "]" );
allNeutralData = eval( "[" + allNeutralData.slice(0, -2) + "]" );
allNegativeData = eval( "[" + allNegativeData.slice(0, -2) + "]" );
Highcharts-setup
newChart = new Highcharts.Chart({
chart : {
renderTo : 'container',
type: 'column'
},
[...] // skipping the rest of the setup
series: [
{
name: 'Positive',
data: allPositiveData
}, {
name: 'Neutral',
data: allNeutralData
}, {
name: 'Negative',
data: allNegativeData
}]
});
I figure there are a few ways to achieve what I want but I want to know a better (maybe object orientated) solution.
http://jsfiddle.net/x8455/
I think you are trying to do something what you already have done.
You want to get display three series from your JSON, for respective categories, then let's to that:
Your code:
var categories = testDia['chartCategories'];
var series = testDia['chartSeries'];
Great! Now use that variables:
newChart = new Highcharts.Chart({
chart : {
renderTo : portletContainer,
type: 'column'
},
...
xAxis: {
categories: categories,
labels: {
rotation: -45,
align: 'right',
}
},
...
series: [{
name: 'Positive',
data: series.positive // testDia.chartSeries.positive is the same
}, {
name: 'Neutral',
data: series.neutral
}, {
name: 'Negative',
data: series.negative
}]
});
And working demo: http://jsfiddle.net/x8455/1/
Here's how you should do it.
var allPositiveData = []; // You want an array, so start off with an array.
for(var i=0; i < categories.length; i++) {
var diaPositive = series['positive'][i]['y'];
urlPositive = series['positive'][i]['url'];
allPositiveData.push({'y':diaPositive, 'url':urlPositive}); // Add the element to the array.
}
That's all there is to it. Your Highcharts-setup piece of code can remain the same.
To make the sample a little shorter, I only edited the code for the positive data, the rest is the same, just a different name.
It's seems to be very easy but i can not make it works. I have an array con 2 var inside that i get from Jquery.
var features = [long, lat ]
i would like to get all the valores in the loop and i need
fetures[i]
that will give me long1 and lat1 but when i try
alert( features[0] )
i get all the long values.
and when i try with [1] i get all the lat values.
How can i solve this issue?
I can not make it work, maybe you can have a look at my code:
$.ajax({
url : "https://api.foursquare.com/v2/venues/search?limit=3&radius=1000&client_id=J22NHX41TJBJ2PZM4NBTLDWLDYIBWLMIF4LJCFWNAXK1WALY&client_secret=RS110L4OYLY1XFCEMV30UB2JJ1JRFQZ0E3P0USSIMSCA45RZ&v=20120101&ll=" + ui.item.y +"," + ui.item.x,
dataType : "jsonp",
success : function(data) {
$.each(data.response.venues, function( index, value ) {
//alert( index + ": " + value.name + " , "+ value.location.lng);
var Name = value.name
var VenueLati = value.location.lat
var VenueLong = value.location.lng
//alert( VenueLong );
var features = [];
for(var i = 0; i < features[0].length; i++) {
feature[i] = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(VenueLong, VenueLati).transform('EPSG:4326', 'EPSG:3857'),
{some:'data'},
{
foo :
}, {
fillColor : '#008040',
fillOpacity : 0.8,
strokeColor : "#ee9900",
strokeOpacity : 1,
strokeWidth : 1,
pointRadius : 8
});
}
When i put a number intead features[0].length then i can see the points but can see only one popup :/
$.ajax({
url : "https://api.foursquare.com/v2/venues/search?limit=3&radius=1000&client_id=J22NHX41TJBJ2PZM4NBTLDWLDYIBWLMIF4LJCFWNAXK1WALY&client_secret=RS110L4OYLY1XFCEMV30UB2JJ1JRFQZ0E3P0USSIMSCA45RZ&v=20120101&ll=" + ui.item.y +"," + ui.item.x,
dataType : "jsonp",
success : function(data) {
$.each(data.response.venues, function( index, value ) {
//alert( index + ": " + value.name + " , "+ value.location.lng);
var Name = value.name
var VenueLati = value.location.lat
var VenueLong = value.location.lng
alert( VenueLong );
var features = [];
for(var i = 0; i<50; i++) {
features[i] = new OpenLayers.Feature.Vector(
toMercator(new OpenLayers.Geometry.Point(VenueLong,
VenueLati)),
{
ulica : Name
}, {
fillColor : '#008040',
fillOpacity : 0.8,
strokeColor : "#ee9900",
strokeOpacity : 1,
strokeWidth : 1,
pointRadius : 8
});
}
// create the layer with listeners to create and destroy popups
var vector = new OpenLayers.Layer.Vector("Points",{
eventListeners:{
'featureselected':function(evt){
var feature = evt.feature;
var popup = new OpenLayers.Popup.FramedCloud("popup",
OpenLayers.LonLat.fromString(feature.geometry.toShortString()),
null,
"<div style='font-size:.8em'>Name: " + feature.id +"<br>Address: " + feature.attributes.ulica+"</div>",
null,
true
);
feature.popup = popup;
map.addPopup(popup);
},
'featureunselected':function(evt){
var feature = evt.feature;
map.removePopup(feature.popup);
feature.popup.destroy();
feature.popup = null;
}
}
});
vector.addFeatures(features);
// create the select feature control
var selector = new OpenLayers.Control.SelectFeature(vector,{
hover:true,
autoActivate:true
});
map.addLayers([vector]);
map.addControl(selector);
center = new OpenLayers.LonLat(lon, lat).transform('EPSG:4326', 'EPSG:3857');
map.setCenter(center, 15);
You have 2 array in one array like this:
var features = [ [100, 200, 300, 400], ["A", "B", "C", "D"];
if you want to get the long s, you should do this:
for(var i=0;i<features[0].length;i++){
alert(features[0][i]);
}
and for the lat s:
for(var j=0;j<features[1].length;j++){
alert(features[1][j]);
}
but I think you are expecting something else, like an array of json objects with long and lat as its keys, although you can map these 2 array based on their order, if both lists are ordered:
var newArray = [];
for(var i=0;i<features[0].length;i++){
newArray.push({"long":features[0][i], "lat":features[1][i]});
}
Instead of literal values in your array, you will want objects:
var features = [{long: 123, lat: 234}, {long: 545, lat: 677}];
Then,
features[0]
will give you
{long: 123, lat: 234}
Which you can access by
features[0].long
features[0].lat
I hope this helps. Let me know if you have further questions.
I am using flot charts. I want to plot chart which is updated per second and also want to add the feature of turning off and on the data series.
I am able to make it work but has problems which I did not expect, like color of one series change when other series is turned off; other is when I update the array of data series the charts seems to move but it removes element from the right,at the same time the new value is plotted on the right hand side ...
var d1 = [] ;
var d2 = [] ;
var d3 = [] ;
$(function(){
{%for reading in readings%}
var time_stamp = parseFloat({{reading['timestamp']}} + 19800.00) * 1000
var A = parseFloat({{reading['values']['A']}}) ;
var V = parseFloat({{reading['values']['VLN']}}) - 50 ;
var W = parseFloat({{reading['values']['W']}}) / 1000 ;
d1.push([time_stamp,A]);
d2.push([time_stamp,V]);
d3.push([time_stamp,W]);
{%endfor%}
var datasets = {
"current":{
label : "A",
data : d1
},
"voltage":{
label : "V",
data : d2
},
"power":{
label : "W",
data : d3
},
}
var i = 0;
$.each(datasets, function(key, val) {
val.color = i;
++i;
});
// insert checkboxes
var choiceContainer = $("#choices");
$.each(datasets, function(key, val) {
choiceContainer.append("<br/><input type='checkbox' name='" + key +
"' checked='checked' id='id" + key + "'></input>" +
"<label for='id" + key + "'>"
+ val.label + "</label>");
});
choiceContainer.find("input").click(plotAccordingToChoices);
function plotAccordingToChoices() {
var data = [];
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key]) {
data.push(datasets[key]);
}
});
if (data.length > 0) {
$.plot("#placeholder", data, {
series: {
shadowSize: 0,
lines: {
show: true
},
},
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0,
mode:"time"
}
});
}
setTimeout(getNextDataset,1000);
}
plotAccordingToChoices();
});
function getNextDataset()
{
$.ajax({url : '/newdata' , success:function(result){
reading =JSON.parse(result);
var time_stamp = (parseFloat(reading.timestamp) + 19800.00) * 1000
var A = parseFloat(reading.values.A) ;
var W = parseFloat(reading.values.W) / 1000 ;
var V = parseFloat(reading.values.VLN) - 50 ;
d1.shift();d2.shift();d3.shift();
d1.push([time_stamp,A]);
d2.push([time_stamp,V]);
d3.push([time_stamp,W]);
var datasets = {
"current":{
label : "A",
data : d1
},
"voltage":{
label : "V",
data : d2
},
"power":{
label : "W",
data : d3
},
}
var data = [] ;
var choiceContainer = $("#choices");
choiceContainer.find("input:checked").each(function () {
var key = $(this).attr("name");
if (key && datasets[key]) {
data.push(datasets[key]);
}
});
if (data.length > 0) {
$.plot("#placeholder", data, {
series: {
shadowSize: 0,
lines: {
show: true
},
points:{
show:false
},
},
yaxis: {
min: 0
},
xaxis: {
tickDecimals: 0,
mode:"time"
}
});
}
}
});
setTimeout(getNextDataset,1000) ;
}
`
I am making use of code available in flot charts examples.Where am I going wrong ??
Thank you ?
Problem 1 : Color updating every time a checkbox was checked or unchecked
Reason: Every time the checkbox click event was triggered,some how the color used to get updated
Solution : Removed setTimeout(getNextDataset,1000); call from the function plotAccordingToChoices()
Problem 2: The data elements are removed from the right instead of left.
Reason : (Very dumb) Data was coming in descending order and I was using pushing data in that order only.So latest point was at location 0 of the array and oldest point was at location n-1.And I was removing (n-1)th point.
Solution : Replaced push in the beginning with unshift().Did the magic :P