For these inputs:
Origin
Destination
Arrival Time
I want two Google Sheets formulas that result in showing:
the distance in miles
travel times (driving, with traffic).
It'd be simple formulas that reference cells in the sheet that goes something like
=TravelTime(Origin,Destination,Arrive)
I've set up a Google Directions API account and pieced together this so far, but I have no idea how to get the URL to work and how to get the formula to return the outputs I want.
function TravelTime(Origin,Destination,Arrive) {
var Origin
var Destination
var Arrive
var apiUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin='&Origin&'&destination='&Destination&'&key=MYKEY';
}
It seems you are trying to call an external API.
Try doing something like this:
function TravelTime(Origin,Destination,Arrive) {
var apiUrl = 'https://maps.googleapis.com/maps/api/directions/json?origin='&Origin&'&destination='&Destination&'&key=MYKEY';
var response = UrlFetchApp.fetch(apiUrl);
var json = response.getContentText();
var data = JSON.parse(json); //your final object, get the data you want here then return it.
}
Hope it helps!
Related
considering the website: https://www.coindesk.com/price/bitcoin/
I'm trying to extract the value $23,073.15 (that changes continuosly) of the following span class.
span class="typography__StyledTypography-owin6q-0 fZpnIj">$23,073.15</span
I tried the following code with Google script using Cheerio without success:
var URL = "https://www.coindesk.com/price/bitcoin/";
var response = UrlFetchApp.fetch(URL);
var $ = Cheerio.load(response.getContentText());
var itemsOfInterest = $('span.typography__StyledTypography-owin6q-0 fZpnIj').text();```
any help about?
When I saw the HTML data from your URL using Google Apps Script, unfortunately, it seems that the data is retrieved from an API by Javascript. By this, in this case, your expected value cannot be retrieved from your URL with cheerio. So, in this answer, I would like to propose retrieving your expected value using the API. The sample script is as follows.
Sample script:
function sample() {
const url = "https://production.api.coindesk.com/v2/tb/price/ticker?assets=BTC";
const res = UrlFetchApp.fetch(url);
const obj = JSON.parse(res.getContentText());
const value = obj.data.BTC.ohlc.l;
console.log(value)
}
I think that when this script is run, you can see your expected value in the log.
Hi I'm trying to get the current WTI (West Texas Intermediate) price but GoogleFinance doesn't recognize it. Has anybody had luck with this?
Ok. Found a solution. Google Sheets has an add-on and you can add the Yahoo Finance and then run formula =YAHOOFINANCE("ticker") and pick up commodities such as WTI (CL=F).
With Yahoo, you can also get the information by decoding the json cntained in the web page. In A1 for instance =marketPrice("CL=F") and the script :
function marketPrice(code) {
var url='https://finance.yahoo.com/quote/'+code
var source = UrlFetchApp.fetch(url).getContentText()
var jsonString = source.match(/(?<=root.App.main = ).*(?=}}}})/g) + '}}}}'
var data = JSON.parse(jsonString)
var regularMarketPrice = data.context.dispatcher.stores.StreamDataStore.quoteData.item(code).regularMarketPrice.raw
return regularMarketPrice
}
Object.prototype.item=function(i){return this[i]};
Try
=GOOGLEFINANCE("NYSE:WTI","price")
I'm trying to fetch some data to a google sheet. The code goes like this:
function ls() {
var url = "https://api.loanscan.io/v1/interest-rates?tokenFilter=BTC";
var params = {
"contentType": "application/json",
"headers":{"x-api-key": "KEY",
},
};
var json = UrlFetchApp.fetch(url, params);
var jsondata=json.getContentText();
var page = JSON.parse(jsondata);
Logger.log page
return page;
}
The Logger.log gives the correct Data, as you can see in the next link.
Log
However when I run the function in the google sheet, it returns a blank cell.
Please help, thank you.
You should write the Logger.log(page); with parentheses, because sheets is probably hanging on your Logger statement.
I don't have an API key for that site, but I do get the forbidden error response from the API when using =ls() in a cell in sheets.
I would like to return the number of tables in a HTML page to a google sheet. The code below can get me the number of tables in the chrome console.
var i = 1; [].forEach.call(document.getElementsByTagName("table"),
function(x) { (i++, x); });
console.log (i)
But I dont know how to get this result (i) in Google App Script so I can return it to my sheet. Something on the lines of
function doGet() {
var html = UrlFetchApp.fetch('http://allqs.saqa.org.za/showUnitStandard.php?id=7743').getContentText();
var table = getElementsByClassName(html, 'table')[0];
var i = 1; [].forEach.call(document.getElementsByTagName("table"),
(i++, x);
console.log (i)
You want to retrieve the number of tags of <table> fronm the URL of http://allqs.saqa.org.za/showUnitStandard.php?id=7743 using GAS. If my understanding is correct, how about this modification?
Modification points :
In the native GAS, getElementsByTagName() can't be used.
In this answer, the number of <table> was retrieved using regex.
Modified script :
var url = "http://allqs.saqa.org.za/showUnitStandard.php?id=7743";
var res = UrlFetchApp.fetch(url).getContentText();
var numberOfTables = res.match(/<table/g).length;
Logger.log(numberOfTables) // 96 is retrieved.
If I misunderstand your question, I'm sorry.
I keep finding forum results that refer to the google visualiser for displaying my query results. But it just seems to dump the data in a pre-made table. I haven't found a way to write my own custom table dynamically.
In the past, when I have hacked together PHP to make use of mySQL DB, I would simply connect to my DB, run a query into an array, then cycle through the array and write the table in HTML. I could do IF statements in the middle for formatting or extra tweaks to the displayed data, etc. But I am struggling to find documentation on how to do something similar in a google script. What is the equivalent work flow? Can someone point me to a tutorial that will start me down this path?
I just want a simple HTML page with text box and submit button that runs a query on my Google sheet (back in the .gs file) and displays the results in a table back on the HTML page.
Maybe my understanding that GAS/google sheets is an alternative to PHP/mySQL is where I'm going wrong? Am I trying to make a smoothie with a toaster instead of a blender?
Any help appreciated
Welcome David. Ruben is right, it's cool to post up some code you have tried. But I spent many months getting my head around Apps-script and love to share what I know. There are several ways to get the data out of a Google sheet. There is a very well document Spreadsheet Service For GAS. There is also a client API..
There is the approach you mention. I suggest converting the incoming data to JSON so you can do with it as you like.
Unauthenticated frontend queries are also possible. Which needs the spreadsheet to be published and set to anyone with the link can view, and uses the Google visualisation API
var sql = 'SELECT A,B,C,D,E,F,G where A = true order by A DESC LIMIT 10 offset '
var queryString = encodeURIComponent(sql);
var query = new google.visualization.Query('https://docs.google.com/spreadsheets/d/'+ spreadsheetId +'/gviz/tq?tq=' + queryString);
query.send(handleSampleDataQueryResponse);
function handleSampleDataQueryResponseTotal(responsetotal) {
var myData = responsetotal.getDataTable();
var myObject = JSON.parse(myData.toJSON());
console.log(myObject)
}
Other Approaches
In your GAS back end this can get all of your data in columns A to C as an array of arrays ([[row1],[row2],[row3]]).
function getData(query){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A1:C');
var data = range.getValues();
// return data after some query
}
In your GAS front end this can call to your backend.
var data = google.script.run.withSuccessHandler(success).getData(query);
var success = (e) => {
console.log(e)
}
In your GAS backend this can add data to your sheet. The client side API will also add data, but is more complex and needs authentication.
function getData(data){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A1:C');
var data = range.setValues([[row1],[row2],[row3]]);
return 'success!'
}
In your GAS frontend this can send data to your backend.
var updateData = [[row1],[row2],[row3]]
var data = google.script.run.withSuccessHandler(success).getData(updateData);
var success = (e) => {
console.log(e)
}
Finally
Or you can get everything from the sheet as JSON and do the query in the client. This works okay if you manipulate the data in the sheet as you will need it. This also needs the spreadsheet to be published and set to anyone with the link can view.
var firstSheet = function(){
var spreadsheetID = "SOME_ID";
var url = "https://spreadsheets.google.com/feeds/list/" + spreadsheetID +"/1/public/values?alt=json";
return new Promise((resolve,reject)=>{
$.getJSON(url, (data)=>{
let result = data.feed.entry
resolve(result)
});
})
}
firstSheet().then(function(data){
console.log(data)
})