Error Loading another script in the JS File - javascript

I am trying to create chart in my widget. I am using AM Charts for this purpose.
I am having a script file(.js) in which I am unable to load the AM Charts. The scripts are getting loaded but I am getting the error "AmCharts is not defined".
My Widget Code:
(function () {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
jQuery = window.jQuery.noConflict(true);
main();
}
/******** Our main function ********/
function main() {
var LanguageVal = 1;
jQuery(document).ready(function ($) {
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "Content/css/DailyPrices.css"
});
css_link.appendTo('head');
var css_link1 = $("<link>", {
rel: "stylesheet",
type: "text/css",
media:"all",
href: "https://www.amcharts.com/lib/3/plugins/export/export.css"
});
css_link1.appendTo('head');
var css_link2 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/amcharts.js",
});
css_link2.appendTo('head');
var css_link3 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/serial.js",
});
css_link3.appendTo('head');
var css_link4 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/plugins/export/export.min.js",
});
css_link4.appendTo('head');
var css_link5 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/themes/light.js",
});
css_link5.appendTo('head');
$.ajax({
url: "http://localhost:44360/api/TodayPrice/DailyPrice",
data: { Language: LanguageVal },
success: function (result) {
var list1 = result.data;
var list2 = result.HeaderLst;
var TodayDieselPrice = list1[0].TodayDieselPrice;
var TodayPetrolPrice = list1[0].TodayPetrolPrice;
var YesterdayDieselPrice = list1[0].YesterdayDieselPrice;
var YesterdayPetrolPrice = list1[0].YesterdayPetrolPrice;
var PetrolText = list1[0].PetrolText;
var DieselText = list1[0].DieselText;
var PetrolIconColor = list1[0].PetrolIconColor;
var DieselIconColor = list1[0].DieselIconColor;
var FirstHeader = list2[0].FirstHeader;
var SecondHeader = list2[0].SecondHeader;
var ThirdHeader = list2[0].ThirdHeader;
var FourthHeader = list2[0].FourthHeader;
var FifthHeader = list2[0].FifthHeader;
var LastHeader = list2[0].LastHeader;
$("#example-widget-container").append('<div class="WholeDiv row"><div class="col-md-12 firstrow"><div style="float:left;padding:8px">'+FirstHeader+'</div><div style="float:right"><img src="Content/images/Petrol-pump-icon.png"/></div></div>'+
'<div class="col-md-12 secondrow"><div class="col-md-3">'+SecondHeader+'</div><div class="col-md-4">'+ThirdHeader+'</div><div class="col-md-2"></div><div class="col-md-3">'+FourthHeader+'</div></div><div class="col-md-12 thirdrow"><div class="col-md-3">'+PetrolText+'</div><div class="col-md-4">'+YesterdayPetrolPrice+'</div><div class="col-md-2"><div class="PIconColor"></div></div><div class="col-md-3">'+TodayPetrolPrice+'</div></div>'+
'<div class="col-md-12 fourthrow"><div class="col-md-3">'+DieselText+'</div><div class="col-md-4">'+YesterdayDieselPrice+'</div><div class="col-md-2"><div class="DIconColor"></div></div><div class="col-md-3">'+TodayDieselPrice+'</div></div><div class="col-md-12 fifthrow"> <div style="float:left"><a>'+FifthHeader+'</a></div> <div style="float:right" class="sponsorDiv"><div class="sponsorTextDiv">Powered By ICICI</div></div></div></div>');
$("#example-widget-container").append('<div id="chartdiv"></div>');
if (PetrolIconColor == "Red") {
$('.PIconColor').addClass('arrow-up');
}
else
{
$('.PIconColor').addClass('arrow-down');
}
if (DieselIconColor == "Red") {
$('.DIconColor').addClass('arrow-up');
}
else {
$('.DIconColor').addClass('arrow-down');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 70,
"dataProvider": [{
"country": "USA",
"visits": 3025,
"color": "#FF0F00"
}, {
"country": "China",
"visits": 1882,
"color": "#FF6600"
}, {
"country": "Japan",
"visits": 1809,
"color": "#FF9E01"
}, {
"country": "Germany",
"visits": 1322,
"color": "#FCD202"
}, {
"country": "UK",
"visits": 1122,
"color": "#F8FF01"
}, {
"country": "France",
"visits": 1114,
"color": "#B0DE09"
}, {
"country": "India",
"visits": 984,
"color": "#04D215"
}, {
"country": "Spain",
"visits": 711,
"color": "#0D8ECF"
}, {
"country": "Netherlands",
"visits": 665,
"color": "#0D52D1"
}, {
"country": "Russia",
"visits": 580,
"color": "#2A0CD0"
}, {
"country": "South Korea",
"visits": 443,
"color": "#8A0CCF"
}, {
"country": "Canada",
"visits": 441,
"color": "#CD0D74"
}],
"valueAxes": [{
"axisAlpha": 0,
"position": "left",
"title": "Visitors from country"
}],
"startDuration": 1,
"graphs": [{
"balloonText": "<b>[[category]]: [[value]]</b>",
"fillColorsField": "color",
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
}],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "country",
"categoryAxis": {
"gridPosition": "start",
"labelRotation": 45
},
"export": {
"enabled": true
}
});
});
}
})(); // We call our anonymous function immediately
HTML Code:
<div id="example-widget-container"></div>

