Loading map data from JSON using $.getJSON - javascript

Using gmap3 (a jquery plugin) to display a Google maps interface. I'm trying to load my data from a JSON file but for some reason it's not executing. The map displays, the addMarkers() function is being called, but if I put a console.log() anywhere inside function(data), it doesn't display.
I'm somewhat confused about these anonymous functions and haven't worked with asynchronous functions before. Any advice would be much appreciated.
Javascript
$(document).ready(function(){
displayMap();
addMarkers();
});
// Create map with options
function displayMap(){
$('#map_canvas').gmap3({
map: {
options: mapOptions
}
});
};
// Load data and add markers for each data point
function addMarkers(){
$.getJSON( dataURL, function(data) {
$.each( data.markers, function(i, marker) {
console.log( marker.lat + ':' + marker.lng + ':' + marker.data.category + ':' + marker.data.content );
})
});
};
JSON
{
markers: [
{ lat:-30, lng:145, data: {title: "Le Restaurant", category:"Restaurant", content:"Some French restaurant"} },
{ lat:-30, lng:145, data: {title :"Gem Cafe", category:"Cafe", content:"They sell coffee"} },
{ lat:-30, lng:145, data: {title :"Home", category:"Home", content:"Home sweet home."} }
]
}

Silly me, just checked my JSON format using http://jsonlint.com/ and discovered it was malformed. I needed to enclose the 'key' names in quotes like so ...
{
"markers": [
{ "lat":-30, "lng":145, "data": {"title": "Le Restaurant", "category":"Restaurant", "content":"Some French restaurant"} },
{ "lat":-30, "lng":145, "data": {"title" :"Gem Cafe", "category":"Cafe", "content":"They sell coffee"} },
{ "lat":-30, "lng":145, "data": {"title" :"Home", "category":"Home", "content":"Home sweet home."} }
]
}

Related

How do I map the return of my dataSource to a Kendo AutoComplete UI

I have a Kendo jquery AutoComplete UI component with a remote REST web API dataSource. I want to map the responce of the API to the autoComplete. I have it displaying the choices but when I examine the select function I just see what I've selected. What I want is the complete json object on the select event. Or at least what I really need is the unitKey property.
my code:
//create AutoComplete UI component
$("#autoAddress").kendoAutoComplete({
minLength: 3,
dataTextField: "address",
filter: "startswith",
placeholder: "Address lookup ...",
select : function(e) {
var item = e.item;
console.log(item.text());
},
dataSource: new kendo.data.DataSource ({
serverFiltering: true,
transport: {
read: {
url: "https://testapi.mydomain.com/homeinfo/api/address/",
// dataType: "jsonp",
data: {
q : function() {
return $("#autoAddress").data("kendoAutoComplete").value();
},
maxRows: 30
}
}
},
schema : {
data: function(response){
return response;
}
}
})
});
sample date from api call:
[
{
"unitKey": "S37.75 ",
"address": "1234 ADDISON AVE"
},
{
"unitKey": "S22.215 ",
"address": "1234 AUGUSTINE DR"
},
{
"unitKey": "L100.9 ",
"address": "1234 AVENIDA DE LAS CASAS"
}
]
I'm trying to get the "unitKey" when the user makes a selection from the autocomplete component.
You want to look at e.dataItem rather than e.item:
console.log(e.dataItem.unitKey);
In cases like this I usually log 'e' itself to the console or breakpoint with the debugger to inspect it to see what it contains since the documentation is not always as comprehensive as it could be.

Execute javascript code delivered via PHP using AJAX

