Adding reviewers image from Google Places Review - json

I am currently using this jQuery plugin on my site to pull in a single user review from my Google Places account:
https://github.com/peledies/google-places (unmodified).
It works ok - however I need to extend the code to somehow also pull in and display the avatar/image of the reviewer that I'm pulling in.
<script>
jQuery(document).ready(function() {
jQuery("#google-reviews").googlePlaces({
placeId: 'ChIJ_____....766FU3cfuE',
render: ['reviews'],
min_rating: 2,
max_rows: 0,
personsName: 'Jt D.'
});
});
</script>
I need to extend this to also include the avatar/image of the single review I am displaying.
I have found "profilePhotoUrl" is in the "reviewer" object in the JSON (https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews) but I can't work out how to add that to the existing code.

After a bit of twiddling around, I found the following solution.
in the google-places.js, find the renderReviews function:
var renderReviews = function(reviews)
add this:
var img = reviews[i].profile_photo_url;
This returns the image stored in the review as a URL. You can then add it to the output within an img html tag:
if (name === plugin.settings.personsName) { html = html+" <img src="+ img +"> <div class='review-item'><div class='review-meta'><span class='review-author'>"+name+" | <span class='review-date'>"+date+"</span></div>"+stars+"<p class='review-text'>"+reviews[i].text+"</p></div>"
}

Related

How to disable double click on img tag

I have one delete img and on clicking on that it will make an api call and delete the record, but on double click it is making multiple api calls. I tried disabling double click using ng-dblclick="return false;" but no use. can some one help me How to disable double click on img tag using angular js?
PS: I have seen this approach is working on div tag
Thanks
Here's an example of how you could avoid multiple api calls. It may look different than your code, but since you havn't provided any, this is the best I can do.
In your controller you'd have a variable, that you set to true on the first click and set to false when your API call returns with a response. Each time the function making the API call is executed, you check whether this variable is true. If it is, you simply return before making the API call again. This is the code (I'm skipping best practices here, to keep the sample minimal):
angular.module('app').controller('myController', function($http){
var ctrl = this;
ctrl.isDeleting = false;
ctrl.deleteRecord = function(id){
if(ctrl.isDeleting){
return;
}
ctrl.isDeleting = true;
$http.delete('[your_api_url]/' + id).finally(function(){
ctrl.isDeleting = false;
});
};
});
Then your html would look like this:
<img src="images/delete.png" ng-click="$ctrl.deleteRecord(id)" ng-class="{'img-disabled': $ctrl.isDeleting}" />
and add some css for visual feedback to the user:
.img-disabled {
cursor: default;
opacity: 0.5;
}
That's it.
To reiterate, I have no idea how your code looks, so I've taken a few assumptions that you'll have to account for when applying this solution.
The easiest option would be :
<img src="Tulips.png" alt="Add" height="25" width="25" ng-disabled="!isEnabled" ng-click="!isEnabled"></img>
var app = angular.module('main', []).
controller('DemoCtrl', function($scope, $filter) {
$scope.isEnabled=true;
});

