i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html
Related
i'm working with xpages and javascript server side i want to convert the fields in format json then i parse this dat and i put them in a grid,the problem is that these fields can contains values :one item or a list how can i convert them in json ?
this is my code :
this.getWFLog = function ()
{
var wfLoglines = [];
var line = "";
if (this.doc.hasItem (WF.LogActivityPS) == false) then
return ("");
var WFLogActivityPS = this.doc.getItem ("WF.LogActivityPS");
var WFActivityInPS = this.doc.getItem ("WFActivityInPS");
var WFActivityOutPS = this.doc.getItem ("WFActivityOutPS");
var WFLogDecisionPS = this.doc.getItem ("WF.LogDecisionPS");
var WFLogSubmitterPS = this.doc.getItem ("WF.LogSubmitterPS");
var WFLogCommentPS = this.doc.getItem ("WF.LogCommentPS");
var WFLogActivityDescPS = this.doc.getItem ("WF.LogActivityDescPS");
var Durr =((WFActivityOutPS-WFActivityInPS)/3600);
var json= {
"unid":"aa",
"Act":WFLogActivityPS,
"Fin":WFActivityOutPS,
"Durr":Durr,
"Decision":WFLogDecisionPS,
"Interv":WFLogSubmitterPS,
"Instruction":WFLogActivityDescPS,
"Comment":WFLogCommentPS
}
/*
*
* var wfdoc = new PSWorkflowDoc (document1, this);
histopry = wfdoc.getWFLog();
var getContact = JSON.parse(histopry );
*/ }
Careful. Your code is bleeding memory. Each Notes object you create (like the items) needs to be recycled after use calling .recycle().
There are a few ways you can go about it. The most radical would be to deploy the OpenNTF Domino API (ODA) which provides a handy document.toJson() function.
Less radical: create a helper bean and put code inside there. I would call a method with the document and an array of field names as parameter. This will allow you to loop through it.
Use the Json helper methods found in com.ibm.commons.util.io.json they will make sure all escaping is done properly. You need to decide if you really want arrays and objects mixed - especially if the same field can be one or the other in different documents. If you want them flat use item.getText(); otherwise use item.getValues() There's a good article by Jesse explaining more on JSON in XPages. Go check it out. Hope that helps.
If an input field contains several values that you want to transform into an array, use the split method :
var WFLogActivityPS = this.doc.getItem("WF.LogActivityPS").split(",")
// input : A,B,C --> result :["A","B","C"]
Using this plugin I need to draw an audio waveform with pre-rendered data.
I stored JSON data inside MySQL as {"sample_rate":44100,"samples_per_pixel":4410,"bits":8,"length":2668,"data":[0.13,0.19,0.15,0.11,0.13,0.13,0.24,0.35 ...]}
So I tried:
PHP
$json = $row['wave'];
$json_array = json_decode($json);
$json_wave = implode(',', $json_array->data);
HTML
<div data-track-wave="'.$json_wave.'" id="play'.$row['id'].'" class="track"></div>
JS
function createWaveform(json) {
$( "#waveformbottom" ).empty();
var linGrad = document.createElement('canvas').getContext('2d').createLinearGradient(0,0,0,170);
linGrad.addColorStop(0, '#ff3b25');
linGrad.addColorStop(0.5, '#ff0018');
var wavesurferbottom = WaveSurfer.create({
container: document.querySelector('#waveformbottom'),
waveColor: '#b3b3b3',
progressColor: linGrad,
backend: 'MediaElement',
mediaType:'audio',
height:'48',
cursorColor:'#fff',
cursorWidth:'0',
normalize:true,
barWidth:'2'
});
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = [json];
//Draw peaks
wavesurferbottom.drawBuffer();
$(window).resize(function(){
if($(this).width() != width){
widthbottom = $(this).width();
wavesurferbottom.drawer.containerWidth = wavesurferbottom.drawer.container.clientWidth;
wavesurferbottom.drawBuffer();
}
});
}
$(document).on('click touchend', '.track', function(e) {
var wave_data = $(this).data('track-wave');
createWaveform(json);
e.preventDefault();
});
A debug of my wave_data shows that is correct like 0.01,0.13,0.19,0.15,0.11,... however the waveform is not drawn.
Instead if I set wavesurferbottom.backend.peaks = [0.01,0.13,0.19,0.15,0.11,...];it works.
I'm not a JSON expert, what am I doing wrong?
The difference is that one is a string (which isn't valid JSON anyway - it's just a list of comma separated numbers):
data-track-json="0.01,0.13,0.19,0.15,0.11"
var json = $(this).data('track-json'); // a string
And the other is a JS array:
var x=[0.01,0.13,0.19,0.15,0.11];
A simple approach is to split it by , - that'll convert your string into the JS array that you need, like so:
var samples = $(this).data('track-json').split(','); // Renamed because it's not JSON
..
createWaveform(samples);
It's also worth noting that you'll get an array of strings rather than an array of numbers, but many JS libraries handle that. If you wanted to go the JSON route, then make sure your attribute contains square brackets:
data-track-json="[0.01,0.13,0.19,0.15,0.11]"
The PHP to create that could look like this:
$json_wave = '['.implode(',', $json_array->data).']';
Then use a JSON.parse call to convert it into a suitable array of number types:
var samples = JSON.parse( $(this).data('track-json') );
If you still want to use JSON
PHP
$json = $row['wave'];
$object = json_decode($json);
$json_wave = json_encode($object->data);
This is a JSON string, presumably something like [1,2,3,4]
HTML unchanged
<div data-track-name="'.$row['name'].'" data-track-id="'.$row['id'].'" data-track-json="'.$json_wave.'" id="play'.$row['id'].'" class="track song-play-btn playthistrack"></div>
JS parse the JSON where you've identified the problem
//Set peaks ! THE PROBLEM !
wavesurferbottom.backend.peaks = JSON.parse(json);
wavesurferbottom.backend.peaks will be an array of Numbers - presumably what the rest of the code expects
I have a web page which uses jQuery to fetch data from a JSON file that contains a location name, latitude, and longitude. I then push the retrieved data into an array.
var weatherSites = [];
function weather() {
$.getJSON('json/LOCS.json', function(data) {
$.each(data.locations, function() {
var locationLatitude = this.latitude;
var locationLongitude = this.longitude;
var locationName = this.location;
// -- If the latitude and longitude are 0,0 then skip to the next iteration --
if (locationtLatitude == +0 || locationLatitude == -0 && locationLongitude == +0 || locationLongitude == -0) {
return true;
}
// Populate array with site name, latitude, and longitude
weatherSites.push({name: locationName, latitude: locationLatitude, longitude: locationLongitude});
});
});
};
The code retrieves the data and populates the array as required. However, there are a number of locationName items which are the same, even though the locationLatitude and/or locationLongitude are different. I need to remove from the array elements where the locationNames are the same, regardless of the latitude or longitude.
I have tried using a number of methods seen here but have had no luck. For example:
function removeDupes() {
var uniques = _.map(_.groupBy(weatherSites,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
This example requires underscore.js. This did not work for me. I am new to programming and GIS in general. I would appreciate an answer which contains the full code necessary and hopefully the logic behind what is happening. This would be very helpful for me and will of course help me to learn.
Thank you for your help.
The open source project http://www.jinqJs.com can easily do it.
Here is the GitHub link: GitHub
var results = jinqJs()
.from(data1)
.groupBy('locationName')
.max('locationLatitude', 'locationLongitude')
.select();
Let me know if you need any working examples.
I have a website that uses AJAX to deliver a JSON formatted string to a HighCharts chart.
You can see this as the middle JSON code part at:
http://jsfiddle.net/1Loag7pv/
$('#container').highcharts(
//JSON Start
{
"plotOptions": {
"series": {"animation": {"duration": 500}}
,"pie": {
"allowPointSelect": true,
"cursor": "pointer",
"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}
}
},
"chart":{"renderTo":"divReportChart"}
,"title":{"text":"Sales Totals"}
,"xAxis":{"title":{"text":"Item"}, "categories":["Taxes","Discounts","NetSalesTotal"], "gridLineWidth":1}
,"yAxis":[{"title":{"text":"Amount"}, "gridLineWidth":1}]
,"series":[{"name":"Amount","type":"pie", "startAngle": -60,"yAxis": 0,"data":[["Taxes",17.8700],["Discounts",36.0000],["NetSalesTotal",377.9500]]}]
}
//JSON end
);
The problem is that the function part...
"dataLabels": {"formatter":function(){return this.point.name+': '+this.percentage.toFixed(1) + '%';}}
is not being transferred via the JSON
All research tells me that there is NO WAY to do this.
IE... Is it valid to define functions in JSON results?
Anybody got an idea on how to get around this limitation?
It is true that you cannot pass functions in JSON. Javascript is a superset of JSON.
A common approach is for the chart to be defined in javascript (e.g. during the page load), and the page then requests just the data via Ajax. When the data is returned it can be added to the chart object, either before it is rendered or afterwards using the highcharts API.
If you really want to pass the formatter function from the server with the chart, send it as a string, and then turn it into a function like this:
var fn = Function(mystring);
and use it in highcharts like:
chart.plotOptions.pie.dataLabels = {"formatter":fn};
I've re-factored your example to show the approach: http://jsfiddle.net/wo7zn0bw/
I had a similar conundrum. I wanted to create the JSON server side (ruby on rails) so I could create images of charts for a web API and also present it on the client web browser with the same code. This is similar to SteveP's answer.
To conform with JSON standards, I changed all formatter functions to strings
{"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
On the web side, I navigate the hash looking for formatter keys and replace them with the function using this code (may be a better way!?). javascript:
function HashNavigator(){
this.navigateAndReplace = function(hash, key){
if (!this.isObject(hash)){
//Nice if only navigated hashes and arrays
return;
}
var keys = Object.keys(hash);
for(var i = 0; i< keys.length; i++){
if (keys[i] == key){
//convert string to js function
hash[keys[i]] = this.parseFunction(hash[keys[i]]);
} else if (this.isObject(hash[keys[i]])){
//navigate hash tree
this.navigateAndReplace(hash[keys[i]], key);
} else {
//continue
}
}
};
this.isObject = function(testVar) {
return testVar !== null && typeof testVar === 'object'
}
//http://stackoverflow.com/questions/7650071/is-there-a-way-to-create-a-function-from-a-string-with-javascript
this.parseFunction = function(fstring){
var funcReg = /function *\(([^()]*)\)[ \n\t]*{(.*)}/gmi;
var match = funcReg.exec(fstring.replace(/\n/g, ' '));
if(match) {
return new Function(match[1].split(','), match[2]);
}
return null;
};
}
To use this, would be something similar to this javascript:
hashNavigator = new HashNavigator();
hashNavigator.navigateAndReplace(myHighchartsHash, "formatter")
At that point the hash/js-object is Highcharts ready
Similar idea was used for the web image API.
I was really hoping that hacking at the JSON was not the only solution, but it works!
I used a different approach. I created a JSON like below
{"formatter": "function(){ return this.point.name+':'+this.percentage.toFixed(1) + '%';}"}
When I came to evaluating the expression, I used (assuming that the value of the 'formatter' is formatterValueString)
formatterValueString = formatterValueString.replace('function()', '');
let opts = (new Function(formatterValueString)).call(this);
formatterValue = opts;
The reason to use this approach was it became hard to bind 'this' with the function. The eval() function did not go well with accessing variable this. I am sure there are ways to do it. Just thought this was quick.
I'm getting a JSON response from my service. Following the tutorial, I created response for binding data in datatables jquery plugin.
Client Side code :
var test_reports = jsonResp.reports;
var aDataSet = [test_reports];
$('#example').dataTable( {
"aaData": aDataSet,
"aoColumns": [{ "sTitle": "Tests" },
{ "sTitle": "Reports"}]
});
In console, my "test_reports" shows :
['TEST_1','1'] ['TEST_2','1']
But while binding this data to tables, it throws error. If I copy this cosole output into aaData, it creates the table. I understood that my "test_reports" is a string and this plugin is expecting an array of values. Any ideas of making this work!!
Server side code which gives this json response :
testcasesCountRS = statement.executeQuery(testcasesQuery);
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
reports.put("reports", resBuffer);
Is there any alternative in my server side code to send the response as an array object to the datatables plugin.
You server response should be an array of array.
[['TEST_1','1'],['TEST_2','1']]
Change your code to
resBuffer.append("[");
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
resBuffer.append("]");
The above code is untested. But hope you get the idea.
Documentation link
I made it work the following way :
JSONArray testCaseArray = new JSONArray();
while(testcasesCountRS.next()){
JSONArray testCase = new JSONArray();
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testCase.add(test_name);
testCase.add(test_count);
testCaseArray.add(testCase);
}
reports.put("reports", testCaseArray);
The only thing thats bothering me is, it so stupid code that I need to create a new Array every time in my loop. And adding these arrays to my main Array object. There should be some work around to make it simple. Please suggest some efficient methodology.