Convert JSP code into JavaScript for canvasJS - thymeleaf

I'm trying to get this canvasJS line chart to render using thymeleaf rather than JSP.
It has the following loop in jsp that I need to convert to javascript. However I'm not proficient in javascript
<c:forEach items="${dataPointsList}" var="dataPoints" varStatus="loop">
<c:forEach items="${dataPoints}" var="dataPoint">
xValue = parseInt("${dataPoint.x}");
yValue = parseFloat("${dataPoint.y}");
dps[parseInt("${loop.index}")].push({
x : xValue,
y : yValue,
});
</c:forEach>
</c:forEach>
The above $dataPointList is created in java as follows
static List<Map<Object, Object>> dataPoints1 = new ArrayList<Map<Object, Object>>();
static {
int limit = 50000;
int y = 100;
Random rand = new Random();
for (int i = 0; i < limit; i += 1) {
y += rand.nextInt(11) - 5;
map = new HashMap<Object, Object>();
map.put("x", i);
map.put("y", y);
dataPoints1.add(map);
}
list.add(dataPoints1);
}
public static List<List<Map<Object, Object>>> getCanvasjsDataList() {
return list;
}
I've tried the following however dps[parseInt(i)].push({ gives a type error. I'm not sure how to create the required data structure for canvasJS given the datalist defined in java.
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<script type="text/javascript" th:inline="none" class="init">
/*<![CDATA[*/
window.onload = function (e) {
var dps = [[]];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "dark1", "dark2"
animationEnabled: true,
zoomEnabled: true,
title: {
text: "Try Zooming and Panning"
},
data: [{
type: "area",
dataPoints: dps[0]
}]
});
var xValue;
var yValue;
var dataPointsList = /*[[${dataPointsList}]]*/ 'default';
for (var i = 0; i < dataPointsList.length; i++) {
var dataPoints = dataPointsList[i];
for (var j = 0; j < dataPoints.length; j++) {
dps[parseInt(i)].push({
x : dataPoints[j].x,
y : dataPoints[j].y,
});
}
}
chart.render();
}
/*]]>*/
</script>

The following adjustments have resulted in the graph displaying
<script type="text/javascript" th:inline="javascript" class="init">
/*<![CDATA[*/
window.onload = function (e) {
var dps = [];
var chart = new CanvasJS.Chart("chartContainer", {
theme: "light2", // "light1", "dark1", "dark2"
animationEnabled: true,
zoomEnabled: true,
title: {
text: "Try Zooming and Panning"
},
data: [{
type: "area",
dataPoints: dps
}]
});
var dataPointsList = /*[[${dataPointsList}]]*/ 'null';
count = 0;
for (var i = 0; i < dataPointsList.length; i++) {
var dataPoints = dataPointsList[i];
for (var j = 0; j < dataPoints.length; j++) {
dps[count++] = {
x: dataPoints[j].x,
y: dataPoints[j].y
};
}
}
chart.render();
}
/*]]>*/
</script>

Related

select2 v4 dataAdapter.query not firing

I have an input to which I wish to bind a dataAdapter for a custom query as described in https://select2.org/upgrading/migrating-from-35#removed-the-requirement-of-initselection
<input name="pickup_point">
My script:
Application.prototype.init = function() {
this.alloc('$pickupLocations',this.$el.find('[name="pickup_point"]'));
var that = this;
$.fn.select2.amd.require([
'select2/data/array',
'select2/utils'
], function (ArrayData, Utils) {
var CustomData = function($element, options) {
CustomData.__super__.constructor.call(this, $element, options);
};Utils.Extend(CustomData, ArrayData);
CustomData.prototype.query = function (params, callback) {
var data = {
results: []
};
console.log("xxx");
for (var i = 1; i < 5; i++) {
var s = "";
for (var j = 0; j < i; j++) {
s = s + params.term;
}
data.results.push({
id: params.term + i,
text: s
});
}
callback(data);
};
that.$pickupLocations.select2({
minimumInputLength: 2,
language: translations[that.options.lang],
tags: [],
dataAdapter: CustomData
});
});
}
But when I type the in the select2 search box the xxx i'm logging for testing doesn't appear in my console.
How can I fix this?
I found the solution on
https://github.com/select2/select2/issues/4153#issuecomment-182258515
The problem is that I tried to initialize the select2 on an input field.
By changing the type to a select, everything works fine.
<select name="pickup_point">
</select>

forEachFeatureAtPixel does not work properly

