Am trying to Inserting JSON data's into Google Spreadsheet. This is My code ,
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
var read=(function(){
data1={
"jobstatus": [
{
"dateAndTime": "hi",
"jobId": "TCC_tfc",
"userId": "admin",
"status": "Completed",
"jobType": "Excel Upload"
}
]
};
var jobs = data1;
var datae = new google.visualization.DataTable();
datae.addRows(["datetime",jobs.jobstatus.dateAndTime],
['jobId', jobs.jobstatus.jobId],
['userId', jobs.jobstatus.userId],
['status', jobs.jobstatus.status],
['jobType', jobs.jobstatus.jobType]
);});
</script>
While am Executing this code am getting error as
TypeError: google.visualization is undefined
How can i solve that Error ? i searched solution for that in "SO" they said me to add this line :
google.load('visualization', '1.0', {'packages':['corechart'], 'callback': read});
By adding this also am getting that same error . Can someone help me out from this .
here are a few recommendations...
1) recommend using loader.js vs. the older library jsapi
<script src="https://www.gstatic.com/charts/loader.js"></script>
2) name the callback function, rather than assigning to a variable
google.charts.load('current', {
callback: read,
packages:['table']
});
function read(){...}
3) must add columns before addRows, several ways to do this, using arrayToDataTable is easy
var datae = google.visualization.arrayToDataTable([
['datetime', 'jobId', 'userId', 'status', 'jobType'],
]);
4) in data1, "jobstatus" is an array, so must use array element index to access value
jobs.jobstatus[0].dateAndTime // get first array element with [0]
--or--
if there is more than one jobstatus in the array, use a loop to add them all, using addRow
jobs.jobstatus.forEach(function (job) {
datae.addRow([
job.dateAndTime,
job.jobId,
job.userId,
job.status,
job.jobType
]);
});
see following working snippet...
google.charts.load('current', {
callback: read,
packages:['table']
});
function read(){
var data1={
"jobstatus": [{
"dateAndTime": "hi",
"jobId": "TCC_tfc",
"userId": "admin",
"status": "Completed",
"jobType": "Excel Upload"
}]
};
var jobs = data1;
var datae = google.visualization.arrayToDataTable([
['datetime', 'jobId', 'userId', 'status', 'jobType'],
]);
jobs.jobstatus.forEach(function (job) {
datae.addRow([
job.dateAndTime,
job.jobId,
job.userId,
job.status,
job.jobType
]);
});
var chart = new google.visualization.Table(document.getElementById('chart_div'));
chart.draw(datae);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Related
I am a total javascript/leaflet/ag-grid newbie, so please bear with me.
I am creating a website that allows users to query (add/remove) spatial points on a leaflet map based on selecting rows from ag-grid. I have no understanding/experience with React or Angular, so I am using vanilla javascript. Leaflet is used to display the data spatially.
I have spatial data that has GPS coordinates that are parent records. Each parent they have multiple children.
Spatial data
The spatial data is an external file I read into my HTML file. It looks like this:
var spatial_data = {
"type": "FeatureCollection",
"features": [
{ "type": "Feature",
"properties": { "Name": "Boulder 1", "SpatialID": "Lower Blair_0" },
"geometry": { "type": "Point", "coordinates": [ -105.39079766, 41.19044516, 2510.159912109375 ] } },
{ "type": "Feature",
"properties": { "Name": "Boulder 2", "SpatialID": "Upper Blair_1" },
"geometry": { "type": "Point", "coordinates": [ -105.39058423, 41.19655902, 2534.4599609375 ] } }
]};
Children records
There are children records for each parent spatial ID. The data is within the .js code.
The functionality I am hoping for is someone could filter the ag-grid for a route called 'Slam Dunk' and that would provide the "SpatialID":"Lower Blair_0". If they filter for 'Test two' it provides the same SpatialID. This would be available to play around within the HTML file.
myownscript.js
var rowData = [{"Route Name":"Slam Dunk","SpatialID":"Lower Blair_0"},
{"Route Name":"Test two","SpatialID":"Lower Blair_0"},
{"Route Name":"Test three","SpatialID":"Upper Blair_1"}];
var columnDefs= [
{field: 'Route Name', minWidth:10, sortable:true, filter:true},
{field: 'Sub-Area', minWidth:5, sortable:true, filter:true},
];
const gridOptions = {
columnDefs: columnDefs,
rowData: rowData,
defaultColDef:{
flex:1,
minWidth:100
},
rowSelection: 'multiple',
pagination:true
};
function onlyUnique(value, index, self) {
return self.indexOf(value) === index;
};
function grabFilteredData(){
let rowData = [];
gridOptions.api.forEachNodeAfterFilter(node => {
rowData.push(node.data.SpatialID);
});
var uniqueID = rowData.filter(onlyUnique);
return uniqueID;
}
document.addEventListener('DOMContentLoaded', () => {
const gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
});
I can easily send 'test' to the console. That provides me with the ability to check that my onSelectionChanged() is working; however, I really need to pass the output from onSelectionChanged() as an array. I need to pass that and use that in an embedded script within my HTML. This is so I can filter the data in my leaflet layers and features.
my html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Read in the geojson-->
<script src='assets/spatialdata.json'></script>
<script src="https://unpkg.com/ag-grid-community#27.0.1/dist/ag-grid-community.min.js"></script>
<script src="myownscript.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="bstrap/js/bootstrap.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.10.1/bootstrap-table.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-alpine.css">
</head>
<body>
<script >
var sat_data = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
attribution: 'Map data © OpenStreetMap contributors, Imagery © Mapbox',
maxZoom: 18,
id: 'mapbox/satellite-streets-v11',
tileSize: 512,
zoomOffset: -1,
accessToken: 'my.api.key'
});
var bounds = new L.LatLngBounds(new L.LatLng(41.008,-106.710), new L.LatLng(41.813,-104.861));
var baseMaps = {
"Satellite":sat_data
};
var map = L.map('map', {
center: [41.210, -105.360],
zoom: 11,
layers:[osm,sat_data],
noWrap:true,
maxBounds:bounds,
maxBoundsViscosit:1.0
});
L.control.layers(baseMaps).addTo(map);
var promise = $.getJSON("/assets/vedauwoo.geojson");
promise.then(function(data){
var allData = L.geoJson(data,{
onEachFeature: function(feature,layer){
layer.bindPopup('<h4> Area Name: '+feature.properties.Name+'</h4><p>Grades: '+feature.properties.Grade+'</p>');
}
});
var others = L.geoJson(data, {
onEachFeature: function(feature,layer){
layer.bindPopup('<h4> Area Name: '+feature.properties.Name+'</h4><p>Grades: '+feature.properties.Grade+'</p>');
},
filter: function(feature,layer){
}
});
var layerGroup = L.layerGroup().addTo(map);
allData.addTo(layerGroup)
$("#others").click(function() {
var dataToSubset = grabFilteredData();
var subset_data = L.geoJson(data, {
onEachFeature: function(feature,layer){
layer.bindPopup('<h4> Area Name: '+feature.properties.Name+'</h4><p>Grades: '+feature.properties.Grade+'</p>');
},
filter: function(feature,layer){
return dataToSubset.includes(feature.properties.SpatialID);
}
});
//Works in a hacky way by sending the ID over
layerGroup.removeLayer(allData)
layerGroup.addLayer(subset_data)
window.map_id = subset_data._leaflet_id;
});
$("#allData").click(function() {
layerGroup.removeLayer(map_id)
layerGroup.addLayer(allData)
});
</script>
</body>
</html>
I have tried extensive searching. For some reason, the majority of use cases for gridOptions.api.getSelectedRows() or forEachNodeAfterFilter end with an example of using console.log(). I need to actually pass that information along instead of just outputting to the console. I am not sure if this is a misunderstanding on my part for how JS works, or if it is expected behavior from ag-grid, but it doesn't seem possible.
This doesn't seem to work as the console.log() in the .js file doesn't work, and in the script in the HTML it can not find test.
I am primarily a statistician/python programmer, so this a new foray for me. It is likely I am missing a bigger picture thing and if so, I would appreciate alternatives to my current approach.
So once onSelectionChanged is called with the filtered rows - what script do you need to pass it to?
I assume you want to link the table with the leaflet map. If so, you need to
obtain a reference to the map object (see Leaflet docs)
create a GeoJSON layer based on the filtered Geometries and add it to the map.
If the filtering in the table and thus the leaflet layer data update happens multiple times, you need to remove the existing layer and add a new one, as far as I know. Check this post.
I am using javascript to create Google-sheets-document with user data. The document is saved on the user's Drive.
I can't figure out how to make a graph from the data i have inserted. I am using vanilla javascript with the Google sheets API.
It would probably look something like this:
function createGraph() {
gapi.client.sheets.graph
.create({
properties: {
type(?): 'Pie'
spreadsheetid: //some id
range: 'A1:A10'
},
})
}
EDIT: To specify, i want to insert the graph to the sheets-document that i have created, not to the website.
If you want to add the chart to your spreadsheet, you can use Sheets API's AddChartRequest, as part of the spreadsheets.batchUpdate method.
Code snippet:
On broad terms, your request would look like this (check the reference below in order to build the request body in detail):
const payload = {
"requests": [
{
"addChart": {
"chart": {
"spec": { // Chart type, range source, etc.
"pieChart": { // Pie chart specification
// object (PieChartSpec)
}
// rest of ChartSpec properties
},
"position": { // Where the chart will be located
// object (EmbeddedObjectPosition)
}
}
}
}
]
}
const params = {
spreadsheetId = "YOUR-SPREADSHEET-ID",
body = payload
}
gapi.client.sheets.spreadsheets.batchUpdate(params);
Render chart in browsers and mobile devices:
In case you just wanted to render the chart in a browser, but not add it to your spreadsheet, you would use Google Charts (see Visualization: Pie Chart, for example).
Reference:
Sheets API > Charts
EmbeddedChart
ChartSpec
EmbeddedObjectPosition
PieChartSpec
Refer this example
<html>
<head>
<!--Load the AJAX API-->
<script
type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"
></script>
<script type="text/javascript">
var data;
var chart;
// Load the Visualization API and the piechart package.
google.charts.load("current", { packages: ["corechart"] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create our data table.
data = new google.visualization.DataTable();
data.addColumn("string", "Topping");
data.addColumn("number", "Slices");
data.addRows([
["Mushrooms", 3],
["Onions", 1],
["Olives", 1],
["Zucchini", 1],
["Pepperoni", 2]
]);
// Set chart options
var options = {
title: "How Much Pizza I Ate Last Night",
width: 400,
height: 300
};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(
document.getElementById("chart_div")
);
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width: 400; height: 300;"></div>
</body>
</html>
Referred from
https://developers.google.com/chart/interactive/docs/drawing_charts
I solved it. Thanks for the help! This worked for me.
function createGraphv2(spreadsheetIdGraph, endIndex) {
var params = {
// The spreadsheet to apply the updates to.
spreadsheetId: spreadsheetIdGraph, // TODO: Update placeholder value.
};
var batchUpdateSpreadsheetRequestBody = {
// A list of updates to apply to the spreadsheet.
// Requests will be applied in the order they are specified.
// If any request is not valid, no requests will be applied.
requests: [
{
addChart: {
chart: {
spec: {
title: 'Rapport',
basicChart: {
chartType: 'COLUMN',
legendPosition: 'BOTTOM_LEGEND',
axis: [
//X-AXIS
{
position: "BOTTOM_AXIS",
title: "FORBRUK"
},
//Y-AXIS
{
position: "LEFT_AXIS",
title: "TID"
}
],
series: [
{
series: {
sourceRange: {
sources: [
{
sheetId: 0,
startRowIndex: 0,
endRowIndex: endIndex,
startColumnIndex: 5,
endColumnIndex: 6,
},
],
},
},
targetAxis: "LEFT_AXIS"
}
]
}
},
position : {
newSheet : 'True'
}
},
}
}
],
// TODO: Add desired properties to the request body.
};
var request = gapi.client.sheets.spreadsheets.batchUpdate(
params,
batchUpdateSpreadsheetRequestBody
);
request.then(
function (response) {
// TODO: Change code below to process the `response` object:
console.log(response.result);
},
function (reason) {
console.error("error: " + reason.result.error.message);
}
);
}
I'm using google bar charts for my project and I create an ajax function to load charts with data. But when I use jquery each function to create data bars in google charts its getting error called
Uncaught (in promise) Error: Row 1 has 42 columns, but must have 2. Can Anyone show me the error in my code
This is my chart code
//chart 2
google.charts.load('current', {
'packages': ['bar']
});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
var dataa1 = google.visualization.arrayToDataTable([
['DS Division', 'No of Youths'],
$.each(data.locations, function(index, value3) {
['' + value3.DSD_Name + '', value3.total]
}),
]);
var options1 = {
chart: {
},
bars: 'horizontal', // Required for Material Bar Charts.
legend: {
position: 'none'
},
};
var chart1 = new google.charts.Bar(document.getElementById('barchart_material'));
chart1.draw(dataa1, google.charts.Bar.convertOptions(options1));
}
This is my response data from the controller
return response() => json(array(
'male' => $male,
'female' => $female,
'locations' => $locations,
'salary1' => $salary1,
'salary2' => $salary2,
'salary3' => $salary3,
'salary4' => $salary4,
'salary5' => $salary5,
'salary6' => $salary6,
'employers' => $employers
));
Please help me to slove this
Thank You
instead of trying to loop within the array declaration,
use the loop to add values to the array...
var chartData = [
['DS Division', 'No of Youths'],
];
$.each(data.locations, function(index, value3) {
chartData.push([value3.DSD_Name, value3.total]);
});
var dataa1 = google.visualization.arrayToDataTable(chartData);
so I am trying to read the data from my JSON file and display it on the webpage using HTML. It would work with simple keys with this particular database it wouldn't work for me.
JSON:
var carInfo = [
{
carId: 1,
carPrice : 15.00,
},
{
carId: 2,
carPrice : 25.00,
}
];
JS:
$(document).ready(function() {
$.getJSON("vehicle_data.json", function(data) {
$.each(data.carInfo, function() {
$("ul").append("<li>Car ID: "+this[carInfo[0].carId]);
});
});
});
HTML:
<html>
<body>
<ul></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="json_data_retrieve.js"></script>
</body>
</html>
It is not a valid JSON file. It is a JS script.
var carInfo = [
{
carId: 1,
carPrice : 15.00,
},
{
carId: 2,
carPrice : 25.00,
}
];
Try this:
{
"carInfo":
[
{
"carId": 1,
"carPrice": 15
},
{
"carId": 2,
"carPrice": 25
}
]
}
Update:
You may load this script as a script source in an HTML. It must be an .js file.
<script src="vehicle_data.js"></script>
If you need to load it dynamically, use jQuery $.getScript method.
It doesn't matter that it has .json extensions because it will be evaluated as a script.
$(document).ready(function()
{
$.getScript("vehicle_data.json", function()
{
// Pay attention. In this case, you work with carInfo
// variable because it has been executed as a script,
// but not loaded as a JSON file.
$.each(carInfo, function() {
$("ul").append("<li>Car ID: " + this[carInfo[0].carId]);
});
});
});
However, it is very strange that someone gives you .json file with JS declaration and tells you that you should execute it but shouldn't rename it or load as a script.
Looks like you are trying to iterate the parent object from within itself.
Try this
$.each(data.carInfo, function(k, v) {
$("ul").append("<li>Car ID: "+v.carId);
});
I am new to SAPUI5/OPENUI5.
I am trying out a sample program to consume json data from a domain and display it in my openui5 table. I have tried two methods to get the data and bind it to table control.But I am not able to generate the table with the json data.
Please let me know my mistake in the code.
And also please refer me some links to understand the concept in a better way.
Thanks in advance.
Please find the two approaches below :
JSON Data :
[
{
"name": "Rajesh"
},
{
"name": "Kunal Jauhari"
},
{
"name": "Ashish Singh"
},
{
"name": "Ansuman Parhi"
},
{
"name": "Arup Kumar"
},
{
"name": "Deepak Malviya"
},
{
"name": "Seshu"
},
{
"name": "Ankush Datey"
},
{
"name": "Tapesh Syawaria"
},
{
"name": "Mahesh"
},
{
"name": "Vinay Joshi"
},
{
"name": "Ardhendu Karna"
},
{
"name": "Abhishek Shukla"
},
{
"name": "Kashim"
},
{
"name": "Vinayak"
}
]
Approach 1 : I am using a php file to echo the JSON data and use it in my ui5 screen.
When I access the run the php file individually, it generates the data and prints the data on screen.
Error I get is getJSON is not called.
Code :
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv='Content-Type' content='text/html;charset=UTF-8'/>
<script src="https://openui5.hana.ondemand.com/resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons,sap.ui.table"
data-sap-ui-theme="sap_bluecrystal">
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script>
var json_url = "http://mydomain/teamdetails_ui5.php?t=6";
$.ajax({
url : json_url,
jsonpCallback : 'getJSON',
contentType : "application/json",
dataType: 'jsonp',
success: function(data,textStatus,jqXHR) {
oModel.setData({data: data});
sap.ui.getCore().setModel(oModel);
var oTable1 = new sap.ui.table.Table({
title : "Players List",
visibleRowCount : 3,
selectionMode : sap.ui.table.SelectionMode.Single,
navigationMode : sap.ui.table.NavigationMode.Paginator,
});
//Define the columns and the control templates to be used
oTable1.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "Player Name"
}),
template : new sap.ui.commons.TextView().bindProperty(
"text", "name"),
width : "10px"
}));
oTable1.setModel(oModel);
oTable1.bindRows("/oModel");
oTable1.placeAt('table_cont');
},
error : function(jqXHR,textStatus,errorThrown) {
alert("Oh no, an error occurred");
alert(jqXHR);
alert(textStatus);
alert(errorThrown);
}
});
</script>
</head>
<body class="sapUiBody" role="application">
<div id="table_cont"></div>
</body>
</html>
Approach 2 : I am trying to access the JSON file directly on my domain and access the data.
Code is the same as above except url.
Url is used for this approach is (mydomain/players.json) where players.json contain the above json data.
Please help me in understanding the concept of JSON data handling.
Regards,
Rajan
First of all: SAPUI5 is built onto jQuery, yes. But there should be no need to use jQuery inside your SAPUI5 Application.
Use a JSONModel to load JSON-Data. Also the JSONModel can load the data from URL.
See the Documentation
this will look like:
// create a "json" Model
var oModel = new sap.ui.model.json.JSONModel();
// load data from URL
oModel.loadData('http://mydomain/teamdetails_ui5.php?t=6');
after this you can register this model in your sap.ui.core with:
sap.ui.getCore().setModel(oModel);
after this line every control can use the data from this model by simple binding-syntax.
Now lets create the table:
// create your table
var oTable1 = new sap.ui.table.Table({
title : "Players List",
visibleRowCount : 3,
selectionMode : sap.ui.table.SelectionMode.Single,
navigationMode : sap.ui.table.NavigationMode.Paginator,
// bind the core-model to this table by aggregating player-Array
rows: '{/player}'
});
beware of the part with "rows: '{/player}'". This is the only thing that has to be done to get the data from the model inside your table.
now finish the demo by adding the column and add the table to the DOM:
// define the columns and the control templates to be used
oTable1.addColumn(new sap.ui.table.Column({
label : new sap.ui.commons.Label({
text : "Player Name"
}),
template : new sap.ui.commons.TextView({
text: '{name}'
}),
width : "10px"
}));
//place at DOM
oTable1.placeAt('content');
Thats it. If it doesn't work, here is a running DEMO.