How to parse the RSS using google api or any other techinques - google-api

I want to parse the below mentioned RSS in order to get the title, description, image and date. Currently i'm able to get the all other details except image. Im using google api feed to parse the rss. Please can anyone me in this context.
RSS:https://news.google.com/news/feeds?cf=all&ned=in&hl=en&q=cricket&output=rss
// Google Feed API: https://developers.google.com/feed/
// Inspiration: http://designshack.net/articles/javascript/build-an-automated-rss-feed-list-with-jquery/
function parseFeed(url, container) {
$.ajax({
url: document.location.protocol + '//ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=5&callback=?&q=' + encodeURIComponent(url),
dataType: 'json',
success: function (data) {
// log object data in console
console.log(data.responseData.feed);
// append feed link and title in container
$(container).append('<span class="iconicstroke-rss-alt"></span>');
$(container).append('<h1 class="feed">' + data.responseData.feed.title + '</h1>');
// for each entry... *
$.each(data.responseData.feed.entries, function (key, value) {
// * create new date object and pass in entry date
var date = new Date(value.publishedDate);
// var thumbnail = entry.mediaGroups[0].contents[0].url;
// * create months array
var months = new Array(12);
months[0] = 'January';
months[1] = 'February';
months[2] = 'March';
months[3] = 'April';
months[4] = 'May';
months[5] = 'June';
months[6] = 'July';
months[7] = 'August';
months[8] = 'September';
months[9] = 'October';
months[10] = 'November';
months[11] = 'December';
// * parse month, day and year
var month = date.getMonth();
var day = date.getDate();
var year = date.getFullYear();
// * assign entry variables
var title = '<h3 class="title">' + value.title + '</h3>';
var time = '<p class="time">' + months[month] + ' ' + day + ', ' + year + '</p>';
var snippet = '<p class="snippet">' + value.contentSnippet + '</p>';
var img = '<p class="snippet">' + value.thumbnail + '</p>';
var entry = '<div class="entry">' + title + time + snippet + '</div>';
// * append entire entry in container
$(container).append(entry);
});
},
// if there's an error... *
error: function (errorThrown) {
// * log error message in console
console.log(errorThrown);
// * show error message
alert('Houston, we have a problem.');
}
});
}
$(document).ready(function () {
parseFeed('https://news.google.com/news/feeds?pz=1&cf=all&ned=en&hl=in&q=aishwarya%20rai&output=rss', '#csstricks');
});

Just add this to your script
var content = document.createElement("content");
content.innerHTML = value.content;
var images = "";
$(content).find('img').each(function() {
images += this.outerHTML;
});
var img = '<p class="snippet">' + images + '</p>';
Same answer as here: https://stackoverflow.com/a/26369373/989257
Codepen example: http://codepen.io/janih/pen/JdPMZX

Related

Google Map doesn't appear on load