Try following order atleast AmCharts issue seems to be resolved
function loadChart() {
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"marginRight": 70,
"dataProvider": [{
"country": "USA",
"visits": 3025,
"color": "#FF0F00"
}, {
"country": "China",
"visits": 1882,
"color": "#FF6600"
}, {
"country": "Japan",
"visits": 1809,
"color": "#FF9E01"
}, {
"country": "Germany",
"visits": 1322,
"color": "#FCD202"
}, {
"country": "UK",
"visits": 1122,
"color": "#F8FF01"
}, {
"country": "France",
"visits": 1114,
"color": "#B0DE09"
}, {
"country": "India",
"visits": 984,
"color": "#04D215"
}, {
"country": "Spain",
"visits": 711,
"color": "#0D8ECF"
}, {
"country": "Netherlands",
"visits": 665,
"color": "#0D52D1"
}, {
"country": "Russia",
"visits": 580,
"color": "#2A0CD0"
}, {
"country": "South Korea",
"visits": 443,
"color": "#8A0CCF"
}, {
"country": "Canada",
"visits": 441,
"color": "#CD0D74"
}],
"valueAxes": [{
"axisAlpha": 0,
"position": "left",
"title": "Visitors from country"
}],
"startDuration": 1,
"graphs": [{
"balloonText": "<b>[[category]]: [[value]]</b>",
"fillColorsField": "color",
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
}],
"chartCursor": {
"categoryBalloonEnabled": false,
"cursorAlpha": 0,
"zoomable": false
},
"categoryField": "country",
"categoryAxis": {
"gridPosition": "start",
"labelRotation": 45
},
"export": {
"enabled": true
}
});
}
(function () {
// Localize jQuery variable
var jQuery;
/******** Load jQuery if not present *********/
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') {
var script_tag = document.createElement('script');
script_tag.setAttribute("type", "text/javascript");
script_tag.setAttribute("src",
"https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "Content/css/DailyPrices.css"
});
css_link.appendTo('head');
var css_link1 = $("<link>", {
rel: "stylesheet",
type: "text/css",
media:"all",
href: "https://www.amcharts.com/lib/3/plugins/export/export.css"
});
css_link1.appendTo('head');
var css_link2 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/amcharts.js",
});
css_link2.appendTo('head');
var css_link3 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/serial.js",
});
css_link3.appendTo('head');
if (script_tag.readyState) {
script_tag.onreadystatechange = function () { // For old versions of IE
if (this.readyState == 'complete' || this.readyState == 'loaded') {
scriptLoadHandler();
}
};
} else {
script_tag.onload = scriptLoadHandler;
}
// Try to find the head, otherwise default to the documentElement
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
else {
// The jQuery version on the window is the one we want to use
jQuery = window.jQuery;
main();
}
/******** Called once jQuery has loaded ******/
function scriptLoadHandler() {
setTimeout(function(){
// wait for amchart to load
var css_link4 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/plugins/export/export.min.js",
});
css_link4.appendTo('head');
jQuery = window.jQuery.noConflict(true);
var css_link5 = $("<script>", {
type: "text/javascript",
src: "https://www.amcharts.com/lib/3/themes/light.js",
});
css_link5.appendTo('head');
main();
}, 1000);
}
/******** Our main function ********/
function main() {
var LanguageVal = 1;
jQuery(document).ready(function ($) {
$.ajax({
url: "http://localhost:44360/api/TodayPrice/DailyPrice",
data: { Language: LanguageVal },
success: function (result) {
var list1 = result.data;
var list2 = result.HeaderLst;
var TodayDieselPrice = list1[0].TodayDieselPrice;
var TodayPetrolPrice = list1[0].TodayPetrolPrice;
var YesterdayDieselPrice = list1[0].YesterdayDieselPrice;
var YesterdayPetrolPrice = list1[0].YesterdayPetrolPrice;
var PetrolText = list1[0].PetrolText;
var DieselText = list1[0].DieselText;
var PetrolIconColor = list1[0].PetrolIconColor;
var DieselIconColor = list1[0].DieselIconColor;
var FirstHeader = list2[0].FirstHeader;
var SecondHeader = list2[0].SecondHeader;
var ThirdHeader = list2[0].ThirdHeader;
var FourthHeader = list2[0].FourthHeader;
var FifthHeader = list2[0].FifthHeader;
var LastHeader = list2[0].LastHeader;
$("#example-widget-container").append('<div class="WholeDiv row"><div class="col-md-12 firstrow"><div style="float:left;padding:8px">'+FirstHeader+'</div><div style="float:right"><img src="Content/images/Petrol-pump-icon.png"/></div></div>'+
'<div class="col-md-12 secondrow"><div class="col-md-3">'+SecondHeader+'</div><div class="col-md-4">'+ThirdHeader+'</div><div class="col-md-2"></div><div class="col-md-3">'+FourthHeader+'</div></div><div class="col-md-12 thirdrow"><div class="col-md-3">'+PetrolText+'</div><div class="col-md-4">'+YesterdayPetrolPrice+'</div><div class="col-md-2"><div class="PIconColor"></div></div><div class="col-md-3">'+TodayPetrolPrice+'</div></div>'+
'<div class="col-md-12 fourthrow"><div class="col-md-3">'+DieselText+'</div><div class="col-md-4">'+YesterdayDieselPrice+'</div><div class="col-md-2"><div class="DIconColor"></div></div><div class="col-md-3">'+TodayDieselPrice+'</div></div><div class="col-md-12 fifthrow"> <div style="float:left"><a>'+FifthHeader+'</a></div> <div style="float:right" class="sponsorDiv"><div class="sponsorTextDiv">Powered By ICICI</div></div></div></div>');
$("#example-widget-container").append('<div id="chartdiv"></div>');
if (PetrolIconColor == "Red") {
$('.PIconColor').addClass('arrow-up');
}
else
{
$('.PIconColor').addClass('arrow-down');
}
if (DieselIconColor == "Red") {
$('.DIconColor').addClass('arrow-up');
}
else {
$('.DIconColor').addClass('arrow-down');
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
}
});
loadChart();
});
}
})();