I have been stumped on this for about 2 hours now.
My problem is that I need to load an array from a MySQL database using PHP and Ajax, and use the array in JavaScript.
I got that part working fine however the part where it references "onClick" and contains a function to run does not work. It provides numerous errors which say the exact same thing.
Uncaught RangeError: Maximum call stack size exceeded
at buttons.<computed>.onClick (app.js:1281)
The example of the array is the following:
[
{
"text": "Lost to Competitor",
"onClick": "closeOpportunity(\"Lost to Competitor\", el, stages)"
},
{
"text": "No Budget \/ Lost Funding",
"onClick": "closeOpportunity(\"No Budget \/ Lost Funding\", el, stages)"
},
{
"text": "No Decision \/ Non-responsive",
"onClick": "closeOpportunity(\"No Decision \/ Non-responsive\", el, stages)"
},
{
"text": "Price",
"onClick": "closeOpportunity(\"Price\", el, stages)"
},
{
"text": "Other",
"onClick": "closeOpportunity(\"Other\", el, stages)"
},
{
"text": "Won via Another Opportunity",
"onClick": "closeOpportunity(\"Won via Another Opportunity\", el, stages)"
}
]
My code for loading the array is the following:
function closeOpportunity(name, el, stages) {
$$("#opportunity_loss_reason2").text(name);
$$("#closedType").text("Closed Lost");
$$("#convertToProject").hide();
$$("#lostReasonLI").show();
upStepper(el, stages);
}
var stages = [
"enquiry",
"qualification",
"proposal",
"negotiation",
"closed"
];
var buttons = [];
app.request.json('scripts/lostButtonsArray.php', function (data) {
buttons = data;
console.log(buttons);
});
buttons.forEach((v, i) => {
console.log(v['onClick']);
buttons[i]['onClick'] = function() { window.eval.call(window, v['onClick'])(el, stages); };
});
app.dialog.create({
title: 'ECOM',
text: 'Why was the opportunity lost?',
cssClass: 'custom-dialog',
closeByBackdropClick: 'true',
buttons: buttons,
verticalButtons: true,
}).open();
I have already tried using regular eval() and loading the code directly without any sort of helper (eval, window.eval).
I will be happy to provide more information to help solve this problem if I haven't provided enough information.
Found the solution.
I was trying to load "name" instead of "text"
Working function
app.request.json('scripts/lostButtonsArray.php', function (data) {
buttons = data;
buttons.forEach((v, i) => {
buttons[i]['onClick'] = function() { eval('closeOpportunity')(v['text'], el, stages); };
});
});

Combining two JSON files