I have the following code,
basically I have two layers one osm laryer, one vector layers, first I add two feature nodes with id 1 and id 2 into the vector layer by single click at two random locations on the map using ol.interaction.draw, then switch to interaction drag by select 'Drag Point' (top left corner), the idea is when drag either one of the two nodes over the other node, the node being dragged shall turn into green node, I can do this by dragging node id 1 to to node id 2 easily, but when i try to drag node id 2 to node id 1, it demands much higher accuracy than vice versa. The only difference between two nodes is node id 1 is created before node id 2.
The problem I see here is in forEachFeatureAtPixel, it rarely detects(or the call back rarely return node id 1) feature node id 1 when dragging node id 2 over node id 1.
I have spent quite a while on this issue. Still cannot figure out why. Really appreciated any help.
Thanks
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Draw and Modify Features</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v3.20.1/build/ol-debug.js"></script>
</head>
<body>
<form class="form-inline">
<select id="type">
<option value="DrawPoint">Draw Point</option>
<option value="DragPoint">Drag Point</option>
</select>
</form>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [raster],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var circle_style = new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 2)'
})
})
});
var overlap_style = new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 2)'
})
})
});
var features = new ol.Collection();
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector({
features: features
}),
style: circle_style
});
featureOverlay.setMap(map);
window.app = {};
var app = window.app;
/**
* #constructor
* #extends {ol.interaction.Pointer}
*/
app.Drag = function () {
ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent,
handleUpEvent: app.Drag.prototype.handleUpEvent
});
this.coordinate12_ = null;
this.cursor_ = 'pointer';
this.feature_ = null;
this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);
app.Drag.prototype.handleDownEvent = function (evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
return feature;
});
if (feature) {
console.log("down: node_id: " + feature.getProperties()['id']);
this.coordinate12_ = evt.coordinate;
this.feature_ = feature;
}
return !!feature;
};
app.Drag.prototype.handleDragEvent = function (evt) {
var map = evt.map;
fs = featureOverlay.getSource().getFeatures();
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
return feature;
});
if (!(feature === undefined)) {
console.log("drag: node_id: " + feature.getProperties()['id']);
// console.log("this:" + this.feature_.getId()+ " o: " + feature.getId());
if (this.feature_.getProperties()['id'] != feature.getProperties()['id']) {
console.log("green: node_id: " + feature.getProperties()['id']);
this.feature_.setStyle(overlap_style);
} else {
this.feature_.setStyle(circle_style);
}
}
var deltaX = evt.coordinate[0] - this.coordinate12_[0];
var deltaY = evt.coordinate[1] - this.coordinate12_[1];
var geometry = /** #type {ol.geom.SimpleGeometry} */
(this.feature_.getGeometry());
geometry.translate(deltaX, deltaY);
this.coordinate12_[0] = evt.coordinate[0];
this.coordinate12_[1] = evt.coordinate[1];
};
app.Drag.prototype.handleMoveEvent = function (evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
if (this.feature_ != null)
{
console.log("move forEachFeatureAtPixel: node_id: " + feature.getProperties()['id']);
}
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (this.feature_ != null)
{
console.log("move forEachFeatureAtPixel: node_id: " + feature.getProperties()['id']);
}
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
};
/**
* #param {ol.MapBrowserEvent} evt Map browser event.
* #return {boolean} `false` to stop the drag sequence.
*/
app.Drag.prototype.handleUpEvent = function (evt) {
this.coordinate12_ = null;
this.feature_ = null;
return false;
};
var draw = new ol.interaction.Draw({
features: features,
type: ('Point')
});
var drag = new app.Drag();
var id_count = 0;
draw.on('drawend', function(e) {
e.feature.setProperties({
'id': ++id_count
})
console.log(e.feature, e.feature.getProperties());
});
map.addInteraction(draw);
var typeSelect = document.getElementById('type');
typeSelect.value = 'DrawPoint';
typeSelect.onchange = function () {
if (typeSelect.value == 'DrawPoint')
{
map.removeInteraction(drag);
map.addInteraction(draw);
}else
{
map.removeInteraction(draw);
map.addInteraction(drag);
}
};
</script>
</body>
</html>
Prevent the feature(be it 1st or 2nd) which is being moved to get returned from map.forEachFeatureAtPixel method.
See the below working code snippet.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Draw and Modify Features</title>
<link rel="stylesheet" href="https://openlayers.org/en/v3.20.1/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v3.20.1/build/ol-debug.js"></script>
</head>
<body>
<form class="form-inline">
<select id="type">
<option value="DrawPoint">Draw Point</option>
<option value="DragPoint">Drag Point</option>
</select>
</form>
<div id="map" class="map"></div>
<script>
var raster = new ol.layer.Tile({
source: new ol.source.OSM()
});
var map = new ol.Map({
layers: [raster],
target: 'map',
view: new ol.View({
center: [-11000000, 4600000],
zoom: 4
})
});
var circle_style = new ol.style.Style({
image: new ol.style.Circle({
radius: 5,
fill: new ol.style.Fill({
color: 'rgba(255, 0, 0, 2)'
})
})
});
var overlap_style = new ol.style.Style({
image: new ol.style.Circle({
radius: 8,
fill: new ol.style.Fill({
color: 'rgba(0, 255, 0, 2)'
})
})
});
var features = new ol.Collection();
var featureOverlay = new ol.layer.Vector({
source: new ol.source.Vector({
features: features
}),
style: circle_style
});
featureOverlay.setMap(map);
window.app = {};
var app = window.app;
/**
* #constructor
* #extends {ol.interaction.Pointer}
*/
var dragFeature;
app.Drag = function () {
ol.interaction.Pointer.call(this, {
handleDownEvent: app.Drag.prototype.handleDownEvent,
handleDragEvent: app.Drag.prototype.handleDragEvent,
handleMoveEvent: app.Drag.prototype.handleMoveEvent,
handleUpEvent: app.Drag.prototype.handleUpEvent
});
this.coordinate12_ = null;
this.cursor_ = 'pointer';
this.previousCursor_ = undefined;
};
ol.inherits(app.Drag, ol.interaction.Pointer);
app.Drag.prototype.handleDownEvent = function (evt) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
return feature;
});
if (feature) {
//console.log("down: node_id: " + feature.getProperties()['id']);
this.coordinate12_ = evt.coordinate;
//this.feature_ = feature;
dragFeature = feature;
}
return !!feature;
};
app.Drag.prototype.handleDragEvent = function (evt) {
var map = evt.map;
fs = featureOverlay.getSource().getFeatures();
// Filter the feature
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
if ( feature.getProperties()['id'] != dragFeature.getProperties()['id'] ) {
return feature;
}
});
if (!(feature === undefined)) {
console.log("------------------- drag: node_id: " + feature.getProperties()['id']);
// console.log("this:" + this.feature_.getId()+ " o: " + feature.getId());
if (dragFeature.getProperties()['id'] != feature.getProperties()['id']) {
console.log("green: node_id: " + feature.getProperties()['id']);
dragFeature.setStyle(overlap_style);
}
}
else {
dragFeature.setStyle(circle_style);
}
var deltaX = evt.coordinate[0] - this.coordinate12_[0];
var deltaY = evt.coordinate[1] - this.coordinate12_[1];
var geometry = /** #type {ol.geom.SimpleGeometry} */
(dragFeature.getGeometry());
geometry.translate(deltaX, deltaY);
this.coordinate12_[0] = evt.coordinate[0];
this.coordinate12_[1] = evt.coordinate[1];
};
app.Drag.prototype.handleMoveEvent = function (evt) {
if (this.cursor_) {
var map = evt.map;
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) {
if (dragFeature != null)
{
//console.log("move forEachFeatureAtPixel: node_id: " + feature.getProperties()['id']);
}
return feature;
});
var element = evt.map.getTargetElement();
if (feature) {
if (dragFeature != null)
{
//console.log("move forEachFeatureAtPixel: node_id: " + feature.getProperties()['id']);
}
if (element.style.cursor != this.cursor_) {
this.previousCursor_ = element.style.cursor;
element.style.cursor = this.cursor_;
}
} else if (this.previousCursor_ !== undefined) {
element.style.cursor = this.previousCursor_;
this.previousCursor_ = undefined;
}
}
};
/**
* #param {ol.MapBrowserEvent} evt Map browser event.
* #return {boolean} `false` to stop the drag sequence.
*/
app.Drag.prototype.handleUpEvent = function (evt) {
this.coordinate12_ = null;
//this.feature_ = null;
dragFeature = null;
return false;
};
var draw = new ol.interaction.Draw({
features: features,
type: ('Point')
});
var drag = new app.Drag();
var id_count = 0;
draw.on('drawend', function(e) {
e.feature.setProperties({
'id': ++id_count
})
//console.log(e.feature, e.feature.getProperties());
});
map.addInteraction(draw);
var typeSelect = document.getElementById('type');
typeSelect.value = 'DrawPoint';
typeSelect.onchange = function () {
if (typeSelect.value == 'DrawPoint')
{
map.removeInteraction(drag);
map.addInteraction(draw);
}else
{
map.removeInteraction(draw);
map.addInteraction(drag);
}
};
</script>
</body>
</html>