Related

AmCharts 3 - Remove Listener on first run (reference function inside itself)

I would like to know how to add a listener that only runs once, I believe in the end this is mostly a generic javascript question, but I might be missing something.
Here's what I have :
const listener = chart.addListener('rendered', () => {
console.log('Chart rendered! This should only print once!');
doSomethingToChart(chart);
chart.removeListener(chart, 'rendered', listener);
})
The problem here is, is not removing the listener, the console.log is printing on each render. How can I fix this?
addListener doesn't have a return value at all, nor makes any mention of one in the documentation, which is why your code doesn't work. Just store the function reference separately before you add the listner, then call removeListener on that reference and it will work, for example:
let counter = 0;
const listener = () => {
console.log('dataUpdated called', counter += 1);
};
chart.addListener('dataUpdated', listener);
let timer = setInterval(() => {
chart.validateData(); //triggers dataUpdated
if (counter == 3) {
chart.removeListener(chart, 'dataUpdated', listener);
console.log('dataUpdated removed')
chart.validateData(); //one more call to confirm that the listner no longer runs
clearInterval(timer);
}
}, 1500);
Demo:
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": [{
"country": "USA",
"visits": 2025
}, {
"country": "China",
"visits": 1882
}, {
"country": "Japan",
"visits": 1809
}, {
"country": "Germany",
"visits": 1322
}, {
"country": "UK",
"visits": 1122
}, {
"country": "France",
"visits": 1114
}, {
"country": "India",
"visits": 984
}, {
"country": "Spain",
"visits": 711
}, {
"country": "Netherlands",
"visits": 665
}, {
"country": "Russia",
"visits": 580
}, {
"country": "South Korea",
"visits": 443
}, {
"country": "Canada",
"visits": 441
}, {
"country": "Brazil",
"visits": 395
}],
"graphs": [{
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits"
}],
"categoryField": "country"
}, 100);
let counter = 0;
const listener = () => {
console.log('dataUpdated called', counter += 1);
};
chart.addListener('dataUpdated', listener);
let timer = setInterval(() => {
chart.validateData(); //this triggers dataUpdated
if (counter == 3) {
chart.removeListener(chart, 'dataUpdated', listener);
console.log('dataUpdated removed')
chart.validateData(); //confirm that listner isn't called anymore
clearInterval(timer);
}
}, 1500);
html,
body {
width: 100%;
height: 100%;
margin: 0px;
}
#chartdiv {
width: 100%;
height: 100%;
}
<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>
Just use use the listener like this:
const listener = () => {
console.log('Chart rendered! This should only print once!');
// ...
chart.removeListener(chart, 'rendered', listener);
};
chart.addListener('rendered', listener);
Here is a codepen showing the behavior.
Alternatively you can use an external variable to save the state:
let executedOnce = false;
chart.addListener('rendered', () => {
if (executedOnce) {
return;
}
executedOnce = true;
console.log('Chart rendered! This should only print once!');
// ...
});
Beside that I would recommend switching to amcharts4, because it is much more flexible and has even new chart types. You can migrate easily, beginning with just one chart. You can use amcharts3 and amcharts4 in parallel (Migration Guide).
In amcharts4 you can subscribe once to an event (docs):
chart.events.once('datavalidated' => {
// ...
});