Right now I am feeding in the contents of one JSON feed and display
(function () {
var twitterLikes = "data.json";
//Grab the JSON
$.getJSON(twitterLikes, {
format: "json"
})
.done(function (data) {
//iterate through each item
$.each(data.likes, function (i, likes) {
//Print out JSON results
var twitterLike = '<div class="twitterLike" id="' + likes.id + '"><img class="twitterLikeImage" src="' + likes.image + '"><p class="twitterLikeCaption">' + likes.caption + '</p><a class="twitterLikeLink" href="' + likes.link + '" target="_blank">See original post</a></div>';
//Append printed reuslts to parent container
document.getElementById("twitterLikes").innerHTML += twitterLike;
//Cap the results
if (i === 12) {
return false;
}
});
});
})();
This needs modification. I have another JSON file that I've created as some sort of "Locked" file, which basically locks a particular post in a given position.
{ "locked":[{"id":90210, "position":3}] }
How would I modify my function to parse the 2nd JSON File (locked). Basically look in the locked file, see if theres an id and position. Match that id to the 1st JSON file (data.json). Lock that post based on id to the particular position. Go through data.json and paint the rest of the posts skipping the locked positions. Should only show 12 at most also.
I am not sure I understand your locking mechanism, but some variant on (I have used lodash to help - but it's not necessary)
$.getJSON("data.json", { format: "json" })
.done(function (data) {
$.getJSON("locked.json", {format: "json"})
.done(function(locked){
var lockedIds = _.map(locked, function(l){
return l.id
})
$.each(data.likes, function(i, likes){
// If not locked then process
if (!_.contains(likes.id, lockedIds)){
// do something here
}
})
})
}
Hope this helps.
Thanks Joe. This is what I got so far:
$.getJSON("data.json", { format: "json" })
.done(function( data ) {
$.getJSON("locked.json", {format: "json"})
.done(function(locked){
var lockedIds = _.map(locked, function(l){
return l.id
})
//iterate through each item
$.each( data.likes, function( i, likes ) {
if (!_.contains(likes.id, lockedIds)){
//Print out JSON results
var twitterLike='<div class="twitterLike" id="'+likes.id+'"><img class="twitterLikeImage" src="'+likes.image+'"><p class="twitterLikeCaption">'+likes.caption+'</p><a class="twitterLikeLink" href="'+likes.link+'" target="_blank">See original post</a></div>';
//Append printed reuslts to parent container
document.getElementById("twitterLikes").innerHTML+=twitterLike;
}
//Cap the results
if ( i === 12 ) {
return false;
}
});
});
})();
I seem to be off a little bit. You are right, I don't necessarily need to combine the two. More need to display those posts in a "locked" position, then move onto the rest from the original feed.
DATA.JSON
{
"count": 2,
"likes": [
{
"link": "http://twitter.com/p/tQc2YNh3ox/",
"caption": "Yada",
"profile_pic": "",
"likes": 27,
"id": "815278414704900657_1364335477",
"image": "http://twitter.com/pic1.png"
}, {
"link": "http://twitter.com/p/tQc2YNh3ox2/",
"caption": "Yada2",
"profile_pic": "",
"likes": 27,
"id": "815078520979421610_1364335477",
"image": "http://twitter.com/pic2.png"
}
]
}
LOCKED.JSON
{
"likes": [
{
"id": "815278414704900657_1364335477",
"position": 3
}, {
"id": "815078520979421610_1364335477",
"position": 5
}
]
}

How can we consume JSON data using OPENUI5/SAPUI5?

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.

Consume WCF crossdomain using JSONP to store in datagrid and view data dojo?

I can't find this anywhere and i don't know why the cross domain REST request is not solved by dojo. anyways here is the problem:
I am implementing dojo data-grid, and i am trying to get the data for the grid from a WCF that is not in my domain, so i crossdomain problem is raised and i am trying to over come this problem by using JSONP.
but i am a newbie in dojo so i am probably doing something wrong. here is my code:
require([
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/store/Cache",
"dojox/grid/DataGrid",
"dojo/data/ObjectStore",
"dojo/query",
"dijit/form/Button",
"dojo/domReady!",
"dojo/request/script","dojo/dom-construct"
],function(script, domConstruct){
//make the request just as before
script.get("http://localhost:8060/ListService.svc/LoadLists?uid=c4446476-15e6-e111-9ecb-b7c5971d170a", {
jsonp: "callback",
query: {q: "#dojo"}
}).then(function(data){
test = data;
}).then(function(){
console.log(results);
});
}, function (JsonRest, Memory, Cache, DataGrid, ObjectStore ,query) {
grid = new DataGrid({
store: dataStore = test,
structure: [
{ name: "Blog Id", field: "id", width: "50px", },
{ name: "Name", field: "listtype", width: "200px",classes:"Name" },
{ name: "Phone Number", field: "longlevel", width: "200px",classes:"test" }
]
}, "gridTest"); // make sure you have a target HTML element with this id
grid.startup();
dojo.query("body").addClass("claro");
grid.canSort = function () { return false; };
});
the error i am getting is query is not a function. any ideas how to implement this correctly.
Simple mistake just put the data grid command inside the first then with the data returning
require([
"dojo/store/JsonRest",
"dojo/store/Memory",
"dojo/store/Cache",
"dojox/grid/DataGrid",
"dojo/data/ObjectStore",
"dojo/query",
"dijit/form/Button",
"dojo/domReady!",
"dojo/request/script","dojo/dom-construct"
],function(script, domConstruct){
//make the request just as before
script.get("http://localhost:8060/ListService.svc/LoadLists?uid=c4446476-15e6-e111-9ecb-b7c5971d170a", {
jsonp: "callback",
query: {q: "#dojo"}
}).then(function(data){
function (JsonRest, Memory, Cache, DataGrid, ObjectStore ,query) {
grid = new DataGrid({
store: dataStore = test,
structure: [
{ name: "Blog Id", field: "id", width: "50px", },
{ name: "Name", field: "listtype", width: "200px",classes:"Name" },
{ name: "Phone Number", field: "longlevel", width: "200px",classes:"test" }
]
}, "gridTest"); // make sure you have a target HTML element with this id
grid.startup();
dojo.query("body").addClass("claro");
grid.canSort = function () { return false; };
})
}).then(function(){
console.log(results);
});
};
If you still find a problem probably because the grid is created before the request is returning from the wcf.
if that happened please use the Deferred in dojo 1.8 which make you in control of you processes sequence.
so you will be able to call the request give it some time and then put the data in the grid to be viewed.

Categories