I’m trying to make a script using the Google Visualization App Geomap. In the example code on the Google Developers page, they are using a hard coded table. What I want to do, is to make code use data from a Google Spreadsheet connected to a Google Form. More specifically, I want to use the data of the spreadsheet tab «countries» from the following spreadsheet: https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit?usp=sharing.
Somehow this does not work, and I get the error messages listed below.
How can I collect the data from the spreadsheet in the right format? I have attempted to use this procedure to collect the data from the spreadsheet: https://google-developers.appspot.com/chart/interactive/docs/spreadsheets.
Error message on web page:
"Data table is not defined"
Error message in Safari Console:
TypeError: undefined is not an object (evaluating 'new google.visualization.Query’)
drawChart help:113
(anonymous function) help:117
My code
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["geomap"]});
google.setOnLoadCallback(drawMap);
function drawMap() {
var opts = {sendMethod: 'auto'};
// ***My code***
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/1l77TXctG6mgva1ggs3iR3eBNx949hzn9SiVjki1v59I/edit#gid=957991050', 'sheet=countries', 'headers=1');
var data = query.send(handleQueryResponse);
var options = {};
options['dataMode'] = 'regions';
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
return response.getDataTable();
}
</script>
Hope there is someone out there who can help me with this (hopefully) not so hard task. Thank you very much in advance! :-)
You can get data inside of a callback function handleQueryResponse
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
} else {
var container = document.getElementById('regions_div');
var geomap = new google.visualization.GeoMap(container);
var data = response.getDataTable();
geomap.draw(data, options);
}
}
Google provides example here.
Also check format which you get in response and use method google.visualization.arrayToDataTable to format data as in example if needed cause it format should be correct.
Related
I'm using a script to extract data from google search console in a sheet.
I built a sidebar to chose on which website the user want to analyse his data.
For that i have a function that can list all sites link to the google account, but i have an error when i try to execute this function in my html file.
I use withSuccessHandler(function) method which sets a callback function to run if the server-side function returns successfully. (i have a OAuth2.0.gs file where is my getService function.
The error is "service.hasAccess is not a function at listAccountSites" where listAccountSites is my function. Here's an extract of my html file:
<script src="OAuth2.0.gs"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
var liste = google.script.run.withSuccessHandler(listAccountSites)
.getService();
console.log(liste);
});
function listAccountSites(service){
if (service.hasAccess()) {
var apiURL = "https://www.googleapis.com/webmasters/v3/sites";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)
console.log('if')
var URLs = []
for (var i in json.siteEntry) {
URLs.push([json.siteEntry[i].siteUrl, json.siteEntry[i].permissionLevel]);
}
/*
newdoc.getRange(1,1).setValue('Sites');
newdoc.getRange(1,3).setValue('URL du site à analyser');
newdoc.getRange(2,1,URLs.length,1).setValues(URLs);
*/
console.log(URLs);
} else {
console.log('else')
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
Browser.msgBox('Open the following URL and re-run the script: ' + authorizationUrl);
}
return URLs;
}
</script>
i found the solution.
Jquery is useless here, you just have to use google.script.run.yourfunction() to run your gs. function on your html sidebar.
I need to get the currentUser information, like email address and or name when a Home.aspx page is loaded in a specific area on the page like maybe the footer area. I have search and every JavaScript that I have found do not work.
I need the text to display either in a Script Editor or Content Editor or an XML file.
What is wrong with the following JavaScript that I found. I have it in the WebApp Script Editor:
<script type=”text/javascript”>
ExecuteOrDelayUntilScriptLoaded(init,”sp.js”);
var currentUser;
function init(){
this.clientContext = new SP.ClientContext.get_current();
this.oWeb = clientContext.get_web();
currentUser = this.oWeb.get_currentUser();
this.clientContext.load(currentUser);
this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}
function onQuerySucceeded() {
document.getElementById(“logUser”).innerHTML = currentUser.get_loginName();
}
function onQueryFailed(sender, args) {
alert(‘Request failed. \nError: ‘ + args.get_message() + ‘\nStackTrace: ‘ + args.get_stackTrace());
}
< /script>
< div>Current Logged User:<label id=”logUser”></label></div>
Can anyone help me?
Most probably init method is not executed since SP.SOD.executeOrDelayUntilScriptLoaded method expects SharePoint Client Library sp.js to be loaded first.
Use SP.SOD.executeFunc method instead since it supports on demand scripts.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext',function(){
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var currentUser = web.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(
function(){
console.log(currentUser.get_loginName());
},
function(sender, args){
console.log('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
});
});
I tried to read an RSS feed from an external website with the following code:
$.get('http://myrssurl.com',function (XMLmediaArray) {
$(XMLmediaArray).find('item').each(function() {
var item = $(this);
var title = item.find('title').text();
var description = item.find('description').text();
var link = item.find('link').text();
var image = item.find('enclosure[type="image/jpeg"]').attr('url');
});
});
I got an error message which says:
XMLHttpRequest cannot load http://myrssurl.com. No '*Access-Control-Allow-Origin*' header is present on the requested resource. Origin 'localhost is therefore not allowed access.
Do you know how to solve this?
Thanks for your help! in the meanwhile I tried to use the GOOGLE RSS FEED service but I also have to deal with a problem by using this:
in the html file I'm using this:
<script type="text/javascript">
new rssdisplayer("msndiv","http://www.myrssfeedurl",6,"date, description");
</script>
and in the Javascript file the follow:
google.load("feeds", "1"); //Load Google Ajax Feed API (version 1)
function rssdisplayer(divid, url, feedlimit, showoptions){
this.showoptions=showoptions || "" //get string of options to show ("date" and/or "description"wink
var feedpointer=new google.feeds.Feed(url) //create new instance of Google Ajax Feed API
feedpointer.setNumEntries(feedlimit) //set number of items to display
document.write('<div id="'+divid+'">Loading feed, </div>')
this.feedcontainer=document.getElementById(divid)
var displayer=this
feedpointer.load(function(r){displayer.formatoutput(r)}) //call Feed.load() to retrieve and output RSS feed
}
rssdisplayer.prototype.formatdate=function(datestr){
var itemdate=new Date(datestr)
return "<span style='color:gray; font-size: 90%'>"+itemdate.toLocaleString()+"</span>"
}
rssdisplayer.prototype.formatoutput=function(result){
if (!result.error){ //if RSS feed successfully fetched
var thefeeds=result.feed.entries //get all feed entries as a JSON array
var rssoutput="<ul>"
for (var i=0; i<thefeeds.length; i++){ //loop through entries
var itemtitle="" + thefeeds[i].title + ""
var itemdate=/date/i.test(this.showoptions)? this.formatdate(thefeeds[i].publishedDate) : ""
var itemdescription=/description/i.test(this.showoptions)? "<br />"+thefeeds[i].content : ""
rssoutput+="<li>" + itemtitle + " " + itemdate + itemdescription + "</li>"
}
rssoutput+="</ul>"
this.feedcontainer.innerHTML=rssoutput
}
else //else, output error
alert("Error fetching feeds: "+result.error.message)
}
but when I execute it in the Browser I get this error message:
Uncaught ReferenceError: rssdisplayer is not defined (index):127 (anonymous function)
Do you guys know what the issue is?
This is an AJAX security: https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS
You are not allowed to query on other websites.
I would recommend to parse the RSS feed on your server and re-format it in JSON for convenience.
I solved it with the Google API RSS Feed Service. The error came because the rssdisplayer.js file was included too late in the html file. Include it directly after the jquery mobile javascript
I'm working with Google Charts Api.
As a data surce, I'm using a Google spreeadsheat. I using this spreadsheat:
https://docs.google.com/spreadsheet/pub?key=0Amf7cOIp81pxdGdxUmFMZVVFVjBwTENTcUpVVldVRnc&output=html
The problem is that as the table has multiple columns, how can I select which column I wnat to show in the chart?
I get the table via: var data = response.getDataTable(); But I don't know hot to get some column from data.
In draw() method I don't know too if I can pass as parameter some specific column
Here my complete code:
google.load('visualization', '1.0', {'packages':['corechart']});
google.load('visualization', '1.0', {'packages':['controls']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheet/pub?key=0Amf7cOIp81pxdGdxUmFMZVVFVjBwTENTcUpVVldVRnc&output=html');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
// Testing
console.log(data.getColumnId(1));
var chart = new google.visualization.PieChart(document.getElementById('columnchart'));
var options = {'title':'World Cup Statistics',
'width':800,
'height':800};
chart.draw(data, options);
Use the setQuery method of the Query object:
query.setQuery('select A, B, C');
Use the letter ID's of the columns you want to select in the query. Documentation on the query language is here.
What I am trying to do:
Get location based off of IP (Done)
Use the City and Country code to use openweather's API (Done)
Read the XML into my webpage so that I can display the "Temperature" field.
This is my first venture into using XML in webpages, and I've tried for 3 days now with no success. I have searched google and stackoverflow, and have tried many things so far, including SimpleXMLElement, with no luck.
What I currently have on my page is just a generated link to the XML sheet for your location.
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
var city = geoip_city();
document.write('Link text');
</script>
How am I able to display the text from the required field on my page?
Thanks in advance! :)
It might be easier to change the API call to return JSON, in which case you could then use this code, the temps are stored in temp, temp_min and temp_max.
var country = geoip_country_code();
var city = geoip_city();
$.getJSON('http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=json&units=metric', function( json ) {
var temp = json.main.temp;
var temp_min = json.main.temp_min;
var temp_max = json.main.temp_max;
document.write( 'Temp: ' + temp + '<br>');
document.write( 'Temp Min: ' + temp_min + '<br>');
document.write( 'Temp Max: ' + temp_max + '<br>');
});
You could use javascript library to convert the xml into a javascript object - one such library is called xml2json, it works as a jQuery plugin: http://www.fyneworks.com/jquery/xml-to-json/
Then you can simply do:
var xmlObject;
$.ajax({
url: url_of_xml,
success: function(data) {
xmlObject = $.xml2json(data);
}
});
Then you just need to place the data on your page. The object in my example is faked, but it gives you the idea:
// put this line in the success callback of your ajax call
// after you create the xmlObject
$('#temp').html(xmlObject.weather.temp);
To display the temperature you get the XML, and read one of the three temperature attributes from the XML returned:
$.get("http://api.openweathermap.org/data/2.5/weather?q=' + city + ',' + country + '&mode=xml&units=metric", function(xml) {
avg = $(xml).find("temperature").attr("value"));
max = $(xml).find("temperature").attr("max"));
min = $(xml).find("temperature").attr("min"));
(using JQuery)