Adding Markers to Google map from json Array - arrays

This is my poor code
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i],
var latLng = new google.maps.LatLng(val.lat, val.lng);
console.log(latLng)
}
});
}
Im trying to get details from my own api using json array.
but its not working.
{"location":[{"name":"Home 1","lat":"6.824367","lng":"80.034523","type":"1"},{"name":"Grid Tower 1","lat":"6.82371292","lng":"80.03451942","type":"1"},{"name":"Power Station A","lat":"6.82291793","lng":"80.03417451","type":"1"}],"success":1}
This is json response from my api.php

Try to make things clear first then apply it. First read JSON clearly then go on to apply it in your code. This is the working code.
function loaddata() {
var url = "http://localhost/Geocording/api.php";
$.getJSON(url, function (data) {
var json = data['location'];
for (var i = 0, length = json.length; i < length; i++) {
var val = json[i];
var latLng = new google.maps.LatLng(val['lat'], val['lng']);
console.log(latLng)
}
});
}
Hope this may help you!

Related

Display image fetched from JSON responce in REACT

In my application i need to show multiple images that are loaded from the server on a client side.
This is the server response generating code(ASP.NET Core):
//Create list of thumbnails
List<Object> thumbnails = new List<Object>();
foreach (ClosingDocument DItem in PackageConent.Documents)
{
DItem.GetPDFDocument();
Bitmap thumbnail = DItem.GetThumbnailPage(1);
thumbnails.Add(thumbnail);
}
JArray JO = JArray.FromObject(thumbnails);
response.Add(new JProperty("PdfDocuments", JO));
Then on a client side i do
console.log(data.Package.PdfDocuments1);
and get the following:
But how do i convert it into something that i can put into the <img src="???">
if i do the following:
var dataUrl = window.URL.createObjectURL(data.Package.PdfDocuments[1]);
TypeError: Failed to execute 'createObjectURL' on 'URL': No function
was found that matched the signature provided.
I edited the server code to return Base64 encoded image.
now when i do
var blob = atob(data.Package.PdfDocuments[1]);
console.log(blob);
i get:
But when i try to convert in to URL like this:
var data = window.URL.createObjectURL(blob);
i still get:
TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.
Thanks!
The issue I was having was due to the fact that i was trying to convert blob to an URL directly.
What I needed to do was to convert it to the proper file type first like this:
var blob = atob(page);
var file = new Blob(this.convertToByteArray(blob), { type: "image/png" });
var imageUrl = window.URL.createObjectURL(file);
convertToByteArray(input) {
var sliceSize = 512;
var bytes = [];
for (var offset = 0; offset < input.length; offset += sliceSize) {
var slice = input.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
bytes.push(byteArray);
}
return bytes;
}

Google script, empty array from fetched API

I'm trying to fetch my ETH balance and transactions from etherscan.io website and I'm trying to use the same code I used before for another website. But it seems returning me an empty array, and also the error "The coordinates or dimensions of the range are invalid."
This is the code:
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.length; i++) {
array = data[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 3);
askRange.setValues(rows);
}
The logged "rows" is empty, what am I doing wrong?
Thank you
How about a following modification?
Modification points :
There is data you want at data.result.
Number of columns of data is 4.
Modified script :
function getTx() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Data");
var url = 'http://api.etherscan.io/api?module=account&action=txlist&address=0x49E81AA0cFE7eeA9738430212DC6677acF2f01a1&sort=asc';
var json = UrlFetchApp.fetch(url).getContentText();
var data = JSON.parse(json);
var rows = [],
array;
for (i = 0; i < data.result.length; i++) { // Modified
array = data.result[i];
rows.push([array.timeStamp, array.from, array.to, array.value]);
}
Logger.log(rows)
askRange = sheet.getRange(3, 1, rows.length, 4); // Modified
askRange.setValues(rows);
}
If I misunderstand your question, I'm sorry.

Can not get the array of data using Node.js and MongoDB