I am developing an app where I use 2 API's a.k.a Instagram API and Google Map API. Using AJAX, I get the first set of Images filtered by a tag name. In the 1st set we receive 20 images. Among the received images, the images that have the latitude and longitude info (geotagged images) are displayed on the map.
Now the first time when my page loads, I cannot see the map. But when I press the load more button to get the next set of images, the Map works fine showing my previous images too.
Here is the code for what happens on page load:
$( window ).load(function() {
$.ajax({
type: "GET",
url: "https://api.instagram.com/v1/tags/nyc/media/recent?client_id=02e****",
dataType:'JSONP',
success: function(result) {
onAction(result, 2, tag);
instaMap(result, 2, from);
}
});
});
These are the functions being called:
/**
* [initialize description]
* Initialize the map with markers showing all photos that are geotagged.
*/
var initialize = function(markers) {
var bounds = new google.maps.LatLngBounds(),
mapOptions = {
scrollwheel: false,
mapTypeId: 'roadmap',
center: new google.maps.LatLng(22.50, 6.50),
minZoom: 2
},
gmarkers = [],
map,
positions,
markCluster;
markers = remDuplicate(markers);
// Info Window Content
var infoWindowContent = [];
for (var j = 0; j < markers.length; j++ ) {
var content = [
'<div class="info_content">' +
'<h3>' + markers[j][2] + '</h3>' +
'<a href="' + markers[j][3] + '" target="_blank">' +
'<img src="' + markers[j][4] + '" style="z-index:99999">' + '</a>' +
'</div>'
];
infoWindowContent.push(content);
}
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
// Display multiple markers on a map
var oms = new OverlappingMarkerSpiderfier(map);
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
positions = new google.maps.LatLng(markers[i][0], markers[i][1]);
marker = new google.maps.Marker({
position: positions,
map: map,
animation:google.maps.Animation.BOUNCE,
title: markers[i][2]
});
oms.addMarker(marker);
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.close();
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
};
})(marker, i));
gmarkers.push(marker);
}
google.maps.event.addListener(map, 'click', function() {
infoWindow.setMap(null);
});
markCluster = new MarkerClusterer(map, gmarkers);
// Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
map.setZoom(2);
google.maps.event.removeListener(boundsListener);
});
};
/**
* [onAction]
* OnAction() function helps in loading non-geotagged pics.
*
* #param {[type]} result [Result retruned from the Instagram API in json format]
* #param {[type]} likey [hearts the user has entered as per which the posts will be filtered]
*/
var onAction = function (result, likey, tag) {
$('.load-pics').remove();
if (result.pagination.next_url) {
paginate = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations === null) {
output = '<li class="img-wrap">' + '<div class="main-img">' +
'<a href="' + link + '" target="_blank">' +
'<img src="' + imgUrl + '" ><span class="hover-lay"></span></a>' +'<p>' +
'<span class="heart"></span><span class="likes-no">' + liked + '</span>' +
'<span class="comment-box"></span><span class="comment-no">' +
val.comments.count + '</span> ' + '</p>' + '</div>' +
'<div class="img-bottom-part">'+ '' + '<div class="headin-hastag">' +
'by ' + '<h2>Sebastien Dekoninck</h2>#hello <span>#kanye</span> #helloagain #tagsgohere</div>'
+'</div></li>';
$('#instafeed').append(output);
}
}
});
}
});
if ($('#instafeed').children().length === 0) {
alert('There are no pics with ' + likey + ' likes or #' + tag + ' was not found.');
} else {
// $('.not-geo').remove();
// $('#instafeed').before('<button class="not-geo">Click To See Images That Are Not Geotagged <img src="assets/imgs/down.png" ></button>');
}
$('#instafeed').append('<div class="load-pics"><button id="show-more">Show more <span></span></button> </div>');
};
/**
* [instaMap]
* instaMap() will be the function which will deal with all map based functionalities.
*/
var instaMap = function(result, likey, from) {
$('.load-mark').remove();
if (result.pagination.next_url) {
pagiMap = removeURLParameter(result.pagination.next_url, 'count');
}
$.each(result, function(key, value) {
if (key === 'data') {
$.each(value, function(index, val) {
liked = val.likes.count;
link = val.link;
imgUrl = val.images.low_resolution.url;
locations = val.location;
if (liked >= likey) {
if (locations && locations.latitude !== null) {
tempArr = [
locations.latitude,
locations.longitude,
val.user.username,
val.link,
val.images.low_resolution.url
];
mark.push(tempArr);
}
}
});
}
});
if (mark.length) {
initialize(mark);
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
} else {
alert('No geotagged pics found in the retrieved set. Click see more');
$('.map-parent-wrapper').append('<div class="load-mark"><button id="show-mark">See More </button></div>');
}
};
I have created a See More button to retrieve the next set of images and load those on the Map. When clicking see more, everything seems to work fine. Not sure why it's happening so. Console.log does not show any error. Also, all the values I feed does flow appropriately. I even tried clearing cache. Not sure, why it's happening.
If instaMap is the function which is going to handle all your map based functionality, it has to be the one that loads map in your $( window ).load function ();
Otherwise, if you want Google maps to load on initial window load you need to put below in there:
google.maps.event.addDomListener(window, 'load', initialize);

Parsing JSON with AJAX - show random item of the JSON and update after an amount of time

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

jquery AJAX pulls data from XML - last 4 items only

I am working on a sort of aggregator/tweet wall. At the mo it only uses data from an XML file (of our latest news). I made a bit of a mistake in the logic, though.
At present it only pulls items from the last 30 days. Live demo takes a few secs to load (using last 240 days for extra content to work with). However, I need it to:
Pull the last 4 items in chrono order.
Shuffle that array so they are
random ordered (but will all be "fresh" news).
Output that array.
jQuery(function () {
$.ajax({
url: 'http://www.sagittarius-digital.com/news.rss',
dataType: 'xml',
complete: function() {
/*Init masonry.js*/
var container = document.querySelector('#container');
var msnry = new Masonry( container, {
// options
gutter: 20,
columnWidth: 320,
itemSelector: '.item'
});
}
}).done(function (xml) {
var items = [];
$(xml).find('item').each(function () {
var $item = $(this);
var date = new Date($item.find('pubDate').text());
var date_30 = new Date().getTime() - (1000*60*60*24*240); /* last figure = number of days to sort back from */
var yyyymmdd = date.getFullYear() + '' + (date.getMonth() + 1) + '' + date.getDate();
if ( date_30 < date.getTime() ) { // newer than 30 days
var array = '<div class="item"><h2>News</h2>';
array += '<p>' + yyyymmdd + '</p>';
array += '<a href="' + $item.find('link').text() + '">';
array += '<h2>' + $item.find('title').text() + '</h2>';
array += '<p>' + $item.find('description').text() + '</p>';>
array += '<p>Category: ' + $item.find('category').text() + '</p>';
array += '</a>';
array += '</div>';
items.push(array);
}
});
$('div.item').after(items.join(' '));
}).fail(function () {
console.log('error', arguments)
});
});
Basically after that I need to add a second RSS feed with different info doing the same, a Twitter ajax call and facebook ajax call. So I will have 12 bits of data that are all the 4 "freshest", these will then shuffle into a random order and output, so there is a nice even mix.

