Google Feed API skipping articles? - javascript

With our without an API Key, the google feed api appears to be skipping some of the latest articles in the RSS queried.
Even the default example from https://developers.google.com/feed/v1/devguide?csw=1 appears to be skipping some articles whatever feed I use, see example here: http://codepen.io/anon/pen/xbxxwE
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
function initialize() {
var feed = new google.feeds.Feed("http://fastpshb.appspot.com/feed/1/fastpshb");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("feed");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.appendChild(document.createTextNode(entry.title));
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(initialize);
</script>
I'm specifically using this RSS, http://blog.ncb.org.uk/syndication.axd and the first 2 articles are not appearing either.
Is there anyone else using the API and experiencing the same issue? Where should we go from here? Is there some sort of support for the Feed API?
Cheers,
P.

Google caches the results and it may take up to an hour for it to refresh. That is why the latest articles wont show immediately.
Here was someone having similar issues of the feed not getting updated. It could be that maintaining the Feed API is not a high priority to Google any more. Yahoo Pipes or Superfeedr could be good alternatives.

Related

Wait until response from API to execute javascript Function

I have a site which shows the weather for the next three days of a previously specified city (default city or city searched using a form) --> http://agustin-suarez.com/demos/yield/index.html
I use the API of OpenWeatherMap.org to do so. I am also using Google Tag Manager to send some events to Google Analytics which save the results obtained in the website. This is the code for the Macro (custom html tag):
<script>
(function($) {
$(window).bind("load", function() {
var climaMañana = document.getElementById("reservar1Clima").value;
var precioMañana = document.getElementById("reservar1Precio").value;
var climaPasadoMañana = document.getElementById("reservar2Clima").value;
var precioPasadoMañana = document.getElementById("reservar2Precio").value;
var climaDosDias = document.getElementById("reservar3Clima").value;
var precioDosDias = document.getElementById("reservar3Precio").value;
dataLayer.push({'event': 'climaMañana', 'eventLabelMañana': climaMañana, 'eventValueMañana': precioMañana});
dataLayer.push({'event': 'climaPasadoMañana', 'eventLabelPasadoMañana': climaPasadoMañana, 'eventValuePasadoMañana': precioPasadoMañana});
dataLayer.push({'event': 'climaDosDias', 'eventLabelDosDias': climaDosDias, 'eventValueDosDias': precioDosDias});
});
})(jQuery);
</script>
It works really good 90% of the time, but if the API spends more time than usual to send the response, Google Tag Manager is sending those events anyway with blank values for the variables, which is not optimal for keeping data quality in Google Analytics.
Any suggestion for making Google Tag Manager to wait until all variables are populated?

Auto-refresh Javascript For RSS Using Google Feed API

I apologize if the title is trash. What I'd like to do is rather simple in concept... but I'm having a bit of trouble.
I would like to automatically refresh an RSS feed that is displayed using Google Feed API. I haven't worked with the Google Feed API before, but it seemed like a quick option for getting this rolled out. Technically, it only needs to be the content part that is reloaded.
The purpose: This is displaying the results of a poll, refreshing them every 3 seconds (it will be displayed in a presentation.) The actual result is in the 'content', whereas the item being voted on is the 'title'.
The unstyled basics of the code:
<script type="text/javascript">
var feedcontainer=document.getElementById("feeddiv");
var feedurl="http://theurl.com";
var feedlimit=100;
var rssoutput="<b>Latest Results:</b><br /><ul>";
function rssfeedsetup(){
var feedpointer=new google.feeds.Feed(feedurl) //Google Feed API method
feedpointer.setNumEntries(feedlimit) //Google Feed API method
feedpointer.load(displayfeed) //Google Feed API method
}
function displayfeed(result){
if (!result.error){
var thefeeds=result.feed.entries
for (var i=0; i<thefeeds.length; i++)
rssoutput+="<li>" + thefeeds[i].title + "<br />" + thefeeds[i].content + "</li>"
rssoutput+="</ul>"
feedcontainer.innerHTML=rssoutput
}
else
alert("Error fetching feeds!")
}
window.onload=function(){
rssfeedsetup()
}
</script>
I'm not sure how to go about making the results refresh every 3 seconds. I've tried a few things, like "How to autorefresh XML in Javascript" but wound up printing the results multiple times on the page.
Major bonus points for anyone that can point me towards turning it into an auto refreshing bar graph. That will be my next search or question on here.
I think you should call rssfeedsetup() in a setInterval function. Something like
window.onload = function() {
var delay = 3000;
rssfeedsetup();
setInterval(rssfeedsetup, delay);
}

Google custom search for images only

Since Google image search API is deprecated, one should use Google custom search API for this.
I've made a small example using it. My problem is I want to return google image search results only. Whereby this shows web results, and the user may switch to the image result. How can I show only the image results by default?
<div id="cse" style="width: 100%;">Loading</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'hu'});
google.setOnLoadCallback(function() {
var customSearchOptions = {
enableImageSearch: true,
imageSearchOptions: {
layout: google.search.ImageSearch.LAYOUT_CLASSIC
}
};
var options = new google.search.DrawOptions();
options.setAutoComplete(true);
var customSearchControl = new google.search.CustomSearchControl('XXX', customSearchOptions);
customSearchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
customSearchControl.setAutoCompletionId('XXX');
customSearchControl.draw('cse', options);
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css" type="text/css" />
The API documentation is quite poor, it only describes how to add additional results.
Google images search is now supported in the Custom Search Engine API. See the API parameters section of this page. I'm using the API with python and for my application I just specify the parameter in the API call.
searchType = "image"
See this post on the cse blog.
EDIT: As Marc points out in his comment below, you need to click "Enable image search" in your CSE console.
Per the Google Custom Search Element Control API - documentation web site, this is possible.
https://developers.google.com/custom-search/docs/element
This is the fragment used for searching by image by default:
'defaultToImageSearch'
So I believe the full syntax for using this would be:
<script>
.
// Google custom search code, ids go here...
.
</script>
<gcse:search></gcse:search>
**<gcse:searchresults enableImageSearch="true" defaultToImageSearch="true">**
For those going through the WebExtensions tutorial, here's the updated code I used in popup.js to make it work with the new CSE functionality:
/**
* #param {string} searchTerm - Search term for Google Image search.
* #param {function(string,number,number)} callback - Called when an image has
* been found. The callback gets the URL, width and height of the image.
* #param {function(string)} errorCallback - Called when the image is not found.
* The callback gets a string that describes the failure reason.
*/
function getImageUrl(searchTerm, callback, errorCallback) {
// Google image search - 100 searches per day.
// https://developers.google.com/image-search/
// var searchUrl = 'https://ajax.googleapis.com/ajax/services/search/images' +
// '?v=1.0&q=' + encodeURIComponent(searchTerm);
var searchUrl = 'https://www.googleapis.com/customsearch/v1' +
'?key=' + key + '&cx=' + cx + '&searchType=image&q=' + encodeURIComponent(searchTerm);
var x = new XMLHttpRequest();
x.open('GET', searchUrl);
// The Google image search API responds with JSON, so let Chrome parse it.
x.responseType = 'json';
x.onload = function() {
// Parse and process the response from Google Image Search.
var response = x.response;
if (!response || !response.items || response.items.length === 0) {
errorCallback('No response from Google Image search!');
return;
}
var firstResult = response.items[0];
// Take the thumbnail instead of the full image to get an approximately
// consistent image size.
var imageUrl = firstResult.image.thumbnailLink;
var width = parseInt(firstResult.image.thumbnailWidth);
var height = parseInt(firstResult.image.thumbnailHeight);
console.assert(
typeof imageUrl == 'string' && !isNaN(width) && !isNaN(height),
'Unexpected respose from the Google Image Search API!');
callback(imageUrl, width, height);
};
x.onerror = function() {
errorCallback('Network error.');
};
x.send();
}
Mainly it's changing the search URL (which should have searchType=image as mentioned) and the response structural references in getImageUrl, and setting up the CSE engine. Make sure your CSE has Image search turned on, and under Sites to search make sure to select Search the entire web but emphasize included sites from the options list.
I'm not 100% certain on this, but I don't think the API supports what you're trying to do. This is not at all surprising, as Google's search API's are infamous for being lacking in even basic functionality (such as the standard search API's limit of 20 results, etc). I think the fact that I'm the first person to answer this in the 3 days it's been active is another indication that this is probably just not supported (or, if it is, Google never bothered to tell anyone).
I know you're not going to like this, but I think your best option is to scrape the images out of the returned result set yourself. That's typically what people have to resort to when dealing with Google results data. Fortunately, their frontend code is remarkably consistent, so a few well-tuned regex matches and/or splits should do the trick for ya.
And yes, it's total BS that Google has provided such lousy support for this API. =)
Try adding this line:
customSearchOptions['disableWebSearch'] = true;
I tried to get a more authoritative answer in the official Google AJAX APIs group,
and it seems the answer is NO(!). Google custom search API currently does not support image search only. You can use the deprecated Google image search API instead.
check this
Try this one
customSearchOptions['searchType'] = "image"
customSearchOptions['enableImageSearch'] = true
customSearchOptions['disableWebSearch'] = true;

Custom Google Maps location hotlink

I have a custom map using the Google Maps API to navigate it, and I was looking into getting an address for hot-linking to the current location on the map (like the Maps link such as the following; http://maps.google.com/?ie=UTF8&ll=37.0625,-95.677068&spn=64.880423,135.263672&t=h&z=4 )
I'm not quite sure what the feature is called or how to go about this as I've yet to find anything relevant in the API documentation, does anyone know if this is doable with custom maps, and alternatively how to go about this/pointers on what I should be reading up on?
I've never seen it in the documentation and don't think it's possible. Been looking for it my self without luck.
You probably need to look on the url's query params and navigate to it with javascript.
Do this onload (let's presume that the var map is you google maps object):
var queryArray = window.location.search.substring(1).split('&'),
query = {},
parseQueryByKey = (function () {
var subQuery = '',
i = 0;
for (i = 0; i < queryArray.length; i += 1) {
if (queryArray[i] && queryArray[i].indexOf('=') !== -1) {
subQuery = queryArray[i].split('=');
query[subQuery[0]] = subQuery[1];
}
}
}());
// presumed url http://localhost/?lat=58.1323&lng=18.1231
if (window.location.search && 'lat' in query && 'lng' in query) {
map.setCenter(new google.maps.LatLng(parseFloat(query['lat']), parseFloat(query['lng'])))
}
Hope it helps.
..fredrik

Google Ajax search API

I'm wondering, is it possible to receive google results over their own ajax API in a way like, 100 results per page?
Without a visible search field, I'd like to get the results in the background to create a progression for some search phrases.
My basic question is, what are the restrictions of the google search api ?
--update--
is it possible to change language for a search with google api ? From the start on, it
just delivers from .com in english
Kind Regards
--Andy
The largest number of results you can get is 64, 8 per page of the searcher.
It is possible to combine all of these into one page, but it involves the searcher making 8 calls to the Google Ajax Search API.
Further, you will need to create your own function to render the results:
var s;
var page = 1;
google.load('search', '1', {'nocss' : true});
google.load('jquery', '1.4.2'); // optional
google.setOnLoadCallback(function() {
// T&C's state you should display branding, create a <div id="branding"></div>
google.search.Search.getBranding(document.getElementById('branding'));
s = new google.search.WebSearch();
s.setResultSetSize(google.search.Search.LARGE_RESULTSET);
s.setSearchCompleteCallback(this, searchComplete, null);
s.setNoHtmlGeneration();
});
function searchComplete() {
if(s.results && s.results.length > 0) {
var results = s.results;
for(var i = 0; i < results.length; i++) {
var result = results[i];
// render the results
}
if(page < 8) {
s.gotoPage(page);
page++;
}
}
}
For information about how to render your results see: http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GwebResult
To change the language, add the hl argument when including the script in web pages:
<script src="http://www.google.com/jsapi?hl=en" type="text/javascript"></script>
http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GSearchControl
This has information about the main controller class used. It appears that the following answers your question about result size:
.setResultSetSize(switchTo)
This method is called to select the
number of results returned by each of
the searchers. Note, this is not a
scalar. It is an enumeration that
indicates either a small number of
results, or a large number of results.
In the future, this method may be
enhanced to support medium and extra
large result sets. From the sample
applications, you have probably seen
the more/less twiddle control at the
top of the search control. This method
is used by that twiddle control.
switchTo - supplies en enumeration
which indicates the desired number of
search results to return for each
configured searcher. Valid values
include:
google.search.Search.LARGE_RESULTSET -
request a large number of results
(typically 8 results)
google.search.Search.SMALL_RESULTSET -
request a small number of results
(typically 4 results)
google.search.Search.FILTERED_CSE_RESULTSET
- request up to 10 results. This will only work for Web Search queries
scoped to a Filter Custom Search
engine, otherwise an error will be
returned. returns - n/a
Here is my code:
<script src="https://www.google.com/jsapi?key=GOOGLE_SEARCH_KEY" type="text/javascript"></script>
<script language="Javascript" type="text/javascript">
//<![CDATA[
google.load("search", "1");
function OnLoad() {
// Create a search control
var searchControl = new google.search.SearchControl();
var options = new google.search.SearcherOptions();
options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
searchControl.addSearcher(new google.search.WebSearch(),options);
searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
// Tell the searcher to draw itself and tell it where to attach
searchControl.draw(document.getElementById("searchcontrol"));
}
google.setOnLoadCallback(OnLoad);
//]]>
</script>
<style>.gsc-control { width: 80%; } input.gsc-search-button { border: 1px solid black; }</style>

Categories

Resources