I am trying to fetch data from mongoDB and store those in array format bot outside of callback function I am getting that array variable as blank using Node.js.
My code is below:
exports.getCardDetails=function(req,res){
var userid=req.body.userid;
var token_id=req.body.token_id;
var userData=[];
db.f_user_login.find({_id: mongoJs.ObjectId(userid),token:token_id},function(err,doc){
if (doc.length > 0) {
db.f_card_details.find({userid:userid},function(errs,docs){
if (!errs) {
if (docs) {
for (var i = 0;i< docs.length;i++) {
var oemail=docs[i].email;
var id=docs[i]._id;
var name=docs[i].name;
var company=docs[i].company;
var position=docs[i].position;
var mobile=docs[i].mobile;
var landline=docs[i].landline;
var url=docs[i].url;
var postcode=docs[i].postcode;
var address=docs[i].address;
var isCurrentUser=docs[i].isCurrentUser;
db.f_user_profile.find({email:oemail},function(errs1,docs1){
if (!errs1) {
if (docs1) {
for(var j=0;j < docs1.length;j++){
var profileText=docs1[j].profiletext;
var biography=docs1[j].biography;
var image=docs1[j].file;
var profileid=docs1[j]._id;
}
var data={"id":id,"name":name,"company":company,"position":position,"mobile":mobile,"email":oemail,"landline":landline,"url":url,"postcode":postcode,"address":address,"profileText":profileText,"biography":biography,"image":image,"isCurrentUser":isCurrentUser,"profile_id":profileid};
userData.push(data);
}
}
})
}
console.log('user',userData);
var sdata={"statusCode": 200,"data":userData ,"message": "Your card details has been fetched successfully"};
res.send(sdata);
}
}
})
}else{
var data={"statusCode": 404,"error": "Not Found","message":"Invalid User"};
res.send(data);
}
})
}
Here I am pushing all data into userData array and trying to send those as response but here my problem is inside the loop all data are pushing to that array but console.log('user',userData); is showing blank while sending those data as response. I need to send those data as response.
userData is filled in db.f_user_profile.find callback, that's where you should move res.send(sdata); as well. Also I suggest to convert to async/await if you are using node7:
exports.getCardDetails = async function(req,res){
var userid=req.body.userid;
var token_id=req.body.token_id;
var userData=[];
const user = await db.f_user_login.find({_id: mongoJs.ObjectId(userid),token:token_id}).next();
if(user) {
const cards = await db.f_card_details.find({userid:userid}).toArray();
for (var i = 0;i < cards.length;i++) {
var email=docs[i].email;
var id=docs[i]._id;
var name=docs[i].name;
var company=docs[i].company;
var position=docs[i].position;
var mobile=docs[i].mobile;
var landline=docs[i].landline;
var url=docs[i].url;
var postcode=docs[i].postcode;
var address=docs[i].address;
var isCurrentUser=docs[i].isCurrentUser;
const profiles = await db.f_user_profile.find({email}).toArray();
for(var j=0; j < profiles.length;j++) {
var profileText=docs1[j].profiletext;
var biography=docs1[j].biography;
var image=docs1[j].file;
var profile_id=docs1[j]._id;
var data={id,name,company,position,mobile,email,landline,url,postcode,address,profileText,biography,image,isCurrentUser,profileid};
userData.push(data)
}
}
console.log('user',userData);
var sdata={"statusCode": 200,"data":userData ,"message": "Your card details has been fetched successfully"};
res.send(sdata);
} else {
var data={"statusCode": 404,"error": "Not Found","message":"Invalid User"};
res.send(data);
}
}

Why $http response data are not shown in angular js?

I make a example of directive in angular js .I am using this directive
https://github.com/ONE-LOGIC/ngFlowchart
when I take static data ..it show the output please check my plunker
http://plnkr.co/edit/d2hAhkFG0oN3HPBRS9UU?p=preview
but when I use $http request and make same json object .it not display the chart see my plunker using $http request .I have same data object as in static
http://plnkr.co/edit/Vts6GdT0NNudZr2SJgVY?p=preview
$http.get('data.json').success(function(data) {
console.log(data)
var arr = data
var model={};
var new_array = []
for (var i = 0; i < arr.length; i++) {
var obj = {};
obj.name = arr[i].name;
obj.id = arr[i].id;
obj.x = arr[i].x;
obj.y = arr[i].y;
obj.color = '#000';
obj.borderColor = '#000';
var p = {};
p.type = 'flowchartConstants.bottomConnectorType';
p.id = arr[i].con_id
obj.connectors = [];
obj.connectors.push(p);
new_array.push(obj);
}
console.log('new array')
console.log(new_array)
model.nodes=new_array;
var edge = [];
for (var i = 0; i < arr.length; i++) {
if (arr[i].children.length > 0) {
for (var j = 0; j < arr[i].children.length; j++) {
var obj = {};
obj.source = arr[i].con_id;
obj.destination = arr[i].children[j].con_id;
edge.push(obj);
}
}
}
model.edges=edge;
console.log(edge)
console.log("model")
console.log(JSON.stringify(model))
$scope.flowchartselected = [];
var modelservice = Modelfactory(model, $scope.flowchartselected);
$scope.model = model;
$scope.modelservice = modelservice;
})
any update ?
Working Example
It is now working.
The issue was when we load the directive first time it has no parameter value to it. So, when the chart directive try to initialize your chart with no parameter it gets an error. So, it will not work anymore.
How solve the issue?
Just give a dummy parameter upon the page load. I have given the dummy model as,
$scope.model = model;
$scope.modelservice = modelservice;
So, first your chart will display a chart based on the dummy values. After that it populates chart with the data from the server ($http.get())

Built a JSON from string pieces

I work with a line chart in ExtJS4 now. The chart is based on the data of the store. The store change its data with help 'loadRawData()' function.
Familiar situation, isn't it?
AJAX sends strings every 10 seconds and I need to built JSON from this pieces of strings. I'm trying:
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
var firstPiece = JSON.parse(response.responseText)[i].date;
var secondPiece = JSON.parse(response.responseText)[i].connectCount;
var recording = "{'machinesPlayed':"+firstPiece+", 'machinesOnline':"+secondPiece+"}";
jArray.push(recording);
}
jArray = '['+jArray+']';
store.loadRawData(jArray);
}
But it is wrong way. How to do it properly?
You could use loadData() function instead of loadRawData(). loadData() only needs an array of objects.
success: function(response) {
var requestMassive = JSON.parse(response.responseText);
var jArray = [];
for(var i=0;i<requestMassive.length;i++){
jArray.push({ machinesPlayed: requestMassive[i].date, machinesOnline: requestMassive[i].connectCount});
}
store.loadData(jArray);
}
I didnt get what you are trying to achieve.But it can be formed this way.Try this out.
var recording = {
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
}
jArray.push(recording);
OR
jArray.push({
"machinesPlayed" : firstPiece,
"machinesOnline" : secondPiece
});

Resources