Google Chart Images Replacement [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 6 years ago.
Improve this question
The Google Chart Images API is currently deprecated and scheduled for retirement on 20th April 2015.
Is there any other free service that can replace it and allow generating chart images just by providing parameters in the URL?
Here's an example for a URL used to generate a PNG image, it can be used as an HTML img source and is useful especially in e-mails:
http://chart.apis.google.com/chart?chxl=1:|Apr+04|Apr+05|Apr+06|Apr+07|Apr+08|Apr+09&chxp=1,0,20,40,60,80,100&chxr=0,0,45&chxs=1,676767,11.5,0,lt,676767&chxt=y,x&chs=550x198&cht=ls&chco=3366CC,FF9900&chds=0,45,0,45&chd=t:7,12,11,9,13,7|11,26,45,24,22,27&chdl=Visits++++|Page+Views&chdlp=t&&chdls=333333,16&chg=100,20,0,0&chls=4|2
This will produce the following image that can be added easily via an <img> tag and is supported across all browser and email clients.
Following this announcement, we made a drop-in-replacement for Google Image Charts πŸ‘ and added gif animation on top of it πŸš€(chart animations in emails are awesome!!).
It's called Image-charts. No more server-side chart rendering pain, no scaling issues, it's blazing fast, 1 URL = 1 image chart.
... and QR Code as well:
https://image-charts.com/chart?
&chs=150x150
&cht=qr
&chl=Hello world
&choe=UTF-8
http://www.jfree.org/eastwood/ is an open-source implementation of the google chart api. Its not 100% faithful but was close enough for me.
At the moment I havent found a solution to actually "link directly" to a chart (see later). But it is possible to convert the charts to images / PNG, and that is the prerequisity. And by converting on the fly you can let users save the chart as an image to a file.
The modern google charts is build up in a <svg> tag. The content of this tag can be drawn on a <canvas> using the excellent canvg library.
When that is done, you can transfer the content of the canvas to an <img> by canvas.toDataURL. Here is an example :
First, include the canvg library
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>
Some markup - 3 tags, a <div> for the chart, a <canvas> and a <img>
<div id="chart_div" style="width: 400px; height: 300px"></div>
<canvas id="canvas"></canvas>
<img id="img" width="200">
Notice "width=200" for the image, just to demonstrate this actually is working :)
Draw a chart as "normal" (as anyone are used to do it), here minimalistic just for the test
function drawLineGraph() {
var data = new google.visualization.DataTable(someJSON);
chart = new google.visualization.BarChart(document.getElementById("chart_div"));
var options = {};
chart.draw(data, options);
}
Draw the chart on window.load. I use a setTimeout for effect, but in a real life scenario I think it would be best to use a google.visualization.events.addListener(xxx, 'ready', function.
window.onload = function() {
drawLineGraph();
setTimeout(function() {
//get SVG content
var chart = document.getElementById('chart_div').getElementsByTagName('svg')[0].parentNode;
var svg = chart.innerHTML;
//get the canvas, adjust width / height
var canvas = document.getElementById('canvas');
canvas.setAttribute('width', chart.offsetWidth);
canvas.setAttribute('height', chart.offsetHeight);
//transfer SVG to canvas by canvg
canvg(canvas, svg);
//get an image source by canvas.toDataURL and add to the image
var imgsrc = canvas.toDataURL("image/png");
document.getElementById('img').setAttribute('src', imgsrc);
}, 1000);
}
The src of the image will look something like :
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAZAAAAEsCAYAAADtt+XCAAAdCklEQVR4Xu2dfcyWZfnHDyFwtZVz68WcJWO9UCRuD4T9KjdrJC0HI8wWbmiTGMJPiXBg8bL+IIhioxio4aaiZIPZCxi9qCtro/ZsCatZGzSiLdZcNtwSwugX8Ou8Nhji88B5f0+vPdf5fD
..
..
Of course going on and on....As normal. I have not yet tried to manipulate / remote link / sent this - only used it as image - but I am sure that this is quite easy!
Result / output for the code above :
My team at Ramen recently built exactly this. It's called ChartURL. It's not forever-free like Google Charts API is, but there is a pretty generous free tier.
It lets you construct URLs in two ways. First, you can encrypt the data into the URL. We use encryption for accounting purposes (since it's not forever-free). In both cases, you encode a template_slug and your data into the URL. The template_slug is a string representation of a chart configuration you can modify, preview, and save inside your account on ChartURL.com. So you can have email-bar-chart-1 and email-bar-chart-2 and timeseries-signups each with their own style/config, and then just send in the data you want graphed inside that template.
Here's an example of generating a URL in ruby:
# This is a working example. View fully commented version here:
# https://gist.github.com/ryana/055414a4804806263b82
require 'json'
require 'openssl'
require 'base64'
require 'cgi'
ENCRYPT_KEY = "dek-d7a46236eda961a6c3c18ffcc6b077ba87d27e9ae85f7842c6d427c265dd5f69d5131308d93332353d4a55a4b1160fcf516515a4a9f0aa50fbf2d7a2e7d0f1c5"
ENCRYPT_KEY_DIGEST = KEY_DIGEST = OpenSSL::Digest::SHA256.new(ENCRYPT_KEY).digest
PROJECT_TOKEN = "dt-RwYN"
def charturl_url(template_slug, data)
json = {options: data}.to_json
cipher = OpenSSL::Cipher.new 'AES-256-CBC'
cipher.encrypt
iv = cipher.random_iv
cipher.key = ENCRYPT_KEY_DIGEST
encrypted_json = cipher.update(json) + cipher.final
iv_for_url = CGI.escape(Base64.encode64(iv))
data_for_url = CGI.escape(Base64.encode64(encrypted_json))
"https://charturl.com/i/#{PROJECT_TOKEN}/#{template_slug}/#{iv_for_url}/#{data_for_url}"
end
# Call our helper
url = charturl_url("weekly-activity",
data: {columns: [["This Week", 10,12,41,9,14,15,15], ["Last Week", 9,14,21,21,20,3,5]]})
#=> https://charturl.com/i/dt-RwYN/weekly-activity/nEPfObOZ3zTivXZqri8ZLA%3D%3D%0A/7X6WrBHEdRcnutV0fU0sN8s9mHFGkkRr%2FZYJwb43p8PDzAJvGWd37zi6ro70%0AVJd9f%2FkSIq2dmJzGe%2BW6CSlpUIrhXHXogvXd%2B%2Fk4VOS%2BTSlnMBwKOSJJNpGZ%0AVrLZd%2Fgq1mSbiXQnc%2FydiTVcGL2DaA%3D%3D%0A
Because URLs have a character limit, we also provide an API that allows you to POST us data and we'll return a short URL:
# This is a working example. View fully commented version here:
# https://gist.github.com/ryana/d37fccd7af3c6c409164/
require 'json'
require 'typhoeus'
API_KEY = "dak-55045dac-bb35-40ac-80c8-874ab71c6f83"
def charturl_url(template_slug, options)
url = "https://charturl.com/short-urls.json?api_key=#{API_KEY}"
headers = {'Content-Type' => 'application/json'}
body = {template: template_slug, options: options}.to_json
surl_response = Typhoeus::Request.post(url, body: body, headers: headers)
raise("Error creating ShortURL: #{surl_response.inspect}") if !surl_response.success?
JSON.parse(surl_response.body)['short_url']
end
# Call our helper
url = charturl_url("weekly-activity", data: {columns: [["This week", 4,1,5,6,1,7,8], ["Last week", 1,5,3,1,6,2,6]]})
url #=> "https://charturl.com/r/J9lA"
I have also been searching for other similar services that could generate static image charts, but have been unsuccessful so far.
However an option is to create your own "service" using php scripts on your own server, to which you can pass parameters.
You could use a php charting library, for example something like pChart to generate the graphs with php, and return the .png image from the script.
Some problems with the javascript-based charting solutions are that you normally cannot use them if you also want to generate PDF's with charts on the fly, or if you want to generate the charts inside Rich-text Editors, or just use them in emails (as you already mentioned).
I was also encountered with such a problem where I needed static image based charts on server side using PHP. I found a way to achieve this using PhantomJS and Google Chart's javascript api. Following is an example of how to do this...
var webPage = require('webpage');
var page = webPage.create();
page.includeJs("https://www.gstatic.com/charts/loader.js", function() {
var expectedContent = '<html>' +
'<head>' +
'<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript">' +
'google.charts.load("current", {packages:["corechart"]});'+
'google.charts.setOnLoadCallback(drawChart);'+
'function drawChart() {'+
'var data = google.visualization.arrayToDataTable(['+
'[\'Task\', \'Hours per Day\'],'+
'[\'Work\', 11],'+
'[\'Eat\', 2],'+
'[\'Commute\', 2],'+
'[\'Watch TV\', 2],'+
'[\'Sleep\', 7]'+
']);'+
'var options = {'+
'title: \'My Daily Activities\','+
'is3D: true,'+
'};'+
'var chart = new google.visualization.PieChart(document.getElementById(\'piechart_3d\'));'+
'chart.draw(data, options);'+
'}'+
'</script>'+
'</head>'+
'<body>'+
'<div id="piechart_3d" style="width: 900px; height: 500px;"></div>'+
'</body>'+
'</html>';
var expectedLocation = 'http://www.phantomjs.org/';
page.setContent(expectedContent, expectedLocation);
window.setTimeout(function () {
page.render("mypng.png");
phantom.exit();
}, 1000); // Change timeout as required to allow sufficient time
});
After that you need to run this javascript file within your PHP:-
exec(ROOT_DIRECTORY . "\phantomjs.exe processImageData.js ", $output);

Chrome extension used to refresh pages

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?
Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html
Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.

GetJSON and using a Show More link

I'm using getJSON to get data from the facebook pages api, and it works just fine, using this code:
$(document).ready(function(){
$.getJSON('url',function(json){
$.each(json.data,function(i,fb){
var output='';
//here I add to output, as this example line:
output += '<div"><a href="http://www.facebook.com/profile.php?id='+fb.from.id+'>'+fb.from.name+'</a>';
$("#results").append(output);
});
});
However, what I'd like to do is similar to what facebook does in it's social plug in where it starts off with 5 entries and has a Show More link, which when clicked, brings in 5 more entries.
Is there a way to do this by altering the code I have?
Thanks
Well, sure there is. Do you want to fetch the other results when a user clicks the "more link" to save bandwidth or is it OK to fetch it at the same time? (async vs sync)
This answer considers the bold text:
output += '<div' + (i >= 5 ? ' style="display: none;"' : '') + '><a href="http://www.facebook.com/profile.php?id=' + fb.from.id +'>'+fb.from.name+'</a></div>';
Oh, and check that line in your code, you had a syntax error and an unmatched div. Also you should have quotation marks around your HTML element's attributes.
For showing the links when the more link is clicked you could do something like:
$('.more').click(function() {
$(this).hide();
// Find the closest ancestor which is a parent of both
// the more link and the actual results list
var $parent = $(this).closest('.parentSelector');
$('.listSelector', $parent).children().show();
return false; // Don't follow the link
});
The parts with the parent stuff above is for the case when you have multiple such results list on the same page and you need to separate them. If you don't need it, here is a simpler variant:
$('.more').click(function() {
$(this).hide();
$('#results').children().show(); // Show all other list items
return false; // Don't follow the link
});

jqPlot charts on page load

I have a form where I select the number of items. Upon clicking submit, it should take me to a new page where it would display the item selected and depending on the number of items selected, it would create those many jqPlots, one for each item.
Any suggestions on how do I go about doing this?
Thanks,
S.
It's hard to give any specifics without more detail about the items, but basically you would pass a JSON structure to your view with the items to be plotted. Then you would loop through the JSON structure, creating DIV tag for each item to be plotted and appending the DIV tags to the body.
The Javascript part would look something like this:
$.each(items, function(index, value) {
$myPlot = $("<div>");
$myPlot.attr("id", "item"+index);
$.jqplot($myPlot.attr("id"), ...);
$("body").append($myPlot);
});
This question is very general, but answering (specifically and only) the question of loading multiple charts:
You need a unique HTML div id for each chart; consider using an RFC 4122 UUID (generate as needed) for each chart/div rather than a sequential index for each. Use something that looks like this as a placeholder div for each:
<div class="chartdiv" id="chartdiv-${UID}">
<a rel="api" type="application/json" href="${JSON_URL}" style="display:none">Data</a>
</div>
This embeds the JSON URL for each div inside it, in a hidden hyperlink that can be discovered by JavaScript iterating over your multi-chart HTML page.
The matter of the UUID is inconsequential -- it just seems the most robust way to guarantee a unique HTML id addressable by JavaScript for each chart.
Subsequently, you should have JavaScript that looks something like:
jq('document').ready(function(){
jq('.chartdiv').each(function(index) {
var div = jq(this);
var json_url = jq('a[type="application/json"]', div).attr('href');
var divid = div.attr('id');
jq.ajax({
url: json_url,
success: function(responseText) { /*callback*/
// TODO: responseText is JSON, use it, normalize it, whatever!
var chartdata = responseText;
jq.jqplot(divid, chartdata.seriesdata, chartdata.options);
}
});
});
});