JSON Data in javascript - json

I would like to use json in chartJS. In first example I used
["0","76","32","88"]
and everything looks great.
Problem is in second example when I want to use JSON data as:
var json =[{"wartosc":"0"},{"wartosc":"76"},{"wartosc":"32"},{"wartosc":"88"}];
In variable chartjsData i want to have data as ["0","76","32","88"] but it doesn't work.
var json =[{"wartosc":"0"},{"wartosc":"76"},{"wartosc":"32"},{"wartosc":"88"}];
var chartjsData = [];
for (var i = 0; i < json.lenght; i++) {
chartjsData.push (json[i].wartosc);
}
var areaChartData = {
labels: ["j","j","j","j"],
datasets: [
{
label: "Electronics",
fillColor: "rgba(210, 214, 222, 1)",
strokeColor: "rgba(210, 214, 222, 1)",
pointColor: "rgba(210, 214, 222, 1)",
pointStrokeColor: "#c1c7d1",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
data: ["0","76","32","88"]
},
{
label: "Digital Goods",
fillColor: "rgba(60,141,188,0.9)",
strokeColor: "rgba(60,141,188,0.8)",
pointColor: "#3b8bba",
pointStrokeColor: "rgba(60,141,188,1)",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(60,141,188,1)",
data: chartjsData
}
]
};

You misspelled .length
for (var i = 0; i < json.length; i++) {
chartjsData.push (json[i].wartosc);
}

Related

Highcharts with json from django query not rendered