heat map is not clear

Does anyone know how to set a colour range for this map? The variations between the values aren't large enough to notice the change in colour. So most of the values on the map appear to be in the same colour. I would either like to set my own colours or change much these colours vary by.
I cant find the answer on how to do this in react anywhere
import React, { Component } from 'react';
import AmCharts from "#amcharts/amcharts3-react";
import { connect } from "react-redux"
import { lookup } from 'country-data';
import * as adapter from "../Adapter.js";
class App extends Component {
constructor(props) {
super(props)
this.state = {
allCountriesHouseholdSpending: null,
selectedCoutry: null,
countrySpending: [{
"id": "AU",
"value": 4447100
},
{
"id": "US",
"value": 658188
}]
}
}
componentDidMount() {
adapter.getAllCountriesrtyHouseholdSpending()
.then(spendingData => this.setState({ allCountriesHouseholdSpending: spendingData }))
}
selectedCountrySpending = (country) => {
let selectedCity = country.mapObject.enTitle
if (selectedCity !== "Russia" && selectedCity !== "Venezuela" && selectedCity !== "Bolivia" && selectedCity !== "Svalbard and Jan Mayen" && selectedCity !== "Syria" && selectedCity !== "Tanzania" && selectedCity !== "Democratic Republic of Congo") {
// console.log(lookup.countries({ name: selectedCity }));
console.log(lookup.countries({ name: selectedCity })[0].alpha3);
console.log('selected!', selectedCity)
return selectedCity
}
}
render() {
const config = {
"type": "map",
"theme": "light",
"colorSteps": 10,
"dataProvider": {
"map": "worldLow",
"getAreasFromMap": true,
"areas": [{
"id": "AU",
"value": 658188.6034,
"selected": true
},
{
"id": "AT",
"value": 217653.4063
},
{
"id": "BE",
"value": 255659.6354
},
{
"id": "CA",
"value": 896977.0966
},
],
valueLegend: {
divId: "legenddiv",
left: 10,
bottom: 0,
minValue: "little",
maxValue: "a lot!"
},
},
"areasSettings": {
"selectedColor": "#CC0000",
"selectable": true,
"balloonText": "National Spending in [[title]]: <b>[[value]]</b>"
},
"listeners": [{
"event": "clickMapObject",
"method": (e) => {
console.log(e.mapObject.enTitle)
this.selectedCountrySpending(e)
}
}]
}
return (
<AmCharts.React style={{ width: "100%", height: "600px" }} options={config} />
);
}
}
const mapStateToProps = (state) => ({
})
const mapDispatchToProps = (dispatch) => ({
})
export default connect(mapStateToProps, mapDispatchToProps)(App)
You can customize the start and end colors by setting color and colorSolid in your areasSettings. You can also specify your own color by setting the color directly in the area object, e.g.
{
"id": "AU",
"value": 88323532,
"color": "#00ff00"
},
// ...
Note that setting getAreasFromMap: true essentially enables all the other areas as if they were defined in the dataProvider, which may not be what you want.
Here's a demo of color and colorSolid:
var chart = AmCharts.makeChart("chartdiv", {
"type": "map",
"theme": "light",
"colorSteps": 10,
"dataProvider": {
"map": "worldLow",
//"getAreasFromMap": true,
"areas": [{
"id": "AU",
"value": 658188.6034,
"selected": true
},
{
"id": "AT",
// "color": "#0000ff", //if you want to specify a color directly on an area
"value": 217653.4063
},
{
"id": "BE",
"value": 255659.6354
},
{
"id": "CA",
"value": 896977.0966
},
],
valueLegend: {
divId: "legenddiv",
left: 10,
bottom: 0,
minValue: "little",
maxValue: "a lot!"
},
},
"areasSettings": {
"color": "#880000",
"colorSolid": "#008888",
"selectedColor": "#CC0000",
"selectable": true,
"balloonText": "National Spending in [[title]]: <b>[[value]]</b>"
},
"listeners": [{
"event": "clickMapObject",
"method": (e) => {
}
}]});
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
#chartdiv {
width: 100%;
height: 100%;
}
<script src="//www.amcharts.com/lib/3/ammap.js"></script>
<script src="//www.amcharts.com/lib/3/maps/js/worldLow.js"></script>
<script src="//www.amcharts.com/lib/3/themes/light.js"></script>
<div id="chartdiv"></div>

