jvectorMap plotting data from db - javascript

I'm trying to plot data that I get from the DB, but I have no luck with figuring how to deal with the json array and pass it to the plotting plugin (jvectorMap)
Here is the structure of my json array
{
"countries":[
{
"cname":"Albania",
"ccode":"AL",
"name":"John",
"percent":"20"
},
{
"cname":"Austria",
"ccode":"AT",
"name":"Doe",
"percent":"30"
}
]
}
javaScript in HTML
<script>
var dataC = "<?php echo $mapData?>";
$(function(){
$('#world-map').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
values: dataC[ccode],
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'
}]
},
onLabelShow: function(e, el, code){
el.html(el.html()+dataC[ccode]+dataC[name]+dataC[percent]+dataC[cname]);
}
});
});
</script>
Essentially I would like to have my data plotted based on the ISO code in the ccode key. For instance when i point on the map i would like to see in the marker the data from the name, percentage and the cname field too. Thanks.

var dataC = {
"countries": [
{
"cname": "Albania",
"ccode": "AL",
"name": "John",
"percent": "20"},
{
"cname": "Austria",
"ccode": "AT",
"name": "Doe",
"percent": "30"}
]
};
//---------------------------------------------------------------------------
// The data for the jVectorMap is expected to be an object with
// member variables for each country code and an associated value.
// You need to convert your `dataC` data into that format.
//---------------------------------------------------------------------------
var countryData = [];
//for each country, set the code and value
$.each(dataC.countries, function() {
countryData[this.ccode] = this.percent;
});
$(function() {
$('#world-map').vectorMap({
map: 'world_mill_en',
series: {
regions: [{
values: countryData, //load the data
scale: ['#C8EEFF', '#0071A4'],
normalizeFunction: 'polynomial'}]
},
//-----------------------------------------------
// changed to onRegionLabelShow from onLabelShow
//-----------------------------------------------
onRegionLabelShow: function(e, el, code) {
//search through dataC to find the selected country by it's code
var country = $.grep(dataC.countries, function(obj, index) {
return obj.ccode == code;
})[0]; //snag the first one
//only if selected country was found in dataC
if (country != undefined) {
el.html(el.html() +
"<br/><b>Code: </b>" +country.ccode +
"<br/><b>Name: </b>" + country.name +
"<br/><b>Percent: </b>" + country.percent +
"<br/><b>Country Name: </b>"+ country.cname);
}
}
});
});​

Related

How can I filter a json and get the mean to create a line plot in js?

I have data in json format, so i want plot with plotly js, what i need is to create a plot of different states by semester, so i need to filter each state (example California), after that i need to get the mean of each semester and finally plot it.
So far i have this code, but i dont know how to filter im new in js
// Trace1
var trace1 = {
x: data.map(row => row.date),
y: data.map(row => row.snap_biannual_chan),
text: data.map(row => row.state_name),
name: "snap_biannual_chan",
type: "line"
};
// Combining both traces
var data = [trace1];
// Apply the group barmode to the layout
var layout = {
title: "Practice",
xaxis: {
categoryorder: "array",
}
};
// Render the plot to the div tag with id "plot"
Plotly.newPlot("plot", data, layout)
this is the json example:
"county_state_id": "06001",
"pop_hispan_prop": ".1176472187212034",
"pop_un_st": 3059000,
"state_name": "California",
"county_name": "Alameda County",
"pop_un_co": 109000,
"state_id": "06",
"county_id": "001",
"pop_co": 1605217,
"pop_st": 38654206,
"state_abbrev": "CA",
"semester": "0118",
"snap_beneficiaries": 102034,
"snap_biannual_chan": -2.02980374083036,
"sem": "Jan18",
"pop_un_co_per": 6.790359185082141,
"pop_un_st_per": 7.913757173022776,
"year": 2018,
"month": 1,
"date": "January2018"
You can use the array filter() and reduce() methods to calculate the mean without having to micromanage a bunch of loops and variables. Here's an example:
const data = [
{ state_id: "01", snap_biannual_chan: 5.5 },
{ state_id: "01", snap_biannual_chan: 3 },
{ state_id: "02", snap_biannual_chan: 5 }
];
const state01 = data.filter(x => x.state_id === "01");
const meanState01 = state01.reduce((acc, item) => {
acc.sum += item.snap_biannual_chan;
acc.mean = acc.sum / state01.length
return acc;
}, { sum: 0, mean: 0 });
console.log(meanState01);
console.log("the mean: ", meanState01.mean);

