I'm trying to iterate through some JSON results from the YQL geo.places table using the YQL jQuery plugin (http://plugins.jquery.com/project/jquery-yql) troubleshooting with the following code;
$.yql("select * from geo.places where text=#{placename}", {
placename: '90210'
},
function(data) {
var Results = data.query.results;
$.each(Results.place, function(name, value) {
alert(name + ":" + value);
});
});
});
Except, whenever there is more than one "place" in the results, the alert will spit back "0:[object][object]", "1:[object][object]", etc (for each place). Whenever there is only one place result, the alert will spit back all the names and values of just the one place (woeid, name, country, admin1, etc.)
Essentially I'd like to...
input a zip code to YQL
verify the city/state/country from results against user submitted data
update latitude and longitude fields from the results
Thanks!
If Yahoo returns a single place, it does so as a property of results, not as an array of places. If it's not an array, you can't iterate. So test whether it's an array; if it's not, make it one:
$.yql("select * from geo.places where text=#{placename}", {
placename: '90210'
},
function(data) {
var Places = data.query.results.place;
if (!Places.length) Places = [Places];
$.each(Places, function(index, place) {
alert(index + ":" + place.name);
});
});
});
Related
So I'm building this web forecast app using OpenWeatherMap API, and so far I'm being able to fetch the data from the first iteration of the list's output, however I need to obtain the data of other specific fields aswell. Here's a bit of my code:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
var temperature = document.createElement("h6");
temperature.textContent = data.daily[0].temp.max + "°" + " / " + data.daily[0].temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
});
And here's an example of what the API's output looks like (I'm only showing the first iteration in here, but there are at least 6 in total, https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=APPID&units=metric):
{"lat":4.61,"lon":-74.08,"timezone":"America/Bogota","timezone_offset":-18000,"daily":
[
{"dt":1600876800,
"sunrise":1600857917,
"sunset":1600901504,
"temp":{"day":18.14,"min":8.99,"max":18.14,"night":12.08,"eve":15.45,"morn":8.99},
"feels_like":{"day":17,"night":11.02,"eve":14.6,"morn":7.58},
"pressure":1017,"humidity":54,
"dew_point":8.69,
"wind_speed":1.2,
"wind_deg":164,
"weather":[{"id":501,"main":"Rain","description":"moderate rain","icon":"10d"}],
"clouds":82,
"pop":0.94,
"rain":5.85,
"uvi":15.14}
]
}
So as you can see, I'm being able to print into my HTML the data contained into "data.daily[0].temp.", but it only works for the first set of fields and I got no clue how to select a specific iteration. I'm sure I'm missing something into the concat, but nothing I've tried has worked so far.
Any help would be greatly appreciated, and rewarded with an imaginary waffle. THX :D
The temperatures for each day data.daily are defined as an JavaScript array of objects. You can simply access them by their index, which indicates their position in the array.
data.daily[0] // First element
data.daily[1] // Second element
data.daily[2] // Third element
Once you have selected an object within the array, you can then access certain values like data.daily[2].temp.max.
The cool thing about arrays is that you can iterate them with a loop. This will save you a lot of writing, if you want to print out each temperatures for every day:
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&appid=YOUR_API_KEY_HERE&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily.forEach(function (date) {
var temperature = document.createElement("h6");
temperature.textContent = date.temp.max + "°" + " / " + date.temp.min + "°";
document.getElementById("temperaturaBogVier").appendChild(temperature);
})
});
Please note: I've removed the appid=XXXXX part of the request URL, because it contains your personal API key for OpenWeather, which you should not share publicly.
If I understand the question correctly, you want to take all daily max/min-values and put them into elements that you want to append to another element.
Here is a way to do that
ajaxGet("https://api.openweathermap.org/data/2.5/onecall?lat=4.6097&lon=-74.0817&exclude=current,minutely,hourly,alerts&units=metric", function (response) {
var data = JSON.parse(response);
console.log(data);
data.daily
.map(datapoint => datapoint.temp) //get the temp value/object from each datapoint
.map(temp => { //create an element and add each max/min value to that element's textContent
const temperature = document.createElement("h6");
temperature.textContent = temp.max + "° / " + temp.min + "°";
return temperature;
})
.forEach(element => { //add each of the elements created in the previous map to the desired element
document.getElementById("temperaturaBogVier").appendChild(element);
});
});
As pointed out in the other answer, I've also removed the app-id query parameter
I have a multipage app in Cordova using a (for now local only) SQLite database. All I am wanting to do initially is to use a single row to store 2 different values which I would like to occasionally SELECT, modify, then UPDATE the row with again. I think I am able to SELECT a specific a row but I can't figure out how to parse the two values in the row ready for assigning to variables.
I am using the cordova-sqlite-storage plugin.
var myDB;
/first create/open the database
myDB = window.sqlitePlugin.openDatabase({ name: "mySQLite.db", location: 'default' });
//create table and populate
myDB.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS mcappDB (id text primary key, val1 integer, val2 integer)');
tx.executeSql('INSERT INTO mcappDB VALUES (?,?,?)', ['SessionNums', 12, 15]);
}, function (error) {
alert('Transaction ERROR: ' + error.message);
}, function () {
alert('Table created and populated');
});
//SELECT row and parse (and needing to store parsed data as global variables)
myDB.transaction(function (tx) {
tx.executeSql('SELECT * FROM mcappDB WHERE id="SessionNums"', [],
function (tx, rs) {
alert('Whats in here? ' + rs);
},
function (tx, error) {
alert('select ERROR: ' + error.message);
});
});
Presently, rs just returns as [object Object] and I am unable to parse it. I have tried using rs.toString(0), rs.getString(0), rs.column.item(1), rs(1), etc to no avail.
I in fact began with WHERE id=SessionNums, i.e. no quotes on the row id, but oddly this returned an error with no such columns: SessionNums, tho I thought using the WHERE id= command as such was for fetching row information?! e.g. http://zetcode.com/db/sqlite/select/
Any and all help would be much appreciated.
Cheers, Chris.
First of all, make sure that you have inserted the record before you read it with promises.
Separate insert function and read function and then use this:
$.when(insertFunc()).done(readFunc());
After that you can parse the results as follow:
if (rs.rows.length > 0) {
for (var i = 0; i < rs.rows.length; i++) {
console.log("val1: " + rs.rows.item(i).val1 + "\n" + "val2: " + rs.rows.item(i).val2);
}
}
Best regards,
#BernaAsis
I have used an ajax call to retrieve data from Googles places api and I have used a for/in loop to begin to pull the information. the information that I am looking for logs to the console, but I cannot get it to display in an array how I would like it to.
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
at this point the way it is returning my data, when I run a script to pull a random string, it pulls a random letter out of the last value to be found when searching through my JSON object.
Here is my code. Not sure if I explained myself clearly but it's the best that I could word what I am looking to do. Thanks.
// **GLOBAL VARIABLES** //
// Chosen Restaurant display area
var display = document.getElementById('chosenVenue');
// Grab button
var button = document.getElementById('selectVenue');
// Sample Array that gets queried
var venueData = ["McDonalds", "Burger King", "Wendys"];
// Grab JSON data from Google
$(document).ready(function(){
$.ajax({
url: 'hungr.php', // Send query through proxy (JSONP is disabled for Google maps)
data: { requrl: "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7484,-73.9857&radius=800&sensor=false&keyword=restaurants,food&key=AIzaSyBkCkXIHFjvqcqrRytSqD7T_RyFMNkR6bA&callback=?"}, // URL to query WITH parameters
dataType: "json",
type: "GET", // or POST if you want => update php in that case
success: function (data) {
// Traverse the array using for/in loop using i as var
for (var i in data.results) {
var results = data.results[i];
var nameResults = results.name;
console.log(nameResults);
var typesResults = results.types;
console.log(typesResults);
var vicinityResults = results.vicinity;
console.log(vicinityResults);
};
// On button click, randomly display item from selected array
button.addEventListener('click', function () {
console.log('clicked');
display.style.display = 'block';
//display.innerHTML = nameResults[Math.floor(Math.random() * nameResults.length)];
display.innerHTML = nameResults.toString() + "<br />" + vicinityResults.toString();
});
console.log('It is working');
},
error: function (request, status, error) {
console.log('It is not working');
}
});
});
Right now I am getting a list of names when I request names which is a parameter in the JSON object. Is there a way to get it into an array so the I can randomly select one of the values from the array?
Use the push method and a non-local variable:
this.nameResults = this.nameResults ? this.nameResults.push(results.name) : [];
then reference that with the Math.random method:
this.randName = function(){ return this.nameResults[Math.random() * this.nameResults.length | 0] };
References
Using Math.random flexibly
JavaScript: fast floor of numeric values using the tilde operator
I'm altering a google example template to try to construct a query that finds the nearest location in the table to the user-entered city. And in this example, I just want to output the lat and lon and probably the "id" of the nearest table location to the user-inputted city. First, I'm using my LATITUDE column as location because it's been geocoded in the table as a two-column location. Strangely, when I alerted that variable, it only displays the latitude instead of the lat/lng coordinates. I thought since LATITUDE was acting as a two column location, it would return a lat/lng.
So when I run this simple query after pushing the "go" button after entering a city:
var queryList = [];
queryList.push("SELECT LATITUDE,LONGITUDE FROM ");
queryList.push(tableid);
and then alert the values, in the popup window, it works fine: http://greenandtheblue.com/whentoplant/test_query_geocode.html, alerting a lat and lon from the table...what I hoped it would.
But when I try to use the st_distance, I don't get any suggestion that it's working.
queryList.push("ORDER BY ST_DISTANCE(LATITUDE, LATLNG("+coordinate.lat()+","+coordinate.lng()+")) LIMIT 1");
http://greenandtheblue.com/whentoplant/test_query_geocode_notworking.html
I prefer this method of querying...seems simpler:
query: {
select: 'LATITUDE',
from: tableid
},
but I gathered from the example that I needed to put the second query (acted on when I push go) in an array of sorts, which makes it a bit more complicated.
I hope this is a clear enough question. Thanks for any help.
Shad
If I make the query like this:
queryList.push("SELECT STATION,STATION_NAME,ELEVATION,LATITUDE FROM ");
queryList.push(tableid);
//query seems to work when I comment out the line below.
queryList.push("ORDER BY ST_DISTANCE(LATITUDE, LATLNG("+coordinate.lat()+","+coordinate.lng()+")) LIMIT 1");
var query = encodeURIComponent(queryList.join(' '));
var gvizQuery = new google.visualization.Query(
'http://www.google.com/fusiontables/gvizdata?tq=' + query);
gvizQuery.send(function(response) {
var datatable = response.getDataTable();
var header = 'No results';
var content = 'Sorry, no store delivers here.';
if (datatable && (datatable.getNumberOfRows() > 0)) {
header = datatable.getValue(0, 0);
content = datatable.getValue(0, 1)+"<br>Station:"+datatable.getValue(0,0)+"<br>Elevation:"+datatable.getValue(0,2);
}
infoWindow.setContent('<h3>' + header + '</h3>' +
'<p>' + content + '</p>');
infoWindow.setPosition(coordinate);
infoWindow.open(map);
});
It works for me.
changed:
var query = encodeURIComponent(queryList.join('')); // empty string
to:
var query = encodeURIComponent(queryList.join(' ')); // single space
Am a bit confused here, what does the formatResult and formatItem do in the JQuery Autocomplete plugin?
I have a function that is returning a comma separated string (from Django), but my autocomplete function is unable to split the string into individual entries/rows, how can i achieve this using autocomplete functions?
e.g the returned result looks like this and this what autocomplete is showing :-
["one","oneTwo", "Onethree", "anotherOne"]
I want when showing in the autocomplete field to have it split like this:-
one
oneTwo
Onethree
anotherOne
I have a feeling i can use the formatResult and formatItem but i dont know how, there are no good examples out there !!
my code in the html template:
function autoFill(){
$("#tags").autocomplete("/taglookup/", {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
}
Am using Dajango to process the GET request.
Gath
formatItem formats an item for display in the dropdown list, while formatResult formats the item for display in the inputbox once it is selected.
By default, autocomplete expects to get data from the specified url formatted as:
foo|bar|baz|bing
zaz|ding|blop|grok
where each line is a row of data; each row being the data that it passes to formatItem and formatResult. You may want to take the path of least resistance and return data in the way it likes.
If you want to use data that doesn't fit autocomplete's assumptions, you'll need to use the (undocumented, as far as I can tell) parse option to identify a function to parse the results of your ajax request. It appears to me that your django view is returning an array rather than returning a formatted string. To format your array as jquery would like it:
return HttpResponse('|'.join(your_array), mimetype='text/plain')
Here is an example of doing autocomplete using non-standard autocomplete data (JSON):
<script type="text/javascript">
format_item = function (item, position, length){
return item.title;
}
// Handle data from ajax request
prep_data = function(data){
tmp = $.evalJSON(data);
parsed_data = [];
for (i=0; i < tmp.length; i++) {
obj = tmp[i];
// Other internal autocomplete operations expect
// the data to be split into associative arrays of this sort
parsed_data[i] = {
data: obj ,
value: obj.isbn13,
result: obj.title
};
}
return parsed_data
}
$(document).ready(function(){
$("#fop").autocomplete({
url : "{% url book-search %}",
// undocumented
parse: prep_data,
formatItem: format_item,
});
})
</script>
I have not been able to get formatMatch and formatResult to work so far. I am still working on the 'correct' way to use them. However, as a workaround you can use the parse option as follows. Just to be clear, in this example, formatItem and parse are functional while formatResult and formatMatch are not functional.
jQuery(function(){
$('#profile-tabs_addresses_grid_b_a_PostalCode').autocomplete
('http://test.mydomain.com/locality/postalcodes/', {
minChars:1,
delay:400,
cacheLength:100,
matchContains:true,
max:10,
formatItem:function(item, index, total, query){
return item.PostalCode + ': ' + item.Region + ', ' +
item.City + ', ' + item.Country;
},
formatMatch:function(item){
return item.PostalCode;
},
formatResult:function(item){
return item.PostalCode;
},
dataType:'json',
parse:function(data) {
return $.map(data, function(item) {
return {
data: item,
value: item.PostalCode,
result: item.PostalCode
}
});
}});
});
here is the json data that comes back from the data url ( whitespace
added for easier viewing ):
[
{City:"St. Louis", Country:"USA", PostalCode:"63103", ID:3,
Region:"Missouri"},
{City:"St. Louis", Country:"USA", PostalCode:"63109", ID:1,
Region:"Missouri"},
{City:"St. Louis", Country:"USA", PostalCode:"63119", ID:2,
Region:"Missouri"}
]
When I type a 6 in the postal code box, it shows all three options
properly formatted as:
63103: Missouri, St. Louis, USA
63109: Missouri, St. Louis, USA
63119: Missouri, St. Louis, USA
and when I select one the textbox receives just the selected
postal code.