How to display data in US Heat Map - Javascript - Laravel 5 - javascript

I want to display data in a JS Heat map like this one:
This is the 2 diffrent types of data I'am receiving:
Im getting the data like this:
public function index() {
$regions = DB::table('locations')
->select('regionCode', DB::raw('count(id) as total'))
->groupBy('regionCode')
->get();
$newRegions = [];
foreach( $regions as $region ){
$newRegions[$region->regionCode] = $region->total;
}
return view('admin.dashboard-v2', compact('newRegions'));
}
And this is how I'm SUPPOSED to display it:
var map = AmCharts.makeChart( "chartdiv", {
type: "map",
"theme": "light",
colorSteps: 10,
dataProvider: {
map: "usaLow",
areas: [ {
id: "US-AL",
value: 4447100
}, {
id: "US-AK",
value: 626932
}, {
id: "US-AZ",
value: 5130632
}, {
id: "US-AR",
value: 2673400
}, {
id: "US-CA",
value: 33871648
},.... and so on
Im having trouble displaying it like above: How would I display the data im getting from the array into the 'areas' section in the ChartJS script?
I tried this, but it dosen't work:
areas: [ {
id: "US-{!! json_encode(array_keys($newRegions)) !!}",
value: {!! json_encode(array_values($newRegions)) !!}
} ]

is is a very common problem, transforming data structures to specific implementations.
the phpleague has many cool packages to help you with this.
one of my favorites is
http://fractal.thephpleague.com/
However, I want to show you in plain PHP how to transform an array into the desired structure.
1) get the array of data that you need to transform (the data that you showed in the previous image)
array:15[
0 => regioncode:"AL"
total: 16]
]...
2) transform the array using the array_map function
//http://php.net/manual/en/function.array-map.php
$transformedarray = array_map(function ($loopdata) {
return [
"id" => "US-".$loopdata['regionCode'],
"value" => $loopdata['value']
];
}, $regions->toArray());
3) var_dump($transformedarray) o return this array with laravel responde to check the desired structure match the one you require.
4) pass this variable (array) to the view using this method
return view('admin.dashboard-v2')->with(['newarray' => $transformedarray]);
5) if you are using BLADE try to user control structures to loop over your data
https://laravel.com/docs/5.0/templates
insert this code sniplet where you need the data to populate in the view
areas: [
#foreach ($newarray as $newarr)
{
id:{{ $newarr->id }},
value:{{ $newarr->value }}
},
#endforeach
]
Hope this helps

This is how I did:
$heatMap = DB::table('locations')
->select('regionCode', DB::raw('count(id) as total'))
->groupBy('regionCode')
->get();
$newHeatMap = [];
foreach( $heatMap as $regionH ){
$newHeatMap[] = [ 'id' => 'US-' . $regionH->regionCode, 'value' => $regionH->total ];
}
return view('admin.dashboard-v2', compact('newHeatMap'));
Then In my Chart JS
dataProvider: {
map: "usaLow",
areas: {!! json_encode(array_values($newHeatMap)) !!}
},

Related

Datatables: dropdown in a cell