titanium mobile:get row value from tableview on button click issue

Hello friends,
I am developing an app using Google Place API in Titanium Development and successfully got data and display in tableview and add button in each row but my issue is that I want to get name and address on button click in each row so please give me idea or any link to solve my issue.
Please take a look in my screenshot so on btnclick I want to get name and address.
Thanks in advance.
var categoryName;
var addressLabel;
var row;
var tableData=[];
PlacesListCells = function createRow()
{
//var tableData=[];
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
categoryName = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
// Create a row and set its height to auto
row = Titanium.UI.createTableViewRow({height:'78'});
var placeImage = Titanium.UI.createImageView
({
image:'../iphone/appicon.png',
width:70,
height:50,
top:12,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:80,
top:5,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:12}
});
// Create the label to hold the tweet message
addressLabel = Titanium.UI.createLabel({
left:80,
top:25,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:14}
});
var arrowImage = Ti.UI.createImageView
({
image:'../iphone/appicon.png',
width:20,
height:20,
left:280,
top:30
});
var favoriteButton = Ti.UI.createButton
({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png'
});
nameLabel.text = categoryName;
getDetailsData(addressLabel,row,i);
row.add(placeImage);
row.add(nameLabel);
row.add(addressLabel);
row.add(favoriteButton);
//row.add(arrowImage);
tableData[i] = row;
//set page title for each row
row.pageTitle = nameLabel.text;
favoriteButton.row = i;
favoriteButton.addEventListener('click', function(e)
{
Ti.API.log('favoriteButton clicked on row ' + e.source.row +' at ' + new Date().getSeconds());
alert('favoriteButton clicked on row ' + e.source.row);
var index = e.source.row;
var name = tableData[index];
alert('name'+name);
});
}
tableView.setData(tableData);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
return tableData;
};
Once you have your index, you should be able to reference your original data source by that.
var favoriteButton = Ti.UI.createButton({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png',
name:categoryName,
address:address;//address mention here
});
row.add(favoriteButton);
favoriteButton.addEventListener('click', function(e)
{
var index = e.source.row;
var name = e.source.name;
var address = e.source.address;
alert('name'+name);
});
}
I think this might help you a lot.

titanium mobile:onload function called issue in json parsing

Hello friends,
I am developing an app in Titanium Studio sdk 1.8.1 using Google Place API to display category atm list & address in tableview so I use json parsing using this link but loader.onload function of getData method is not called immediately after send function of getData method in json parsing so its called after getDetailsData() function and also can't display address in tableview so please give me idea how to solve it.
Thanks in advance.
var lat ,lon ,radius , name , sensor , key , reference, address;
lat = '-33.8670522';//'23.042067';
lon = '151.1957362';//'72.530835';//
radius = '500';
name = title;
sensor = 'false';
key = 'AIzaSyDALrXHC4uMtfSrpCg6NHxqPhsLccLYPZE';
var rowData = [];
// getCategoryData using Google Place API
function getData()
{
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
var name = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
getDetailsData();
// Create a row and set its height to auto
var row = Titanium.UI.createTableViewRow({height:'auto'});
// Create the view that will contain the text and avatar
var post_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
// Create the label to hold the tweet message
var addressLabel = Titanium.UI.createLabel({
text:'Address',
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
nameLabel.text = name;
//addressLabel.text = placeAddress;
post_view.add(nameLabel);
post_view.add(addressLabel);
// Add the post view to the row
row.add(post_view);
// Give each row a class name
//row.className = "item"+i;
// Add row to the rowData array
rowData[i] = row;
//rowData.push(row);
}
//tableView.setData(rowData);
// Create the table view and set its data source to "rowData" array
var tableView = Titanium.UI.createTableView({data:rowData});
//Add the table view to the window
showWin.add(tableView);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
}
function getDetailsData ()
{
var loader1 = Titanium.Network.createHTTPClient();
Ti.API.log('getDetailsData');
var url = "https://maps.googleapis.com/maps/api/place/details/json?";
url = url + "reference=" + reference;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader1.open("GET",url);
// Runs the function when the data is ready for us to process
loader1.onload = function()
{
var detailsObj = JSON.parse(this.responseText);
Ti.API.log(detailsObj);
address = detailsObj.result.formatted_address;
Ti.API.log('Address:'+address);
phoneno = detailsObj.result.formatted_phone_number;
Ti.API.log('Phone No:'+phoneno);
};
//-- Network error
loader1.onerror = function(event)
{
Ti.API.info('Network error: ' + JSON.stringify(event));
};
// Send the HTTP request
loader1.send();
return address;
}
getData();
Dont't use the return in the second http request.
Pass the label object in the function like:
getDetailsData(addressLabel);
and set the text inside loader1.onload like this:
address = detailsObj.result.formatted_address;
addressLabel.text = address;

Resources