Speed up multiquery with Instagram api - javascript

I'm getting the images with the media/search endopoint passing a lat and lon like this
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
and then I'm gettin only the pics with a certain tag #instabeachpro,if the pic is not found I go trough the next set of pics adding the last pic created_time to the url with the max_timestamp parameter, here is the code I'm using
(function(){
var url,tags,menos,photos = new Array(),i=90;
function search(){
generateResource(tag;
$.getJSON(url, toScreen);
}
function init(){
bindEventHandlers();
}
function generateResource(){
url = Instagram.Config.apiHost + "/v1/media/search?lat=28.46555600&lng=-16.25113310&distance=5000&callback=?&client_id=" + Instagram.Config.clientID;
return url;
}
function toScreen(){
var next_url=url+"&max_timestamp="+data.data[data.data.length - 1].created_time;
$.each(data.data, function(index, photo){
i--;
tags=photo.tags;
menos=jQuery.inArray( "instabeachpro", tags );
if(menos!=-1)
{
$('div#photos-wrap').append("<div id='"+i+"' ><a href='"+photo.link+"'><img src='"+photo.images.low_resolution.url+"'/></a></div><div><img class='second' src='"+photo.user.profile_picture+"'/></div>");
}
else{
i++;
}
});
if(next_url!=undefined+"&callback=?" && i>=0){
console.log(i);
pagination(next_url);
}
}
function pagination(url)
{
$.getJSON(url, toScreen);
}
Instagram.App = {
search: search,
init: init
};
function bindEventHandlers(){
$('body').on('click', '#loadObject', function(){
url=$(this).attr('data-next-url');
i=90;
if(url=='undefined')
{
alert("undefined");
}
else{
pagination(url);
return false;
}
});
}
}());
$(function(){
Instagram.App.init();
Instagram.App.search();
});
This works but it's extremely slow and I have no idea what to do to speed it up, because the api doesn't support searching like I want to do, and i need to get al the pcitures with a certain tag IN a certain location, I have been told a number of times this is the only way to do it, but there has to be a faster way.Thank you.

Your method is extremely inefficient, since the tag you are searching is not popular and very small percentage of people use it, so getting API around location and then filtering by tag is expensive on number of API calls.
Search the other way round, make API call for the tag and then check for location for that photo. Check this implementation: http://www.gramfeed.com/instagram/tags#instabeachpro
You can get the tag photos and maps it on Google Maps, scroll to load more photos and see that very few of the #instabeachpro photos are tagged with location

Related

Handling random number of links by using AJAX Jquery

I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>

Basic Calling Function Troubleshooting

How do I get the function checkViewers(); to work properly? I believe I am calling it wrong within the JS document file and therefore the JS is not reading the function properly.
The current code:
//Content Viewer Information
function checkViewers() {
//Base Variables
var viewer = $('#viewed span.user');
var totalViews = $('#viewed span.user').length;
var shortenViews = $('#viewed span.user').length -1;
if (totalViews === 0) {
$('<span> 0 people have </span>').insertBefore($('#viewed span:last-child'));
}
if (totalViews === 2) {
$('<span> and </span>').insertAfter(viewer.first());
}
if (totalViews >= 3) {
viewer.slice(1).hide();
$('<span> and </span>').insertAfter(viewer.first());
$('<span class="user count"></span>').insertAfter(viewer.eq(2));
$('.count').html(shortenViews + ' more people');
}
}
The function is called towards the bottom of the remaining JS, after the JSON Data has been called.
Ideally, the JSON Data should be inputted into the HTML and the function should catch the number of viewers. This should then effect how the viewers are being shown in the HTML, upon how many viewers are being listed.
View the Plunker.
Making my comment an answer:
Ajax is Asynchronous. You ordered a pizza off the internet and you try to eat the pizza before it gets to your house. You have to wait for the pizza to show up before you eat it. AKA, you can not call your function until the data is there. So when you set the html, you call your function
xhr.onload = function() { //<--Function is called when the Pizza shows up at your door and the doorbell rings
... //removed a bunch of code....
//Update Page With New Content
var viewerSection = $('#viewed');
viewerSection.html(newViewers); //You open up the pizza box
checkViewers(); //<--- MOVE IT HERE, The pizza is here!!!!
}
};
xhr.open('GET', 'data.json', true); //<-- You set up your pizza order
xhr.send(null); //<--You make the pizza purchase
//checkViewers(); <-- PIZZA IS NOT HERE!!!!

javascript run function with adobe air

I am working on the adobe air with javascript and html. I want to run multiple functions in a function with show the percentange run on the each function but the percentage also show the last calculation please help me.
Edit: added code snippet from comment, but I may have butchered the layout.
function show_percentage() {
down_admin()
down_staff()
down_client() }
function down_admin() {
down all information of admin from the server; flag=1; }
function down_staff() {
down all information of the staff falg=2; }
we want to calculation show the every after loaded functions. as percentage=25% to 100%
If you downloading several types of info and want to show summary progress, first you need to know bytes total of each download. When you get ProgressEvent from each operation, you may call function show():
function show() {
var progress = (adminBytesLoaded + staffBytesLoaded + clientBytesLoaded) * 100 /
(adminBytesTotal + staffBytesTotal + clientBytesTotal);
//show progress somehow
}
Update: some clarifications
Load resource you need with Loader. Add event listener to ProgressEvent on Loader.contentLoaderInfo. There will be three listeners for three load operations - load admin data, client data and staff data. When you get progress event from each operation (track it with three vars), you will know download size total:
var adminTotal:int;
var clientTotal:int;
var staffTotal:int;
var adminLoaded:int;
var clientLoaded:int;
var staffLoaded:int;
function onAdminLoadProgress(event:ProgressEvent):void
{
adminLoaded = event.bytesLoaded;
adminTotal = event.bytesTotal;
//if other operations already going, show progress
if (clientTotal && staffTotal)
{
showProgress();
}
}
function onClientLoadProgress(event:ProgressEvent):void
{
clientLoaded = event.bytesLoaded;
clientTotal = event.bytesTotal;
if (adminTotal && staffTotal)
{
showProgress();
}
}
//write onStaffLoaded yourself as an exercise :)))
I'm assuming you will make single request for each of those three downloads.