i'm trying to generate a table with Datatables.
I receive a json from my controller, here a sample:
this json can change (number of columns, name of the columns) and I can build my table with the good number of column and the good name.
My question is:
How can i do to have a dropdown when the "liste" have an array and a simple input when it's null?
Is it even possible?
EDIT :
I forget to explain something. The Json that I receive is a json to build the table not to fill it. So is it possible to do a columnsDef before the datas are in the cell.
EDIT n°2:
I used the solution that I accepted, but the problem was with my json. I tried to send a json to build and a json to fill the table. So I change my json and I send the list of options in the json to fill the table.
Hope it will help other people.
Thanks
Here are two solutions:
1) With a drop-down.
2) With a formatted array (as an alternative).
1) With a Dropdown
The end result looks like this:
The datatables definition is this:
<script type="text/javascript">
var dataSet = { "records" : [
{ "data" : "123456789",
"liste" : null,
"name" : "Nombre Enfants"
},
{ "data" : "5678901234",
"liste" : [ "Oui", "Non" ],
"name" : "Transport"
}]};
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: [
{ targets: [ 0 ],
title: "Data",
data: "data" },
{ targets: [ 1 ],
title: "Liste",
data: function ( row ) {
if (row.liste == null) {
return null;
} else {
return buildDropdown(row.liste);
}
} },
{ targets: [ 2 ],
title: "Name",
data: "name" }
]
} );
function buildDropdown(data) {
var dropdown = "<select>";
for (var i = 0; i < data.length; i++) {
var option = "<option value=\"" + data[i] + "\">" + data[i] + "</option>";
dropdown = dropdown + option;
}
dropdown = dropdown + "</select>";
return dropdown;
}
} );
</script>
It builds a drop-down based on the assumption that a non-null value is an array. This may not always be the case in your data - just an assumption on my part.
2) With a formatted array
Just in case this is also of interest, DataTables has a built-in syntax for formatting array data, so it is displayed in a cell like this:
In this case, you no longer need the drop-down builder function. Everything else is the same as option (1) except for this part:
{ targets: [ 1 ],
title: "Liste",
data: "liste[, ]" },
Specifically, the [, ] notation lets you format the array data.
I mention this only because it lets you display all the array data in the cell, rather than neeeding to click a drop-down. But that is just a suggestion.
You may find that other functions such as searching and sorting are better with this option.
Update
The question has clarified that the table needs to be built dynamically from the data provided in the JSON.
You can pass variables to the datatables initializer - for example:
var col1 = { targets: [ 0 ], title: "Data", data: "data" };
var col2 = { targets: [ 1 ], title: "Liste", data: "liste" };
var col2 = { targets: [ 2 ], title: "Name", data: "name" };
var dynamicCols = [ col1, col2, col3 ];
The above col1 variable defines the title for the column, and where the column will get its data (from the dataSet.data fields).
The dynamicCols variable can then be used in a columnDefs as follows:
$(document).ready(function() {
$('#example').DataTable( {
data: dataSet.records,
columnDefs: dynamicCols
} );
However, I am not aware of a way to include a function in a columndef, using this approach (for example to present a cell's data as a drop-down, if needed).
There are additional techniques which can be used to make a datatable even more dynamic - several examples are available online - for example here. Without seeing a more detailed example of the JSON being provided, I am not sure if there are any additional suggestions I can make.

How to assign a JSON string to a google pie chart data var

The problem I am facing is that in my web server I am sending a JSON as argument via render_template to my website where I want to use that JSON to show a google pie chart.
The problem is that if I assign the google pie chart data statically like this:
var data = new google.visualization.DataTable({
cols: [
{ id: "", label: "objeto", type: "string" },
{ id: "", label: "quantidade", type: "number" }
],
rows: [
{ c: [{ v: "Caixa 2" }, { v: 3 }] },
{ c: [{ v: "Caixa 3" }, { v: 3 }] },
{ c: [{ v: "Caixa 4" }, { v: 3 }] }
]
});
It works perfectly. On the other hand if I assign it dynamically with the JSON that I am receiving from my server like this:
var data = new google.visualization.DataTable({{json}});
It stops showing the google pie chart in my website.
The things I tried until now was litteraly adapting the JSON to the desired format by google charts because I thought that was the only problem, but now that it is in the required format and it works statically I do not know any way of assigning my received JSON to the data var.
This is my ideal function that I would like to work.
function drawChart() {
var data = new google.visualization.DataTable({{json}});
var options = {
title: 'gráfico Objeto/Quantidade',
is3D: true
};
var chart = new google.visualization.PieChart(
document.getElementById('piechart')
);
chart.draw(data, options);
}
Desired result:
http://prntscr.com/oejojv
Actual result:
http://prntscr.com/oejooe
The JSON string is being HTML-escaped. Assuming that you're using Flask (guessing based on your mention of render_template), you need to do something like {{json | safe}}.
Also, this assumes that you have total control over the content of this JSON, because you are otherwise susceptible to cross-site scripting attacks.

Iterating through the JSON at the view layer using knockout

I'm working on a simple web page using knockout. Consider I have the following ViewModel function
self.sample_data = ko.observableArray([
{
1:[
{ title1:"abc", title2:"def"},
{ title1:"abc", title2:"def"}
],
2:[
{ title1:"ghi", title2:"jkl"},
]
}
]);
Am able to bind the specific json value with key value as '1' to the view layer as follows.
<h1 data-bind="text:sample_data[0].1[0].title1"></h1>
Consider I have two buttons 'previous' and 'next'. On clicking the button 'next' I should bind the data associated with key value as '2' in the JSON to the same h1 tag. How can we acheive that?
You'll want an observable index variable in your view model. Clicking the next button would increment that variable:
var self = {};
self.sample_data = ko.observableArray([
{
"1": [
{ title1: "abc11", title2: "def11" },
{ title1: "abc12", title2: "def12" }
],
"2": [
{ title1: "ghi21", title2: "jkl21" }
]
}
]);
self.index = ko.observable(1);
self.goToNext = function() {
self.index(self.index() + 1);
};
Then, your data binding could look something like this:
<h1 data-bind="text: sample_data()[0][index()][0].title1"></h1>
<a data-bind="click: goToNext">Next</a>
Your Json object has invalid key:
JSON only allows key names to be strings
Here's the binding sample
Html
<h1 data-bind="text: sample_data()[0][2][0].title1"></h1>
JavaScript
var self = {};
self.sample_data = ko.observableArray([
{
"1":[
{ title1:"abc11", title2:"def11"},
{ title1:"abc12", title2:"def12"}
],
"2":[
{ title1:"ghi21", title2:"jkl21"},
]
}]);
ko.applyBindings(self);
You can play with code here

In kendo dataviz chart local data binding , JSON data value was spilted?

I create a Column chart using Kendo ui dataviz.
In my program, i am going to bind the local Javascript Array variable data to chart datasource.
The JSON data was spilted like "3""9""6" for "396".
I dont know why it happened. My Source code is given blow. Please check it and Please give the solution.
Source:
/**************Variable Declaration**********************************/
var eligibilityData = new Array();
eligibilityData = {
mem_status: {
a: 396, b: "56", c: "1125", d: "8423"
}
};
/**************Create Chart**********************************/
function createBarChart(eligibilityData) {
/****** Issue: A value is 396 but it spilted into "3","9","6"************/
$("#Chart1").kendoChart({
theme : $(document).data("kendoSkin") || "default",
dataSource : {
data: JSON.stringify(eligibilityData.mem_status.a),
},
seriesDefaults: { type: "column", },
series : [
{ field: "a", name : "A" }
],
tooltip : { visible: true, },
});
}
Local data should be passed as an array. No need to call JSON.stringify
data: [eligibilityData.mem_status]
See: http://docs.kendoui.com/api/framework/datasource#configuration-data-Array
JSON.stringify does not do what you expect. What you sentence really does is:
It gets the number 396 and converts it to a string.
Converts a string into an array of one character per element.
Not sure about the way you define the DataSource (why you want a DataSource with only one element) but if that is really what you want, you might try:
dataSource : {
data: [eligibilityData.mem_status.a]
},
or
dataSource : {
data: [eligibilityData.mem_status]
},

javascript array from an entity framework table

I would like to generate this array in a JavaScript file
var sports = [{ id: 1, value: "Baseball" },
{ id: 2, value: "Soccer" },
{ id: 3, value: "Basketball" },
{ id: 4, value: "Volleyball" },
{ id: 5, value: "Tennis" },
{ id: 6, value: "Running" },
{ id: 7, value: "Swimming" },
{ id: 8, value: "Tournament"}];
I have started with:
var sports = db.Sports;
But now I am stuck on how to include this in a JavaScript file. Does .net have embedded JavaScript file like Rails do?
You'll need to just retrieve the data and serialize it into javascript. If those two are the only columns, you can do a straight serialization with JavaScriptSerializer or JSON.NET. If not, you'll need to convert them, maybe something like (using JSON.NET):
var x = db.Sports.Select(s => new { id = s.id, value = s.value }).ToArray();
string json = JsonConvert.SerializeObject(x);
Once you have this JSON string, you can dump it onto a page however you want, or write it directly to the response.
If you need to know a specific way to do this part, we'd need more details (WebForms or MVC, inside a page or a separate javascript resource, etc.)
EDIT:
Adding it to the view once it's in the ViewBag is straightforward. Inside your script on the view:
var sports = #Html.Raw(ViewBag.Sports);
// or if you're not using Razor:
var sports = <%= ViewBag.Sports %>;
Since ViewBag.Sports is already properly serialized, you don't need to worry about quotation marks or brackets.

Categories