Changing js array on a html

I want to manipulate an js array after a click but its not triggering.
example is here
https://datatables.net/examples/data_sources/js_array.html
what did i do is: (i need to re set dataset which is loaded into table previously please take a look at above example)
$(document).ready(function() {
$(".retrievemenu").click(function() {
//alert( this.id );
//$('#menus').hide();
var restid = this.id;
data = [
["sasa", "a", "a"]
];
$.post("server.php", {
retrievemenu: 1,
restid: restid
}, function(data) {
console.log(data);
$('#menus').hide();
$('#menus').DataTable({
data: data,
columns: [{
title: "Restaurant Name"
}, {
title: "Menu Name"
}, {
title: "Actions"
}
]
});
$('#menus').show();
});
});
});

Create bar chart using mysql data

I want create bar using mysql data which is returned in JSON Format.
[
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
]
I want to create like this chart
But problem is that this gets formatted from Table. But I have data in JSON as shown above.
Here is the link I am following. Can we convert the JSON Data in a Format so that it can populate chart based on the Data as shown
https://blueflame-software.com/bar-chart-with-data-from-mysql-using-highcharts/
You can process the JSON in the Javascript to build the data required for the chart as shown below:
var jsonFromServer = [
{
"Score": "84",
"Trainer": "Jamshaid",
"Subject Name": "Java"
},
{
"Score": "50",
"Trainer": "Zaid",
"Subject Name": "Android"
},
{
"Score": "40",
"Trainer": "Sajjad",
"Subject Name": "iOS"
},
{
"Score": "50",
"Trainer": "Jamshaid",
"Subject Name": "iOS"
}
];
The above is data from server captured in a variable
The below code helps you to extract the Y axis Values (i.e the unique subject names) from the JSON response:
function getSubjects(){
var subjectsMap = {};
$.each(jsonFromServer, function(index, value){
if(!subjectsMap[value['Subject Name']]){
subjectsMap[value['Subject Name']] = 1;
}
});
return $.map(subjectsMap, function(index, val){ return val; });
}
Then we need to extract the Scores for each trainer in different subject which should be of form: [{name: "Trainer", data: []}] where data is an array of scores in subject whose order should be same as the order of subjects appearing in the Y axis data. Which can be achieved using the below code:
function getTrainers(){
var trainersMap = {};
$.each(jsonFromServer, function(index, value){
if(!trainersMap[value['Trainer']]){
trainersMap[value['Trainer']] = 1;
}
});
return $.map(trainersMap, function(index, val){ return val; });
}
function getMarks(){
var subjects = getSubjects();
var trainers= getTrainers();
var marks = {};
//initialize the trainers scores in all subjects to 0
$.each(trainers, function(index, trainer){
if ( !marks[trainer]){
marks[trainer] = {};
}
$.each(subjects, function(idx2, sub){
marks[trainer][sub] = 0;
});
});
//now populate with the actual values obtained from server
$.each(subjects, function(idx2, sub){
$.each(jsonFromServer, function(index, value){
var trainer = value['Trainer'];
var subName = value['Subject Name'];
var score = value['Score'];
if ( sub == subName){
marks[trainer][sub] = score;
}
});
});
//now format the marks object into the format required for highcharts
//i.e an array of object with properties [{name: "", data:[]}]
return $.map(marks, function(val, index){
var scoreArray = [];
$.each(val, function(index, score){
scoreArray.push(parseInt(score));
});
return {"name": index, "data": scoreArray};
});
}
The working code can be found in the fiddle here.

Sorting data in MemoryStore (or any arbitrary data array)