Highcharts low performance when adding yAxis dynamically

I am trying to add/delete yAxis dynamically but I observe performance issues. It takes more than a second (sometimes it goes upto 4 seconds) to dynamically add or remove a series into a new yAxis. I need to load end of day data (price point for each day) for 10 or more years in the chart.
Any advice in improving the performance will be much appreciated.
Few points to note -
I can use different type of charts (line, ohlc, candlestick, area etc.)
I need mouse tracking to be enabled as I am using click events on the series.
User will have option to either choose to apply data grouping or to not.
Below is my code sample to illustrate the problem.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation:false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
renderTo:'container'
},
navigator: {
outlineColor: '#0066DD',
outlineWidth: 1
},
xAxis: [{
gridLineWidth: 1,
gridLineColor: "#eaf5ff",
lineColor: '#FF0000',
lineWidth: 1
}],
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false);
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData);
updateAxisHeight();
index++;
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(){
var i=0;
$("#axisList > option").each(function() {
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 });
i++;
});
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>
You can significantly improve the performance in this case with one trick: when performing several consecutive operations that each require a redraw (add series, add axis, update axis height), don't redraw until you've told Highcharts about all the operations.
On my machine, this improves the performance of your add axis function by 5x-6x. See code and comments below.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
console.time("chart load");
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation: false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
alignTicks: false,
events: {
load: function () {
console.timeEnd("chart load");
}
},
renderTo:'container'
},
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var startTime = new Date().getTime();
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false, false); // don't redraw yet
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData, false); // don't redraw yet
updateAxisHeight(false); // don't redraw yet
index++;
// finally, redraw now
chart.redraw();
var endTime = new Date().getTime();
console.log("add axis took " + (endTime - startTime) + " msec");
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(redraw){
// set redraw to true by default, like Highcharts does
if (typeof redraw === 'undefined') {
redraw = true;
}
var i=0;
$("#axisList > option").each(function() {
// don't redraw in every iteration
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 }, false);
i++;
});
// redraw if caller asked to, or if the redraw parameter was not specified
if (redraw) {
chart.redraw();
}
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>