I'm following this article to render highchart with json data from django query. However chart is not rendered but I'm not getting any errors from Django or by the client when inspecting source. Appreciate if anyone can point the mistakes. Thank you in advance.
I'm using django 2.0 and python3.5
models.py
PLATFORM = (
('ipcore','IPCORE'),
('metro','METRO E'),
('edge','EDGE'),
('access','ACCESS'),
('voice','VOICE'),
('system','SYSTEM'),
('iptv','IPTV'))
class Contract(models.Model):
vendor_name = models.ForeignKey(Vendor, on_delete=models.CASCADE)
name = models.CharField(max_length=500)
contract_no = models.CharField(max_length=100, blank=True)
partner_name = models.CharField(max_length=200, blank=True)
value = models.DecimalField(max_digits=11, decimal_places=2,
blank=True, null=True)
platform = models.CharField(max_length=100, blank=True,
choices=PLATFORM)
views.py
def json_example(request):
return render(request, 'app/json_example.html')
def chart_data(request):
dataset=Contract.objects.all().values('platform').
exclude(platform='').annotate(Sum('value')).order_by('value__sum')
platform_name = dict()
for platform_tuple in Contract.PLATFORM:
platform_name[platform_tuple[0]] = platform_tuple[1]
chart = {
'chart': {'type': 'pie'},
'title': {'text': 'Contract Value for Every platform'},
'series': [{
'name': 'Platform',
'data': list(map(lambda row: {'name':
platform_name[row['platform']],
'y': row['value__sum']}, dataset))
}]
}
return JsonResponse(chart)
urls.py
url('json_example/', views.json_example, name='json_example'),
url('json_example/data/', views.chart_data, name='chart_data'),
json_example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Contract Inventory Highcharts Example</title>
</head>
<body>
<div id="container" data-url="{% url 'chart_data' %}"></div>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
Highcharts.chart("container", data);
}
});
</script>
</body>
</html>
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
This is the json data from dataset.
[{"platform": "IPTV", "value__sum": "0.00"}, {"platform": "METRO E", "value__sum": "71372564.20"}, {"platform": "EDGE", "value__sum": "73867073.63"}, {"platform": "SYSTEM", "value__sum": "135465418.85"}, {"platform": "IPCORE", "value__sum": "467810178.41"}]
Your json data doesn't contain chart options. It should be something like this:
'{"title":{"text":"Title"},"series":[{"name":"Installation","data":[43934,52503,57177,69658,97031,119931,137133,154175]}]}'
What's more, you should parse json to js object before passing it to Highcharts constructor:
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var chartData = JSON.parse(data);
Highcharts.chart("container", chartData);
}
});
</script>
Check the example:
https://jsfiddle.net/BlackLabel/7zfyhnbr/
You have to format the data in such a way that it should match the highcharts ploting object. Please checkout the below code.
data = [
{"platform": "IPTV", "value__sum": "0.00"},
{"platform": "METRO E", "value__sum": "71372564.20"},
{"platform": "EDGE", "value__sum": "73867073.63"},
{"platform": "SYSTEM", "value__sum": "135465418.85"},
{"platform": "IPCORE", "value__sum": "467810178.41"}];
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div id="container"></div>
</body>
</html>
You have to update your code like below
<script>
$.ajax({
url: $("#container").attr("data-url"),
dataType: 'json',
success: function (data) {
var data = JSON.parse(data);
x_axis_data = [];
y_axis_data = [];
for(index=0; index < data.length; index++) {
item = data[index];
x_axis_data.push(item['platform'])
y_axis_data.push(parseFloat(item['value__sum']))
}
Highcharts.chart('container', {
title: {
text: 'learnbatta.com'
},
xAxis: {
title: {
text: 'X Value'
},
categories: x_axis_data
},
yAxis: {
title: {
text: 'Y Value'
},
},
series: [{
name: 'Curve',
data: y_axis_data
}]
});
}
});
</script>
I've manage to solve it by updated my views.py using django rest API and my template accordingly. Here is my updated code:
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
class ChartView(View):
def get(self, request, *args, **kwargs):
return render(request, 'app/charts.html')
class ChartData(APIView):
authentication_classes = []
permission_classes = []
def get(self, request, format=None):
totalvendor= Contract.objects.all().values("vendor_name_id__name").
annotate(Count("id")).order_by('-id__count')[:8]
labels = totalvendor.values_list('vendor_name_id__name')
default_items = totalvendor.values_list('id__count', flat=True)
default_items = list(default_items)
data = {
"labels": labels,
"default": default_items,
}
return Response(data)
Pass an array from queryset to template and js
Here is my urls.py
url(r'^chart/', views.ChartView.as_view(), name='chart'),
url(r'^api/chart/data/$', ChartData.as_view(), name='chartdata'),
Here my code for charts.html
<script>
{% block jquery %}
var endpoint = '/api/chart/data/'
var defaultData = []
var labels = [];
$.ajax({
method: "GET",
url: endpoint,
success: function(data){
labels = data.labels
defaultData = data.default
setChart()
},
error: function(error_data){
console.log("error")
console.log(error_data)
}
})
function setChart(){
var ctx = document.getElementById("myChart");
var ctx2 = document.getElementById("myChart2");
var myChart = new Chart(ctx2, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: 'Value Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
title:{
display:true,
text:'Count Contract for Every Platform',
fontSize:18,
position:'top'
},
legend:{
display:false,
position:'right',
labels:{
fontColor:'#000'
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
var myChart = new Chart(ctx, {
type: 'polarArea',
data: {
labels: labels,
datasets: [{
label: 'Count Contract for Platform',
data: defaultData,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
}
// var ctx = document.getElementById("myChart");
{% endblock %}
</script>
{% block content %}
<div class='row'>
<div class='col-sm-12' url-endpoint='{% url "chartdata" %}'>
<h1>Data Presentation</h1>
<div class=''>
<div class='col-sm-6'>
<canvas id="myChart" width="400" height="400"></canvas>
</div>
<div class='col-sm-6'>
<canvas id="myChart2" width="400" height="400"></canvas>
</div>
</div>
</div>
</div>
{% endblock content %}
Anyway thanks to those who answered my questions

Highcharts series data from JSON object

I am new to JSON and mvc so here is my issue. I am currently working on graphs using highcharts. I have a controller which returns a JSON object.
public JsonResult _GetChart_TrendPublicationTypeDetailed_Data(int
yearToDisplay)
{
//Types of publications to be considered
string[] publication_types = new string[] { "article", "book", "book_section", "conference_proceedings" };
//Get the list of outputs with usp authors
var uspPubs = _uspAuthoredPublications();
//List of years for which to display the data
List<int> yearRange = _getListOfYears(yearToDisplay, yearRangeFactor_10);
//Get the data
var data = from eprint_summary in localDB.Summary
where
eprint_summary.Year > (yearToDisplay - yearRangeFactor_10)
&& eprint_summary.Year <= yearToDisplay
&& publication_types.Contains(eprint_summary.TypeCode)
&& uspPubs.Contains(eprint_summary.EprintId)
//&& eprint_summary.refereed == "TRUE" //TODO: Confirm whether we need this filter in our counts
group eprint_summary by new { eprint_summary.Year, eprint_summary.TypeDesc } into typeTrend
orderby typeTrend.Key.Year, typeTrend.Key.TypeDesc
select new
{
Year = typeTrend.Key.Year,
Type = typeTrend.Key.TypeDesc,
Count = typeTrend.Count()
};
//Extract the series data
List<object> countData = new List<object>();
foreach (var item in data.ToList().Select(y => y.Type).Distinct().OrderBy(y => y))
{
List<int> yearlyData = new List<int>();
foreach (var year in yearRange)
{
var rec = data
.Where(y => y.Type == item)
.Where(y => y.Year == year)
.Select(y => y.Count).ToArray();
yearlyData.Add(
rec == null || rec.Length == 0 ? 0 : rec[0]
);
}
countData.Add(
new
{
name = item, //Name of the series
data = yearlyData.ToArray() //Array of data
}
);
}
//Form the json object using the series data and labels
return Json(
new
{
labels = yearRange.ToArray(),
series = countData
},
JsonRequestBehavior.AllowGet
);
}
The above is my JSON in controller.
I have my view as below where I am getting the JSON object but I do not know how to append to my graph as series. How would I convert the JSON object to something that the series accepts.
var seriesData = ' ';
var test = ' ';
function ajaxCall() {
$.ajax({
type: "post",
datatype: "Json",
async: true,
url: '#Url.Action("_GetChart_TrendPublicationTypeDetailed_Data", "ResearchCharts")',
data: { yearToDisplay: '#(DateTime.Now.AddYears(-1).Year.ToString())' },
success: function (data) {
seriesData = data;
test = seriesData.series;
//bindChart(test);
//alert(JSON.stringify(seriesData));
alert(JSON.stringify(test));
},
error: function () {
alert("An error occurred.");
}
});
}
//functions call
ajaxCall();
bindChart(test);
function bindChart(test) {
var test2 = [{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }];
$('#chartTrendsPublicationTypeDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
},
series: test2//[{ "name": "Book", "data": [14, 17, 9, 10, 6, 19, 6, 8, 0, 4] }, { "name": "Book Chapter", "data": [65, 74, 44, 66, 9, 23, 36, 51, 53, 36] }, { "name": "Conference Proceedings", "data": [15, 17, 27, 30, 28, 54, 35, 43, 50, 35] }, { "name": "Journal Article", "data": [178, 162, 133, 139, 133, 191, 160, 194, 149, 169] }]
});
Please help, just need to somehow pass the data to highcharts.
in the picture, I have added the series manually and it works, but I need to pass in a variable which the series property accepts.
Old Highcharts rendering code:
$('#chartTrendsPublicationRankDetailed').highcharts({
chart: {
type: 'line'
},
title: {
text: 'My data'
},
xAxis: {
categories: labels
},
series: seriesData
});
New Highcharts rendering code. This accepts my JSON objects successfully and renders the graphs.
function bindChartItemType(seriesData, labels) {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartTrendsPublicationTypeDetailed',
type: 'line',
height: 500,
width: 500
},
credits: {
enabled: false
},
title: {
text: 'Trend of Publications by Item Type'
},
xAxis: {
categories: labels,
title: {
text: '<b>Year</b>'
}
},
yAxis: {
min:0,
title: {
text: '<b># of publications</b>'
}
},
series: seriesData
});
}
Feel free to add anything you like in the comments.
Regards
Shafraz Buksh

Why is here a number?

I am doing a bar chart and I have a problem with names of columns. I was trying also to give names of x and yAxes but here was a problem too.
That's my dates from database:
[{ "id": "1", "paliwo": "200", "przebieg": "150", "jedzenie": "0" }]
My code:
$(document).ready(function() {
$.ajax({
url: "data.php",
method: "GET",
success: function(data) {
console.log(data);
var paliwo = [];
var przebieg = [];
for (var i in data) {
paliwo.push(data[i].paliwo);
przebieg.push(data[i].przebieg);
}
var chartdata = {
labels: paliwo,
przebieg,
datasets: [{
label: 'Paliwo',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: paliwo
}, {
label: 'Przebieg',
backgroundColor: 'rgba(200, 200, 200, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: przebieg
}]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata,
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
},
error: function(data) {
console.log(data);
}
});
});
this is because you have given labels:paliwo; Labels denotes the x axis and paliwo contains [200]

Draw two lines in column chart google charts

I am trying to draw two lines using google combo charts, I am referring this link https://developers.google.com/chart/interactive/docs/gallery/combochart
but I am able to draw only one line!!!
function drawchart1(dataValues) {
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
var data = new google.visualization.DataTable();
data.addColumn('string', 'KPI_MONTH');
data.addColumn('number', 'DIE');
data.addColumn('number', 'DIE_TS');
data.addColumn('number', 'DIE_LL');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].KPI_MONTH, dataValues[i].DIE, dataValues[i].DIE_TS, dataValues[i].DIE_LL]);
}
// Instantiate and draw our chart, passing in some options
var chart = new google.visualization.ComboChart(document.getElementById('ColumnChart'));
//var chart1 = new google.visualization.PieChart(document.getElementById('piechart1'));
chart.draw(data,
{
title: "Column Chart of Google Chart in Asp.net",
position: "top",
fontsize: "14px",
seriesType: 'bars',
series: { 2: { type: 'line' } },
series: { 1: { type: 'line' } },
chartArea: { width: '50%' },
});
Only for the series 1 graph is getting generated like below.Only one line is geeting generated in this graph
The chart options should only have one key for series, which can have multiple series definitions.
series: {
1: { type: 'line' },
2: { type: 'line' }
},
Example...
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawchart1
});
function drawchart1(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'KPI_MONTH');
data.addColumn('number', 'DIE');
data.addColumn('number', 'DIE_TS');
data.addColumn('number', 'DIE_LL');
data.addRow(['Jan-15', 80, 90, 80]);
data.addRow(['Feb-15', null, 90, 80]);
data.addRow(['Mar-15', 100, 90, 80]);
data.addRow(['Apr-15', 100, 90, 80]);
data.addRow(['May-15', 20, 90, 80]);
data.addRow(['Jun-15', 30, 90, 80]);
data.addRow(['Jul-15', 10, 90, 80]);
data.addRow(['Aug-15', 50, 90, 80]);
data.addRow(['Sep-15', 30, 90, 80]);
data.addRow(['Oct-15', 10, 90, 80]);
data.addRow(['Nov-15', 20, 90, 80]);
data.addRow(['Dec-15', 100, 90, 80]);
var chart = new google.visualization.ComboChart(document.getElementById('ColumnChart'));
chart.draw(data,
{
title: "Column Chart of Google Chart in Asp.net",
position: "top",
fontsize: "14px",
seriesType: 'bars',
series: {
1: { type: 'line' },
2: { type: 'line' }
},
chartArea: { width: '50%' },
});
}
<script src="https://www.google.com/jsapi"></script>
<div id="ColumnChart"></div>