Does Dojo hat any utilities for sotring the data within MemoryStore, or optionally, within any data collection?
I'd need all data from the MemoryStore, but sorted by single evt. more columns. Something like Collections.sort in Java...
I'd expect Store to have sort function, but I couldn't find anything in the documentation.
The dojo/store API allows sorting data at query time only, as far as I know. For example:
var store = new Memory({
data: [{
"firstName": "Bird",
"name": "Schultz"
}, {
"firstName": "Brittany",
"name": "Berg"
}, {
"firstName": "Haley",
"name": "Good"
}, {
"firstName": "Randolph",
"name": "Phillips"
}, {
"firstName": "Bernard",
"name": "Small"
}, {
"firstName": "Leslie",
"name": "Wynn"
}, {
"firstName": "Mercado",
"name": "Singleton"
}, {
"firstName": "Esmeralda",
"name": "Huber"
}, {
"firstName": "Juanita",
"name": "Saunders"
}, {
"firstName": "Beverly",
"name": "Clemons"
}]
});
console.log("Alphabetically by first name:");
store.query({}, {
sort: [{
attribute: "firstName",
descending: false
}]
}).forEach(function(person) {
console.log(person.firstName + " " + person.name);
});
You can provide multiple sort attributes as well.
Full example can be found on JSFiddle: http://jsfiddle.net/9HtT3/
When we sort our Data, we do this actual before the Items are stored. We take the filtered Values that are saved in an array and use array.sort()and called inside a function SortByName or SortByNumbers
looks like this:
function streetsToCombobox(results){
var adress;
var values = [];
var testVals={};
var features = results.features;
require(["dojo/_base/array","dojo/store/Memory","dijit/registry","dojo/domReady!"], function(array,Memory,registry){
if (!features[0]) {
alert(noDataFound);
}
else {
array.forEach(features, function(feature, i){
adress = feature.attributes.STRASSE;
if (!testVals[adress]) {
testVals[adress] = true;
values.push({
name: adress
});
}
});
values.sort(SortByName);
var dataItems = {
identifier: 'name',
label: 'name',
items: values
};
storeStreet = new Memory({
data: dataItems
});
//fill existing Combobox ID,NAME,VALUE,SEARCHATTR,ONCHANGE,STORENAME,COMBOBOX
fillExistingCombobox(
"adrSearchSelectCB",
"adrSearchSelectCBName",
"",
"name",
getAdresses,
storeStreet,
registry.byId("adrSearchSelectCBId")
);
}
});
}
function SortByName(x,y) {
return ((x.name == y.name) ? 0 : ((x.name > y.name) ? 1 : -1 ));
}
Maybe this brings some Ideas to you how to solve your Question.
Regards, Miriam

JQuery: Building a dictionary with values as an array from Json

Some json data:
[
{
"country": "US",
"id": 1,
"name": "Brad",
},
{
"country": "US",
"id": 2,
"name": "Mark",
},
{
"country": "CAN",
"id": 3,
"name": "Steve",
},
]
What I'd like to do is create a dictionary from this, {country: [name id]}:
$.getJSON('result.json', function(result) {
var dict = {}
$.each(result, function(key, value){
//build dict
});
});
//{ 'US': ['Brad' 1, 'Mark' 2], 'CAN': ['Steve' 3]
What's the best way of going about this with jquery? Dictionaries constantly confound me for some reason.
$.getJSON('result.json', function(result) {
var dict = {}
$.each(result, function(key, value){
//build dict
var exists = dict[value.country];
if(!exists){
dict[value.country] = [];
}
exists.push([value.name, value.id]);
//if it was my code i would do this ...
//exists.push(value);
});
});
Personally, I don't like converting them to an array, I would keep them as values, which make them easier to manipulate.
var dict = {}
$.each(result, function(i, item){
if(!dict[item.country]) dict[item.country] = [];
dict[item.country].push([item.name, item.id]);
});
You can see this in action on this jsFiddle demo.
For the data you provided, this is the result it gives:
{"US":[["Brad",1],["Mark",2]],"CAN":[["Steve",3]]}

Categories

Resources