How to set responsive for google charts in mvc

<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', { 'packages': ['corechart'] });
// Set a callback to run when the Google Visualization API is loaded.
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
$(document).ready(function () {
google.setOnLoadCallback(drawChartCountry);
$("a[href='#tab11']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartCountry
});
});
$("a[href='#tab21']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartDevice
});
});
$("a[href='#tab31']").on('shown.bs.tab', function (e) {
google.load('visualization', '1', {
packages: ['corechart'],
callback: drawChartVersion
});
});
function drawChartCountry() {
$.post('/AppDashboard/GetCountryChart', {},
function (data) {
var tdata = new google.visualization.DataTable();
tdata.addColumn('string', 'Country');
tdata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
tdata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart_country'));
chart.draw(tdata, options);
});
}
function drawChartDevice() {
$.post('/AppDashboard/GetDeviceChart', {},
function (data) {
var devicedata = new google.visualization.DataTable();
devicedata.addColumn('string', 'Device');
devicedata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
devicedata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-device'));
chart.draw(devicedata, options);
});
}
function drawChartVersion() {
$.post('/AppDashboard/GetVersionChart', {},
function (data) {
var versiondata = new google.visualization.DataTable();
versiondata.addColumn('string', 'Version');
versiondata.addColumn('number', 'No.of Users');
for (var i = 0; i < data.length; i++) {
versiondata.addRow([data[i].Name, data[i].Value]);
}
var options = {
title: "",
is3D: true,
//pieSliceText: 'label',
pieStartAngle: 100,
'width': 450,
'height': 350
};
var chart = new google.visualization.PieChart(document.getElementById('chart-version'));
chart.draw(versiondata, options);
});
}
});
I have set google chart inside a widget but the sad part is responsive is not working.When i resize it to mobile size the chart data exceeds my widget.Kindly help me with this and if you need more info lemme know,thanks in advance :)

How to Upload files in SAPUI5?