how to create density map using googlemaps api

I want to create a density map similar to the link below
http://www.guardian.co.uk/news/datablog/interactive/2011/jun/22/us-casualties-afghanistan-state
Can anyone please steps tell how such type of maps can be created.
thank you
They're using a FusionTablesLayer to do this.
Their maps-related JS in full from that page:
var center = new google.maps.LatLng(38.0000,-97.0000);
var zoom = 4;
var legend_width = '150px';
var tableid = 1038573;
var location_column = 'geo';
var columns = {
'Killed in action': [
{
'min': 0,
'max': 10,
'color': '#f4cccc'
},
{
'min': 10,
'max': 30,
'color': '#ea9999'
},
{
'min': 30,
'max': 60,
'color': '#cc0000'
},
{
'min': 60,
'max': 90,
'color': '#990000'
},
{
'min': 90,
'max': 130,
'color': '#660000'
}
],
'Killed, not in action': [
{
'min': 1,
'max': 10,
'color': '#f4cccc'
},
{
'min': 10,
'max': 20,
'color': '#ea9999'
},
{
'min': 20,
'max': 30,
'color': '#cc0000'
}
],
'Wounded in action': [
{
'min': 0,
'max': 100,
'color': '#f4cccc'
},
{
'min': 100,
'max': 200,
'color': '#ea9999'
},
{
'min': 200,
'max': 400,
'color': '#cc0000'
},
{
'min': 400,
'max': 600,
'color': '#990000'
},
{
'min': 600,
'max': 1000,
'color': '#660000'
}
],
'Total deaths in Afghanistan per 100,000 pop': [
{
'min': 0,
'max': 0.2,
'color': '#f4cccc'
},
{
'min': 0.2,
'max': 0.4,
'color': '#ea9999'
},
{
'min': 0.4,
'max': 0.6,
'color': '#cc0000'
},
{
'min': 0.6,
'max': 1,
'color': '#990000'
},
{
'min': 1,
'max': 2,
'color': '#660000'
}
],
'Wounded, per 100,000 pop': [
{
'min': 0,
'max': 2,
'color': '#f4cccc'
},
{
'min': 2,
'max': 3,
'color': '#ea9999'
},
{
'min': 3,
'max': 4,
'color': '#cc0000'
},
{
'min': 4,
'max': 5,
'color': '#990000'
},
{
'min': 5,
'max': 8,
'color': '#660000'
}
]
}
var map, layer;
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
center: center,
zoom: zoom,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var style = [
{
featureType: 'administrative',
elementType: 'all',
stylers: [
{ visibility: 'off' }
]
}
];
var styledMapType = new google.maps.StyledMapType(style, {
map: map,
name: 'Styled Map'
});
map.mapTypes.set('map-style', styledMapType);
map.setMapTypeId('map-style');
layer = new google.maps.FusionTablesLayer({
query: {
select: location_column,
from: tableid
}
});
layer.setMap(map);
init_selectmenu();
addStyle(getKey());
}
function getKey() {
for(key in columns) {
return key;
}
}
// Initialize the drop-down menu
function init_selectmenu() {
var selectmenu = document.getElementById('selector');
for(column in columns) {
var option = document.createElement('option');
option.setAttribute('value', column);
option.innerHTML = column;
selectmenu.appendChild(option);
}
}
// Apply the style to the layer
function addStyle(column) {
var defined_styles = columns[column];
var styles = new Array();
for(defined_style in defined_styles) {
var style = defined_styles[defined_style];
styles.push({
where: generateWhere(column, style.min, style.max),
polygonOptions: {
fillColor: style.color,
fillOpacity: style.opacity ? style.opacity : 1
}
});
}
layer.set('styles', styles);
updateLegend(column);
}
// Create the where clause
function generateWhere(column_name, low, high) {
var whereClause = new Array();
whereClause.push("'");
whereClause.push(column_name);
whereClause.push("' >= ");
whereClause.push(low);
whereClause.push(" AND '");
whereClause.push(column_name);
whereClause.push("' < ");
whereClause.push(high);
return whereClause.join('');
}
// Create the legend with the corresponding colors
function updateLegend(column) {
var legendDiv = document.createElement('div');
var legend = new Legend(legendDiv, column);
legendDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].pop();
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legendDiv);
}
// Generate the content for the legend
function Legend(controlDiv, column) {
controlDiv.style.padding = '10px';
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '1px';
controlUI.style.width = legend_width;
controlUI.title = 'Legend';
controlDiv.appendChild(controlUI);
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = legendContent(column);
controlUI.appendChild(controlText);
}
function legendContent(column) {
var defined_styles = columns[column];
// Generate the content for the legend using colors from object
var controlTextList = new Array();
controlTextList.push('<p><b>');
controlTextList.push(column);
controlTextList.push('</b></p>');
for(defined_style in defined_styles) {
var style = defined_styles[defined_style];
controlTextList.push('<div style="background-color: ');
controlTextList.push(style.color);
controlTextList.push('; height: 20px; width: 20px; margin: 3px; float: left;"></div>');
controlTextList.push(style.min);
controlTextList.push(' - ');
controlTextList.push(style.max);
controlTextList.push('<br style="clear: both;"/>');
}
controlTextList.push('<br />');
return controlTextList.join('');
}
My addin for Excel does exactly this.