Need help with Javascript....I think

I'm trying to bypass going through a bunch of menus, to get to the data I want directly.
Here are the links I want to go to:
http://factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53053072904&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53025981400&tree_id=4001&context=dt&_lang=en&_ts=288363511701
factfinder.census.gov/servlet/MapItDrawServlet?geo_id=14000US53067011620&tree_id=4001&context=dt&_lang=en&_ts=288363511701
Notice, if you pull that up right now, you simply see a GIF outline of the map, however there is no map data "behind" it.
However, if you go to: factfinder.census.gov/servlet/DTGeoSearchByListServlet?ds_name=DEC_2000_SF1_U&_lang=en&_ts=288392632118
Select Geographic Type: ..... ..... Census Tract
Select a State: Washington
Select a County: Pierce
Select one or more geographic areas: Census Tract 729.04
Hit "Map It"
The map will load perfectly. Also, until you close your browser, any of the other links will work perfectly. What I want to do, is be able to bypass these 5 steps, but obviously something is preventing this. Is there a feasible workaround? I have my own domain that I would be able to upload new Javascript or HTML files or whatever is needed.
Looking at the relevant code, there's only a few functions that are needed. The "Map it" button calls the mapit function with a string literal of '/servlet/MapItDrawServlet'.
function launchMapItServlet(mapItServlet) {
context = document.form1.context.value;
lang = "en";
url = mapItServlet + "?geo_id=" + geo + "&" + "tree_id=" + tree_id + "&context=" + context + "&_lang=" + lang;
url = getAFFWindowLocation(url, true);
windowCtr++;
window.open(url, "identify" + windowCtr, "menubar=yes,scrollbars=yes,resizable=yes,top=10,left=10,width=750,height=550");
}
function mapItMulti(servlet) {
if (numberOfSelections(document.forms["form1"].search_results) == 0 || numberOfSelections(document.forms["form1"].search_results) > 1) {
alert(ALERT_MSG1);
}
else if (canMapItMulti(document.forms["form1"].search_results)) {
index = document.forms["form1"].search_results.selectedIndex;
geo = document.forms["form1"].search_results.options[index].value;
tree_id = document.form1["tree_id"].value;
launchMapItServlet(servlet);
}
else {
alert(ALERT_MSG1);
}
}
function mapit(mapItServlet) {
geo = "";
mapItMulti(mapItServlet);
}
Notice the window.open function which will be the relevant information that you will want to use, especially the 'url' variable.

Javascript in Firefox Plugin: Delay in for loop

I am aware that when coding an extension, there is no way we can delay a function call except for using a setTimeout call but here's what I am trying to achieve in a plugin that I am developing for Firefox (this is not for Javascript embedded into a web page by the way):
for (var i = 0; i < t.length ; i++) {
//Load a URL from an array
//On document complete, get some data
}
The idea is simple. I have an array of URLs that I want to parse and extract some data out of. Each of these URLs take some time to load. So, if I try to get some data from the current page without waiting for the page to load, I will get an error. Now, the only way to do this as I know is as follows:
firstfunction: function() {
//Load the first url
setTimeout("secondfunction", 5000);
}
secondfunction: function() {
//Load the second url
setTimeout("thirdfunction", 5000);
}
And so on... I know this is obviously wrong.. I was just wondering how people achieve this in Javascript...
EDIT: Sorry about not being more detailed...
I'm not convinced that this type of foolery is necessary but I'm not an extension dev so who knows. If this is the approach you want, then just have the setTimeout call refer to the same function:
var index;
firstfunction: function() {
// do something with `index` and increment it when you're done
// check again in a few seconds (`index` is persisted between calls to this)
setTimeout("firstfunction", 5000);
}
I am not sure how to do this from a plugin, but what I've done with iframes in the past is attach a callback to the target document's onLoad event.
Maybe something like:
var index = 0;
var urls = [ ..... ];
function ProcessDocument() { ....; LoadNextDocument(); }
function LoadNextDocument() { index++; /* Load urls[index] */; }
document.body.onLoad = ProcessDocument;
Somewhere in there you'd need to test for index > urls.length too for your end condition.
I had same problem but I used recursion instead of looping.
Below is the running code which changes the innerHTML of an element by looping through the list. Hope its helpful.
<Script type="text/javascript">
var l;
var a;
function call2()
{
l = document.getElementById('listhere').innerHTML;
a = l.split(",");
call1(0);
}
function call1(counter)
{
if(a.length > counter)
{
document.getElementById('here').innerHTML = a[counter];
counter++;
setTimeout("call1("+counter+")",2000);
}
}
</Script>
<body onload="call2()">
<span id="listhere">3,5,2,8</span><Br />
<span id="here">here</span>

Categories