Highlight a single bar on click in amcharts

I have a bar chart from amcharts. I need to highlight a single bar on click on bar. Current scenario is when I click multiple bar, all bars highlighted.
Here is my code
"listeners": [{
"event": "clickGraphItem",
"method": function(event) {
var node = event.item.columnGraphics.node.lastChild;
node.setAttribute("stroke","#8198b4");
node.setAttribute("fill","#8198b4");
}
}]
Any help? Thank You.
Instead of modifying the node, use fillColorsField instead, which allows you to set/unset the currently selected column's highlight and allows you to go through the rest of the chart's data to make sure only one item is selected.
"graphs": [{
// ...
"fillColorsField": "selected"
}],
"zoomOutOnDataUpdate": false, //recommended so that the chart doesn't reset the current zoom after clicking on a column
"listeners": [{
"event": "clickGraphItem",
"method": function(e) {
//if the current item is already selected, deselect it
if (e.item.dataContext.selected) {
e.item.dataContext.selected = undefined;
}
else {
//otherwise, find any other columns that were selected and deselect them
for (var i = 0; i < e.chart.dataProvider.length; ++i) {
if (e.chart.dataProvider[i].selected) {
e.chart.dataProvider[i].selected = undefined;
break;
}
}
e.item.dataContext.selected = "#8198b4";
}
e.chart.validateData(); //update chart
}
}]
Demo below:
var chart = AmCharts.makeChart("chartdiv", {
"type": "serial",
"dataProvider": [{
"country": "USA",
"visits": 2025
}, {
"country": "China",
"visits": 1882
}, {
"country": "Japan",
"visits": 1809
}, {
"country": "Germany",
"visits": 1322
}, {
"country": "UK",
"visits": 1122
}, {
"country": "France",
"visits": 1114
}, {
"country": "India",
"visits": 984
}, {
"country": "Spain",
"visits": 711
}, {
"country": "Netherlands",
"visits": 665
}, {
"country": "Russia",
"visits": 580
}, {
"country": "South Korea",
"visits": 443
}, {
"country": "Canada",
"visits": 441
}, {
"country": "Brazil",
"visits": 395
}],
"graphs": [{
"fillAlphas": 0.9,
"lineAlpha": 0.2,
"type": "column",
"valueField": "visits",
"fillColorsField": "selected"
}],
"categoryField": "country",
"zoomOutOnDataUpdate": false, //recommended so that the chart doesn't reset the current zoom after clicking on a column
"listeners": [{
"event": "clickGraphItem",
"method": function(e) {
//if the current item is already selected, deselect it
if (e.item.dataContext.selected) {
e.item.dataContext.selected = undefined;
}
else {
//otherwise, find any other columns that were selected and deselect them
for (var i = 0; i < e.chart.dataProvider.length; ++i) {
if (e.chart.dataProvider[i].selected) {
e.chart.dataProvider[i].selected = undefined;
break;
}
}
e.item.dataContext.selected = "#8198b4";
}
e.chart.validateData(); //update chart
}
}]
});
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
#chartdiv {
width: 100%;
height: 100%;
}
<script src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script src="//www.amcharts.com/lib/3/serial.js"></script>
<div id="chartdiv"></div>

