I have code to calculate distance place to another place using google distance matrix API, but for free its limited just 100 elements per query. So I make code for solve the problem using looping code such as for elements , My code is PHP, javascript , and I parse latitude and longitude data from MySql. Anyone know some error of my code below ? because It don't appear anything if I click calculate button. Actualy I have modifie the code from this URL https://google-developers.appspot.com/maps/documentation/javascript/examples/distance-matrix , And this is my Code :
function hitung (){
service = new google.maps.DistanceMatrixService();
for (m = 0 ; m < l-80 ; m++ ){
asal = originarray[m];
for (n = 0 ; n < l-80 ; n++ ){
tujuan = destarray [n];
calculateDistances();
}
}
}
function calculateDistances() {
//var s = 0;
//for (m = 0 ; m < l-80 ; m++ ){
// asal = originarray[m];
//for (n = 0 ; n < l-80 ; n++ ){
//servicearray[s] = new google.maps.DistanceMatrixService();
//tujuan = destarray [n];
service.getDistanceMatrix(
{
//origins: [origin1, origin2],
// destinations: [destinationA, destinationB],
origins: asal,
destinations: tujuan,
//origins: originarray,
//destinations: destarray,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, callback);
// s++;
//}
// }
}
function callback(response, status) {
if (status != google.maps.DistanceMatrixStatus.OK) {
alert('Error was: ' + status);
} else {
var origins = response.originAddresses;
var destinations = response.destinationAddresses;
var outputDiv = document.getElementById('outputDiv');
//outputDiv.innerHTML = '';
// deleteOverlays();
for (var i = 0; i < origins.length; i++) {
var results = response.rows[i].elements;
// addMarker(origins[i], false);
for (var j = 0; j < results.length; j++) {
// addMarker(destinations[j], true);
outputDiv.innerHTML += origins[i] + ' to ' + destinations[j]
+ ': ' + results[j].distance.text + ' in '
+ results[j].duration.text + '<br>';
}
}
}
}
function addMarker(location, isDestination) {
var icon;
if (isDestination) {
icon = destinationIcon;
} else {
icon = originIcon;
}
geocoder.geocode({'address': location}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
map: peta,
position: results[0].geometry.location,
icon: icon
});
markersArray.push(marker);
} else {
alert('Geocode was not successful for the following reason: '
+ status);
}
});
}
function deleteOverlays() {
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
}
</script>
Check if you're receiving a response from Google by logging the response...
function callback(response, status) {
console.log(response);
}
Related
My blog is 12 years old, I have more than 5000 posts. I am using a widget that shows random posts from a specific label. I set it to show 2 posts in the sidebar, and I noticed that these posts are always 'neighbors', which means they are always from the same month in the past. For example, it's always 2 posts from May 2014, or June 2018. It's never something like: 1 post from May 2014 and the other from June 2018. Do you have any idea what the problem is?
Here is the part of the code which (I believe) contains the mistake:
rand=Math.floor((Math.random()*_vRiO.total_entry)+1);
if(rand+bcd140526_post_count>_vRiO.total_entry){
rand=_vRiO.total_entry-bcd140526_post_count+1;
}
if(rand<1){
rand=1;
}
var _vXsM=HOST+_s7IgU[159];
if(bcd140526_index_label){
_vXsM+=_s7IgU[160]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[161]+bcd140526_post_count+_s7IgU[162]+rand+_s7IgU[163];
_fIoT(_vXsM);
}else{
_fYbP(json);
}
}
var _vXsM=HOST+_s7IgU[164];
if(bcd140526_index_label){
_vXsM+=_s7IgU[165]+encodeURIComponent(bcd140526_index_label);
}
_vXsM+=_s7IgU[166];
if(bcd140526_sort_by==_s7IgU[167]){
_vXsM+=_s7IgU[168];
}else{
_vXsM+=_s7IgU[169]+bcd140526_post_count;
}
_vXsM+=_s7IgU[170];_fIoT(_vXsM);
I can't paste the whole code, the website doesn't let me. But you can get it here: https://sneeit.com/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget/
My settings:
Post Count - 2
Post Order - Random
Specific Label - Summer
Show Thumbnail - Checked
Thumbnail Size - 200
Show Label - No
Show Comment Numbers - No
Show Date - No
Show Author Name - No
Show Readmore - No
Show Snippet - No
Show Copyright - No
Design Style - List
I have painstakingly deobfuscated this extension to be able to check how you could modify it (which should be much easier for you if you still want to), and I see that getting "non-neighbor" random numbers is not what this system is designed to do. choosePost(json) chooses one post by number to be the starting post, and makeWidget (which, bizarrely, uses string concatenation and document.write to generate the widget) just uses the first post_count posts after the chosen post, so your objective is not (easily) doable.
var show_thumbnail = true;
var show_label = false;
var show_comment_numbers = false;
var show_date = false;
var show_author_name = false;
var show_readmore = false;
var show_snippet = false;
var hide_copyright = true;
var snippet_length = 150;
var post_count = 3;
var thumbnail_size = 140; // v1.5, only effect with list style
var sort_by = 'random'; // latest or random
var index_label = 'summer';
var design_style = 'list'; // list or column
var date_format = 'mm/dd/yyyy';
var lang_readmore = 'Readmore';
var HOST = '';
function sourceJSfile(url) {
document.write('<script type="text/javascript" src="' + url + '"<\/script>');
}
function generateDate(pub_date, format) {
pub_date = pub_date.split('-');
date = new Date(pub_date[0], pub_date[1] - 1, pub_date[2].substring(0, 2));
dd = date.getDate();
mm = date.getMonth() + 1;
yyyy = date.getFullYear();
format = format.replace('dd', dd);
format = format.replace('mm', mm);
format = format.replace('yyyy', yyyy);
return format;
}
function cleanContent(content) {
var tgt = '';
var imgtag = '<img ';
var srctag = 'src="';
var quote = '\"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
index2 = content.indexOf(quote, index1 + srctag.length);
tgt = content.substring(index1 + srctag.length, index2);
}
if (tgt == '') {
imgtag = 'data-thumbnail-src="';
srctag = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0 + imgtag.length);
if (index0 != -1) {
tgt = content.substring(index0 + imgtag.length, index1);
}
}
}
if (tgt == '') {
imgtag = '<iframe ';
srctag = 'src="';
quote = '"';
index0 = content.indexOf(imgtag);
if (index0 != -1) {
index1 = content.indexOf(srctag, index0);
if (index0 != -1) {
index2 = content.indexOf(quote, index1 + srctag.length);
if (index0 != -1) {
tgt = content.substring(index1 + srctag.length, index2);
tgt = tgt.replace("http://www.youtube.com/watch?v=", '');
tgt = tgt.replace("http://www.youtube.com/embed/", '');
tgt = tgt.replace('?rel=0', '');
tgt = 'http://img.youtube.com/vi/' + tgt + '/mqdefault.jpg';
}
}
}
}
return tgt;
}
function jsonProcessor(json) {
var data = new Object();
var regex = /<\S[^>]*>/g;
data.id = json.feed.id.$t;
key = 'blog-';
index = data.id.indexOf(key);
data.id = data.id.substring(index + key.length);
data.id = data.id.replace('.comments', '');
data.cate = new Array();
if ('category' in json.feed) {
for (let i = 0; i < json.feed.category.length; i++) {
data.cate[i] = json.feed.category[i].term;
}
}
data.title = '';
if ('title' in json.feed) {
data.title = json.feed.title.$t;
}
data.subtitle = '';
if ('subtitle' in json.feed) {
data.subtitle = json.feed.subtitle.$t;
}
data.admin = new Object();
data.admin.name = 'Anonymous';
data.admin.uri = '';
data.admin.avatar = 'http://img1.blogblog.com/img/anon36.png';
if ('name' in json.feed.author[0]) {
data.admin.name = json.feed.author[0].name.$t;
}
if ('uri' in json.feed.author[0]) {
data.admin.uri = json.feed.author[0].uri.$t;
}
if ('gd$image' in json.feed.author[0]) {
if (json.feed.author[0].gd$image.src != 'http://img1.blogblog.com/img/blank.gif') {
data.admin.avatar = json.feed.author[0].gd$image.src;
}
}
data.total_entry = Number(json.feed.openSearch$totalResults.$t);
data.start_index = Number(json.feed.openSearch$startIndex.$t);
data.item_per_page = Number(json.feed.openSearch$itemsPerPage.$t);
data.entry_number = 0;
if ('entry' in json.feed) {
data.entry_number = json.feed.entry.length;
}
data.entry = new Array();
for (let i = 0; i < data.entry_number; i++) {
data.entry[i] = new Object();
temp = new Object();
entry = json.feed.entry[i];
temp.id = entry.id.$t;
key = 'post-';
index = temp.id.indexOf(key);
temp.id = temp.id.substring(index + key.length);
temp.published = '';
if ('published' in entry) {
temp.published = entry.published.$t;
}
temp.cate = new Array();
if ('category' in entry) {
for (j = 0; j < entry.category.length; j++) {
temp.cate[j] = entry.category[j].term;
}
}
temp.title = '';
if ('title' in entry) {
temp.title = entry.title.$t;
}
temp.content = '';
if ('content' in entry) {
temp.content = entry.content.$t;
}
temp.summary = '';
if ('summary' in entry) {
temp.summary = entry.summary.$t;
}
if (temp.summary == '') {
temp.summary = temp.content.replace(regex, '');
}
if (temp.content == '') {
temp.content = temp.summary;
}
temp.link = '';
temp.reply_label = 'comments';
if ('link' in entry) {
for (j = 0; j < entry.link.length; j++) {
if (entry.link[j].rel == 'alternate') {
temp.link = entry.link[j].href;
}
if (entry.link[j].rel == 'replies') {
temp.reply_label = entry.link[j].title;
}
}
}
temp.author = new Object();
temp.author.name = 'Anonymous';
temp.author.uri = '';
temp.author.avatar = 'http://img1.blogblog.com/img/anon36.png';
a0 = entry.author[0];
if ('name' in a0) {
temp.author.name = a0.name.$t;
}
if ('uri' in a0) {
temp.author.uri = a0.uri.$t;
}
if ('gd$image' in a0) {
if (a0.gd$image.src != 'http://img1.blogblog.com/blank.gif') {
temp.author.avatar = a0.gd$image.src;
}
}
temp.thumbnail = '';
if ('media$thumbnail' in entry) {
temp.thumbnail = entry.media$thumbnail.url;
}
temp.reply_number = 0;
if ('thr$total' in entry) {
temp.reply_number = Number(entry.thr$total.$t);
}
temp.reply_label = temp.reply_label.replace(temp.reply_number + ' ', '');
temp.reply_to = '';
temp.reply_json = '';
temp.reply_title = '';
if ('thr$in-reply-to' in entry) {
temp.reply_to = entry['thr$in-reply-to'].href;
temp.reply_json = entry['thr$in-reply-to'].source;
temp.reply_json = temp.reply_json.replace('/default/', '/summary/');
temp.reply_json = temp.reply_json + '?alt=json-in-script';
}
temp.pid = '';
if ('gd$extendedProperty' in entry) {
for (j = 0; j < entry.gd$extendedProperty.length; j++) {
if (entry.gd$extendedProperty[j].name == 'blogger.itemClass') {
temp.pid = entry.gd$extendedProperty[j].value;
}
}
}
temp.pid = temp.pid.replace('pid-', '');
data.entry[i] = temp;
}
return data;
}
if (typeof(jquery_included) == 'undefined') {
jquery_included = false;
}
function jqueryLoader() {
if (typeof(jQuery) == 'undefined') {
if (!jquery_included) {
jquery_included = true;
var scriptEl = document.createElement('script');
scriptEl.setAttribute('src', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js');
scriptEl.setAttribute('type', 'text/javascript');
document.getElementsByTagName('head')[0].appendChild(scriptEl);
}
setTimeout(jqueryLoader, 50);
} else {
if (!($('link[href*="font-awesome.css"]').length)) {
linkEl = document.createElement('link');
linkEl.setAttribute('href', 'http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css');
linkEl.setAttribute('rel', 'stylesheet');
document.head.appendChild(linkEl);
}
}
}
jqueryLoader();
function makeWidget(json) {
var div = '<div style="clear:both!important;float:none;!important;line-height:0!important"></div>';
var jsonOut = jsonProcessor(json);
var docAppend = '';
if (jsonOut.total_entry) {
docAppend += ('<div class="post_feed ' + design_style + ' ' + ((show_thumbnail) ? 'thumb' : 'no-thumb') + '"><ul>');
for (let i = 0; i < jsonOut.total_entry && i < post_count; i++) {
p = jsonOut.entry[i];
docAppend += ('<li class="item item-' + i + '">');
if (!p.thumbnail) {
p.thumbnail = cleanContent(p.content);
}
if (show_thumbnail && p.thumbnail) {
var tgt = p.thumbnail;
if (tgt.indexOf('/s72-c/') != -1){
if (design_style === 'column')
tgt = tgt.replace('/s72-c/', '/s1600/');
else
tgt = tgt.replace('/s72-c/', '/s' + thumbnail_size + '-c/');
} else if (tgt.indexOf('youtube.com') != -1 && tgt.indexOf('/default.') != -1) {
tgt = tgt.replace('/default.', '/mqdefault.');
}
p.thumbnail = tgt;
docAppend += ('<a class="thumbnail" style="width:' + thumbnail_size + 'px;height:' + thumbnail_size + 'px;" href="' + p.link + '"><img src="' + p.thumbnail + '"/></a>');
}
docAppend += '<div class="item-body">';
if (show_label && (typeof(p.cate[0]) != 'undefined')) {
docAppend += ('<a class="cate" href="' + HOST + '/search/label/' + p.cate[0] + '">' + p.cate[0] + '</a>');
}
docAppend += ('<h3 class="title">' + p.title + '</h3>');
if (show_author_name || show_comment_numbers || show_date) {
docAppend += '<div class="meta">';
if (show_author_name) {
docAppend += ('<span class="meta-item author-name"><i class="fa fa-user"></i> ' + p.author.name + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item comment-number"><i class="fa fa-comment"></i> ' + p.reply_number + '</span>');
}
if (show_comment_numbers) {
docAppend += ('<span class="meta-item date-time"><i class="fa fa-clock-o"></i> ' + generateDate(p.published, date_format) +'</span>');
}
docAppend += (div + '</div>' + div);
}
if (show_snippet) {
if (p.summary.length > snippet_length) {
p.summary = p.summary.substring(0, snippet_length) + '...';
}
if (show_readmore) {
p.summary += ' ' + lang_readmore + '';
}
docAppend += ('<p class="snippet">' + p.summary + '</p>');
}
docAppend += (div + '</div>' + div);
docAppend += ('</li>');
}
docAppend += ('</ul>');
if (!hide_copyright) {
docAppend += div;
docAppend += '<a target="_blank" class="copyright" href="http://www.sneeit.com/2014/05/blogger-random-recent-specific-label-posts-widget-all-in-one-post-feed-widget" style="font-size: 11px!important;text-align:right;visibility: visible;!important;text-indent:0!important;height:auto!important;width:100%!important;position:static!important;color:#999!important;display:block!important;opacity:1!important;">BloggerWidget</a>';
}
docAppend += ('</div>' + div);
} else {
docAppend += '<p><em>Have no posts</em><p>';
}
document.write(docAppend);
}
function choosePost(json) {
if (sort_by == 'random') {
var processedJSON = jsonProcessor(json);
rand = Math.floor((Math.random() * processedJSON.total_entry) + 1);
if (rand + post_count > processedJSON.total_entry) {
rand = processedJSON.total_entry - post_count + 1;
}
if (rand < 1) {
rand = 1;
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script&max-result=' + post_count + '&start-index=' + rand + '&callback=makeWidget';
sourceJSfile(request);
} else {
makeWidget(json);
}
}
var request = HOST + '/feeds/posts/default';
if (index_label) {
request += '/-/' + encodeURIComponent(index_label);
}
request += '?alt=json-in-script';
if (sort_by == 'random') {
request += '&max-results=0';
} else {
request += '&max-results=' + post_count;
}
request += '&callback=choosePost';
sourceJSfile(request);
The modifications will take some work, but the deobfuscated version should be much easier to use. I'd recommend removing jqueryLoader, and to get you started: the API requests are sourceJSfile('/feeds/post/default/-/summer?alt=json-in-script&max-results=1&callback=choosePost'). You'd probably be better off rewriting the thing from scratch than trying to bodge it on top of this code, I think.
PS: This code loads the entire jquery library so it can load some random stylesheet in jqueryLoad.
Please suggest me, how to remove division. i am wring bellow code for scraping but that is not working for remove division.
I have used javascript and jquery to remove the div but its not working on casperjs . SO I want the solution in casperjs to remove html element like div .
casper.then(function () {
this.wait(10000, function () {
var elems = [];
var outputlength = this.getElementsInfo('.context').length;
for (var i = 0; i < outputlength; i++)
{
var as = this.getElementsInfo('#context_' + i + ' .a').length;
var elems = [];
var isDelete = false;
for (var j = 0; j < as; j++)
{
var text = this.fetchText('#b_' + i + '_' + j);
x = text.split(" ");
if (elems.length == 0) {
elems.push(x[0]);
} else if (elems.indexOf(text) == -1) {
isDelete = true;
break;
}
}
if (casper.exists('#context_' + i + '.notAvailableCell'))
{
isDelete = true;
}
if (isDelete) {
this.wait(2000, function () {
this.evaluate(function () {
$('#context_' + i).remove();
});
});
}
}
this.wait(2000, function () {
this.capture("screenshot.png");
});
});
});
I have found the solution for remove division dynamically by using jquery with casperjs.
this.evaluate(function (d) {
$('#context_' + d).remove();
return d;
}, i);
Now it is working fine for me.
I'm trying to create an map with the leaflet-simple-csv-master (i'm a beginner). It's really nice and i'd like to show different icons with my types (for exemple 1 icon for schools, one for administrations,...). I succed to show my different icons when i have the map but when i click to the filter, my icons disappear. In fact it doesn't work because it do not recognize my variable when i use the filter and i can read that my img is no more logos/type1.png but logos/undefined.png.
This is my all code.
var basemap = new L.TileLayer(baseUrl, {maxZoom: 17, attribution: baseAttribution, subdomains: subdomains, opacity: opacity});
var center = new L.LatLng(0, 0);
var map = new L.Map('map', {center: center, zoom: 2, maxZoom: maxZoom, layers: [basemap]});
var popupOpts = {
autoPanPadding: new L.Point(5, 50),
autoPan: true
};
var points = L.geoCsv (null, {
firstLineTitles: true,
fieldSeparator: fieldSeparator,
onEachFeature: function (feature, layer) {
var popup = '<div class="popup-content"><table class="table table-striped table-condensed">';
for (var clave in feature.properties) {
var title = points.getPropertyTitle(clave).strip();
var attr = feature.properties[clave];
if (title == labelColumn) {
layer.bindLabel(feature.properties[clave], {className: 'map-label'});
}
if (attr.indexOf('http') === 0) {
attr = '<a target="_blank" href="' + attr + '">'+ attr + '</a>';
}
if (attr) {
popup += '<tr><th>'+title+'</th><td>'+ attr +'</td></tr>';
}
}
popup += "</table></popup-content>";
layer.bindPopup(popup, popupOpts);
},
pointToLayer: function (feature, latlng) {
var logo = feature.properties['type'];
return L.marker(latlng, {
icon:L.icon({
iconUrl: 'logos/'+logo+'.png',
shadowUrl: 'marker-shadow.png',
iconSize: [25,41],
shadowSize: [41, 41],
shadowAnchor: [13, 20]
})
});
},
filter: function(feature, layer) {
total += 1;
if (!filterString) {
hits += 1;
return true;
}
var hit = false;
var lowerFilterString = filterString.toLowerCase().strip();
$.each(feature.properties, function(k, v) {
var value = v.toLowerCase();
if (value.indexOf(lowerFilterString) !== -1) {
hit = true;
hits += 1;
return false;
}
});
return hit;
}
});
var hits = 0;
var total = 0;
var filterString;
var markers = new L.MarkerClusterGroup();
var dataCsv;
var addCsvMarkers = function() {
hits = 0;
total = 0;
filterString = document.getElementById('filter-string').value;
if (filterString) {
$("#clear").fadeIn();
} else {
$("#clear").fadeOut();
}
map.removeLayer(markers);
points.clearLayers();
markers = new L.MarkerClusterGroup(clusterOptions);
points.addData(dataCsv);
markers.addLayer(points);
map.addLayer(markers);
try {
var bounds = markers.getBounds();
if (bounds) {
map.fitBounds(bounds);
}
} catch(err) {
// pass
}
if (total > 0) {
$('#search-results').html("Showing " + hits + " of " + total);
}
return false;
};
var typeAheadSource = [];
function ArrayToSet(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
function populateTypeAhead(csv, delimiter) {
var lines = csv.split("\n");
for (var i = lines.length - 1; i >= 1; i--) {
var items = lines[i].split(delimiter);
for (var j = items.length - 1; j >= 0; j--) {
var item = items[j].strip();
item = item.replace(/"/g,'');
if (item.indexOf("http") !== 0 && isNaN(parseFloat(item))) {
typeAheadSource.push(item);
var words = item.split(/\W+/);
for (var k = words.length - 1; k >= 0; k--) {
typeAheadSource.push(words[k]);
}
}
}
}
}
if(typeof(String.prototype.strip) === "undefined") {
String.prototype.strip = function() {
return String(this).replace(/^\s+|\s+$/g, '');
};
}
map.addLayer(markers);
$(document).ready( function() {
$.ajax ({
type:'GET',
dataType:'text',
url: dataUrl,
contentType: "text/csv; charset=utf-8",
error: function() {
alert('Error retrieving csv file');
},
success: function(csv) {
dataCsv = csv;
populateTypeAhead(csv, fieldSeparator);
typeAheadSource = ArrayToSet(typeAheadSource);
$('#filter-string').typeahead({source: typeAheadSource});
addCsvMarkers();
}
});
$("#clear").click(function(evt){
evt.preventDefault();
$("#filter-string").val("").focus();
addCsvMarkers();
});
});
I would like to select the XPath of a tag and the content of the tag, something similar to what Evernote is doing. However, I cannot find any examples. How could this be achieved?
After some research we found this:
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (segs = []; elm && elm.nodeType == 1; elm = elm.parentNode)
{
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[#id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[#class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++;
};
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
}
function lookupElementByXPath(path) {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(path, document.documentElement, null,XPathResult.FIRST_ORDERED_NODE_TYPE, null);
return result.singleNodeValue;
}
I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});