I am trying to get the hereNow parameter from FourSquare using a checkins query on a specific user, unfrotunately I can't seem to get that parameter using checkins, I am seeing all other data regarding a venue except for the hereNow parameter.
Does anyone know how I can get that parameter using checkins? Otherwise, how can I incorporate venue objects and tie into my current code?
Here is my JavaScript to set hereNow as a variable:
var count;
getVenueStatus = function() {
var hereNowUrl = 'https://api.foursquare.com/v2/venues/VENUE_ID?&oauth_token=OAUTH_TOKEN&v=20140303';
$.getJSON(hereNowUrl, {format: "json"}, function(data) {
$(data.response.venue).each(function(index) {
$(this).each(function(index) {
var venue = this;
var hereNowCount = venue.hereNow.count;
count = hereNowCount;
console.log(count);
});
});
});
}
Here is my JavaScript to display the results on a map:
findFoodTrucks = function (param) {
getVenueStatus();
$.mobile.pageLoading();
var url = 'https://api.foursquare.com/v2/users/80507329/checkins?oauth_token=OAUTH_TOKEN&v=20140303';
var mapBounds = new google.maps.LatLngBounds();
if (param.userloc) mapBounds.extend(param.userloc);
$.getJSON(url, function(data) {
$(data.response.checkins).each(function(index) { // groups: nearby, trending
$(this.items).each(function(index) {
var foodtruck = this;
var foodtruckPosition = new google.maps.LatLng(foodtruck.venue.location.lat, foodtruck.venue.location.lng);
var foodtruckIcon = (count > 0) ? 'foodtruck_active.png' : 'foodtruck_inactive.png';
var foodtruckStreet = (foodtruck.venue.location.address) ? '<br>' + foodtruck.venue.location.address : '';
var foodtruckContent = '<strong>' + foodtruck.venue.name + '</strong>' + foodtruckStreet + '<br>';
mapBounds.extend(foodtruckPosition);
addFoodTruckMarker(foodtruckPosition, foodtruckIcon, foodtruckContent);
console.log(foodtruck);
});
if (param.zoomtotrucks) $('#map_canvas').gmap('getMap').fitBounds(mapBounds);
});
})
.error( function() {
loadFoodTrucks(param); //try again
})
.complete( function() {
$.mobile.pageLoading( true );
});
}
Thanks in advance!
The check-in response includes a compact venue, which is only sometimes guaranteed to have a hereNow field. To get the hereNow count, it's probably best to make a second venue detail API call.
PS: also noticed that you seemed to be passing an OAuth token and client ID/secret—in this case, you only need the OAuth token! Take a look at https://developer.foursquare.com/overview/auth for more info.
Related
I have an ajax request which returns a html based on the map Bounds, I need to target certain attributes within the response and store them in variables. The results I get from the response are bootstrap cards which have data-lng and data-lat attributes, how can I store the result properly so I can target the attribues and use them in a loop later? Thank you
Response:
<div id="property-1" class="col box-margin" pid="1">
<div class="card property-card with-overlay v3" data-lng="15.1307613070715" data-lat="44.04613801824153" appId="2">
function initMap() {
google.maps.event.addListener(map, 'idle', function () {
var bounds = map.getBounds();
var getNElng = bounds.getNorthEast().lng(); //max
var getSWlng = bounds.getSouthWest().lng(); //min
var getNElat = bounds.getNorthEast().lat(); //max
var getSWlat = bounds.getSouthWest().lat(); //min
$.ajax({
url: '/property/ajax/html?range_lng=' + getSWlng + '|' + getNElng + '&range_lat=' + getSWlat + '|' + getNElat,
success: function (r, status, jqXHR) {
console.log(r);
if (status == 'success') {
// var response = $('<html />').html(r);
var response = $(r);
var lat= response.find('data-lat');
var lng= response.find('data-lng');
console.log(response);
console.log(lat);
} else {
console.log(status);
}
}
});
}
EDIT Based on original code
Your existing code is close:
var response = $(r);
var box = response.find('#property-1');
(added the # for ID)
however, given that your response is:
<div id="property-1" ...
the root element is already property-1 so it's not a child (and .find() looks at children)
You can either do
var response = $("<div></div>").html(r);
which gives you a root div that you can the use .find on, or you can do:
var response = $(r);
var box = response.filter('#property-1');
EDIT your edit changes things substantially
You now have
var response = $(r);
var lat = response.find('data-lat');
var lng = response.find('data-lng');
as you're not looking at the root element, the $(r) is fine, however the selectors for data-lat/data-lng are incorrect and should be:
var response = $(r);
var lat = response.find('[data-lat]').data("lat");
var lng = response.find('[data-lng]').data("lng");
EXTRA
When the response has multiple results, you can loop through them different ways, depending on what you're trying to get out. Assuming they are all in the format of
<div data-lat... data-lon...`
and all children (see first part) of one or more "root" elements, then you can loop them with:
$("[data-lat]").each((i, e) => {
var lat = $(e).data("lat");
var lng = $(e).data("lng");
});
or you can use .map to create an array of objects:
$("[data-lat]").map((i, e) => {
return {
lat : $(e).data("lat"),
lng = $(e).data("lng")
}
}).toArray();
which will give you an array with an object with .lat and .lng properties.
You might like to consider changing your API (if you can) to only return what you need directly. I suspect it's a 3rd-party API so you don't have that choice, but it's always the better choice if you have it.
I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.
Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}
if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose
Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();
I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.
Inside a web worker, I have an html string like:
"<div id='foo'> <img src='bar'></img> <ul id='baz'></ul> </div>"
Is there any library I can import to easily access id and src attributes of the different tags ? Is regex the only way inside a worker ?
There are two ways to solve this problem efficiently:
Regex
With the risk of getting false positives, you can use something like:
var pattern = /<img [^>]*?src=(["'])((?:[^"']+|(?!\1)["'])*)(\1)/i;
var match = string.match(pattern);
var src = match ? match[2] : '';
Built-in parser & messaging
If getting the HTML right is a critical requirement, just let the browser parse the HTML, by passing the string to the caller. Here's a full example:
Caller:
var worker = new Worker('worker.js');
worker.addEventListener('message', function(e) {
if (!e.data) return;
if (e.data.method === 'getsrc') {
// Unlike document.createElement, etc, the following method does not
// load the image when the HTML is parsed
var doc = document.implementation.createHTMLDocument('');
doc.body.innerHTML = e.data.data;
var images = doc.getElementsByTagName('img');
var result = [];
for (var i=0; i<images.length; i++) {
result.push(images[i].getAttribute('src'));
}
worker.postMessage({
messageID: e.data.messageID,
result: result
});
} else if (e.data.method === 'debug') {
console.log(e.data.data);
}
});
worker.js
// A simple generic messaging API
var callbacks = {};
var lastMessageID = 0;
addEventListener('message', function(e) {
if (callbacks[e.data.messageID]) {
callbacks[e.data.messageID](e.data.result);
}
});
function sendRequest(method, data, callback) {
var messageID = ++lastMessageID;
if (callback) callbacks[messageID] = callback;
postMessage({
method: method,
data: data,
messageID: messageID
});
}
// Example:
sendRequest('getsrc',
'<img src="foo.png">' +
"<img src='bar.png'>" +
'<textarea><img src="should.not.be.visible"></textarea>',
function(result) {
sendRequest('debug', 'Received: ' + result.join(', '));
}
);
Hopefully there is an easy way to do this and my Javascript skills are just lacking. I am wanting to call a function that will get some Facebook posts, add them to an array and return to use elsewhere. Current code is below.
function GetFaceBookStream(name, max) {
FB.init({ apiKey: 'removed for post' });
var lastDate = '2011-04-29Z00:00:00';
var faceBookArray = [];
var faceBookString;
FB.api("/" + name + "/feed", { limit: max, since: lastDate }, function (response) {
var sb = string_buffer();
for (var i = 0; i < response.data.length; i++) {
var post = response.data[i];
sb.append("<li class='facebook'>");
sb.append("<img alt=\"Facebook\" src='Images\\Carousel\\fbIcon.png\' />");
sb.append("<h4>FACEBOOK</h4>\n");
sb.append("<div class=\"from-name\">" + post.from.name + "</div>");
sb.append("<div class=\"time\">" + post.created_time + "</div>");
if (post.message != undefined) {
sb.append("<div class=\"message\">" + post.message + "</div>");
}
sb.append("</li>stringSplitMarker");
}
faceBookString = sb.toString();
faceBookArray = faceBookString.split('stringSplitMarker');
});
return faceBookArray;
}
I realize this set up won't work due to variable scope in Javascript, but this is basically what I'm trying to achieve. Any help will be greatly appreciated!
You're making an asynchronous AJAX request.
The callback only runs after your code finishes.
You need to pass the data back using a callback.
For example:
function GetFaceBookStream(name, max, callback) {
...
FB.api(..., function(response) {
...
callback(something, else);
});
}
You can call the function by supplying a callback to receive the response:
GetFaceBookStream(name, max, function(param1, param2) {
//This code runs later and can use the response.
});