Embed json string in amchart chart?

I'm trying to embed some json into my amcharts. This is the javascript code in the html:
<script type="text/javascript">
AmCharts.makeChart("mapdiv", {
"type": "map",
"imagesSettings": {
"rollOverColor": "#089282",
"rollOverScale": 1,
"selectedScale": 0.5,
"selectedColor": "#089282",
"color": "#13564e",
"selectable": false,
"bringForwardOnHover": false
},
"areasSettings": {
"color": "#D3D3D3",
"autoZoom": true
},
"data": {
"map": "puertoRicoHigh"
},
"dataLoader": {
"url": "http://OurServer/Service1.svc/GetLocations",
"format": "json",
"showErrors": true,
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
}
});
</script>
And this is what the json looks like: [{"title":"Site1","latitude":18.37,"longitude":-67.18},{"title":"Site2","latitude":18.20,"longitude":-65.80}]
I've been trying to embed this json into the code, but I'm having trouble doing so.
I tried using dataprovider instead of dataloader since it's not an http request, but I know I'm missing something:
<script type="text/javascript">
AmCharts.makeChart("mapdiv", {
"type": "map",
"imagesSettings": {
"rollOverColor": "#089282",
"rollOverScale": 1,
"selectedScale": 0.5,
"selectedColor": "#089282",
"color": "#13564e",
"selectable": false,
"bringForwardOnHover": false
},
"areasSettings": {
"color": "#D3D3D3",
"autoZoom": true
},
"data": {
"map": "puertoRicoHigh"
},
"dataProvider": [{"title":"Site1","latitude":18.3764,"longitude":-67.1819},{"title":"Site2","latitude":18.2001,"longitude":-65.8081}],
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
});
</script>
The map dataProvider is an object, not an array, whose structure is demonstrated on the map demos on the AmCharts website. Since your JSON is basically an array of map images, going by the postProcess method, you can restructure your dataProvider like so, adding type: "circle" to each image and skipping the need for any further processing:
dataProvider: {
map: "puertoRicoHigh",
images: [
{"title":"Site1","latitude":18.3764,"longitude":-67.1819, "type": "circle"},
{"title":"Site2","latitude":18.2001,"longitude":-65.8081, "type": "circle"}
]
}
Demo:
AmCharts.makeChart("mapdiv", {
"type": "map",
"imagesSettings": {
"rollOverColor": "#089282",
"rollOverScale": 1,
"selectedScale": 0.5,
"selectedColor": "#089282",
"color": "#13564e",
"selectable": false,
"bringForwardOnHover": false
},
"areasSettings": {
"color": "#D3D3D3",
"autoZoom": true
},
"dataProvider": {
"map": "puertoRicoHigh",
"images": [{
"title": "Site1",
"latitude": 18.3764,
"longitude": -67.1819,
"type": "circle"
},
{
"title": "Site2",
"latitude": 18.2001,
"longitude": -65.8081,
"type": "circle"
}
]
}
});
<script src="//www.amcharts.com/lib/3/ammap.js"></script>
<script src="//www.amcharts.com/lib/3/maps/js/puertoRicoHigh.js"></script>
<div id="mapdiv" style="width: 100%; height: 400px;"></div>