How to upload file in SAP Netweaver server using SAPUI5? I tried to upload file using FileUploader but did not get the luck if any one can help it will be very appreciated.
Thanks in Advance
Nothing was added to the manifest nor the component nor index files. It is working for me, you just need to change the number of columns to whatever you want to fit your file.
UploadFile.view.xml
<VBox>
<sap.ui.unified:FileUploader id="idfileUploader" typeMissmatch="handleTypeMissmatch" change="handleValueChange" maximumFileSize="10" fileSizeExceed="handleFileSize" maximumFilenameLength="50" filenameLengthExceed="handleFileNameLength" multiple="false" width="50%" sameFilenameAllowed="false" buttonText="Browse" fileType="CSV" style="Emphasized" placeholder="Choose a CSV file"/>
<Button text="Upload your file" press="onUpload" type="Emphasized"/>
</VBox>
UploadFile.controller.js
sap.ui.define(["sap/ui/core/mvc/Controller", "sap/m/MessageToast", "sap/m/MessageBox", "sap/ui/core/routing/History"], function(
Controller, MessageToast, MessageBox, History) {
"use strict";
return Controller.extend("cafeteria.controller.EmployeeFileUpload", {
onNavBack: function() {
var oHistory = History.getInstance();
var sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
var oRouter = sap.ui.core.UIComponent.getRouterFor(this);
oRouter.navTo("admin", true);
}
},
handleTypeMissmatch: function(oEvent) {
var aFileTypes = oEvent.getSource().getFileType();
jQuery.each(aFileTypes, function(key, value) {
aFileTypes[key] = "*." + value;
});
var sSupportedFileTypes = aFileTypes.join(", ");
MessageToast.show("The file type *." + oEvent.getParameter("fileType") +
" is not supported. Choose one of the following types: " +
sSupportedFileTypes);
},
handleValueChange: function(oEvent) {
MessageToast.show("Press 'Upload File' to upload file '" + oEvent.getParameter("newValue") + "'");
},
handleFileSize: function(oEvent) {
MessageToast.show("The file size should not exceed 10 MB.");
},
handleFileNameLength: function(oEvent) {
MessageToast.show("The file name should be less than that.");
},
onUpload: function(e) {
var oResourceBundle = this.getView().getModel("i18n").getResourceBundle();
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
var params = "EmployeesJson=";
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
var Len = data.length;
data.reverse();
params += "[";
for (var j = 0; j < Len; j++) {
params += JSON.stringify(data.pop()) + ", ";
}
params = params.substring(0, params.length - 2);
params += "]";
// MessageBox.show(params);
var http = new XMLHttpRequest();
var url = oResourceBundle.getText("UploadEmployeesFile").toString();
http.onreadystatechange = function() {
if (http.readyState === 4 && http.status === 200) {
var json = JSON.parse(http.responseText);
var status = json.status.toString();
switch (status) {
case "Success":
MessageToast.show("Data is uploaded succesfully.");
break;
default:
MessageToast.show("Data was not uploaded.");
}
}
};
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.send(params);
};
reader.readAsBinaryString(file);
}
});
});
After researching a little more on this issue I finally solved this issue by myself I placed a file controller and a uploader in php which return the details related to files further, we can use it to upload it on server.
Here is the code I have used.
fileUpload.html
<!DOCTYPE html>
<html><head>
<meta http-equiv='X-UA-Compatible' content='IE=edge' />
<title>Hello World</title>
<script id='sap-ui-bootstrap' src='http://localhost/resources/sap-ui-core.js' data-sap-ui-theme='sap_goldreflection'
data-sap-ui-libs='sap.ui.commons'></script>
<script>
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader("myupload",{
name: "upload2",
uploadOnChange: true,
uploadUrl: "uploader.php",
uploadComplete: function (oEvent) {
var sResponse = oEvent.getParameter("response");
if (sResponse) {
alert(sResponse);
}
}});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text:'Trigger Upload',
press:function() {
// call the upload method
oFileUploader2.upload();
$("#myupload-fu_form").submit();
alert("hi");
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");
</script>
</head>
<body class='sapUiBody'>
<div id="sample2"></div>
</body>
</html>
uploader.php
<?php
print_r($_FILES);
?>
It would be good if we can see your code.
This should work.
var layout = new sap.ui.commons.layout.MatrixLayout();
layout.setLayoutFixed(false);
// create the uploader and disable the automatic upload
var oFileUploader2 = new sap.ui.commons.FileUploader({
name : "upload2",
uploadOnChange : false,
uploadUrl : "../../../upload"
});
layout.createRow(oFileUploader2);
// create a second button to trigger the upload
var oTriggerButton = new sap.ui.commons.Button({
text : 'Trigger Upload',
press : function() {
// call the upload method
oFileUploader2.upload();
}
});
layout.createRow(oTriggerButton);
layout.placeAt("sample2");

Resources