Hide legend if value is 0 - Kendo UI Pie Chart

I've have Kendo pie chart and its legend still show even there is no value.
Is it possible to hide legend that no value or value = 0. I'm passing value through the function, so I does not know which value is 0. I've tried to set up data in array but I am stuck. Anybody can help me...
Here is my script:
function createPieChart(a,b,c,d) {
var e = a+b+c+d;
var aa = a/e*100;
var bb = b/e*100;
var cc = c/e*100;
var dd = d/e*100;
var perA = Math.round(aa*100.0)/100.0;
var perB = Math.round(bb*100.0)/100.0;
var perC = Math.round(cc*100.0)/100.0;
var perD = Math.round(dd*100.0)/100.0;
var arrValue = [perA, perB, perC, perD];
var data = [{
"source": "Positive",
"percentage": perA,
"color": "#9de219",
"explode": true
},{
"source": "Neutral",
"percentage": perB,
"color": "#90cc38"
},{
"source": "Negative",
"percentage": perC,
"color": "#068c35"
},{
"source": "Unknown",
"percentage": perD,
"color": "#006634"
}];
$("#chart_div").kendoChart({
dataSource: {
transport: {
read: function(e) {
e.success(data);
}
}
},
title: {
position: "top",
text: "Sentiment Result"
},
legend: {
position: "bottom",
visible: true
},
seriesDefaults: {
labels: {
visible: false,
template: "#= category #: \n #= value#%"
}
},
series: [{
type: "pie",
startAngle: 150,
field: "percentage",
categoryField: "source",
colorField: "color",
explodeField: "explode"
}],
tooltip: {
visible: true,
template: "${ category } - ${ value }%"
}
}
Replace this code:
var data = [{
"source": "Positive",
"percentage": perA,
"color": "#9de219",
"explode": true
},{
"source": "Neutral",
"percentage": perB,
"color": "#90cc38"
},{
"source": "Negative",
"percentage": perC,
"color": "#068c35"
},{
"source": "Unknown",
"percentage": perD,
"color": "#006634"
}];
With this code:
var arrValue = [perA, perB, perC, perD];
var arrSource = ["Positive","Neutral","Negative","Unknown"];
var arrColor = ["#9de219","#90cc38","#068c35","#006634"];
var data=[];
for (var i=0; i<arrValue.length; i++){
if(arrValue[i]>0){
data.push({
source: arrSource[i],
percentage: arrValue[i],
color: arrColor[i],
explode: true
});
}
}

Categories