I have a beforeSave function, and one field of the class is a GeoPoint, I want to find the driving distance between the previously available data and the about to be updated data. I understand I need to use some service like Google maps to find the driving distance. But I do not understand how to use a third party js inside the cloud code or call Google directions service with a https request from cloudcode. How do I go about this. Thanks.
The solution was to call the google maps' REST services with a api key from google projects.
This is how my code went.
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+oldLatitude+","+oldLongitude
url = url+"&destinations="+newLatitude+","+newLongitude+"&key=YOUR_API_KEY";
Parse.Cloud.httpRequest({
url: url,
}).then(function(httpResponse) {
var distance = (JSON.parse(httpResponse.text)).rows[0].elements[0].distance.value;
response.success();
}, function(err) {
console.log(err);
response.success();
});
Related
I'm not very experienced with javascript, but the google sheets API is driving me crazy. Took forever to get it to call a range, and now I can't get it to append or update the sheet.
I have done everything in the API setup, I have my API key, client ID, access tokens, all of that, but I can't figure out how to successfully POST to my sheet, and my code is now spaghetti from trying.
Here's what I'm trying to do: I have a button, where onclick it appends a range with the current date, but doing so returns a 401 error, meaning I don't have active credentials. However, I'm signed in, I've tried about 10 different ways of providing the token, and can't update the sheet. here's what I currently have for the onclick function:
CODE EDITED FROM ORIGINAL POST
function fv1Passivated() {
let values = [
[
currentDate
],
];
values = values;
const body = {
values: values,
};
try {
gapi.client.sheets.spreadsheets.values.append({
spreadsheetId: SHEET_ID,
range: 'FV1!A2:A',
valueInputOption: 'USER_ENTERED',
resource: body,
}).then(function() {
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSignInStatus);
updateSignInStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
}).then((response) => {
var result = response.result;
console.log(`${result.updates.updatedCells} cells appended.`);
if (callback) callback(response);
});
} catch (err) {
console.log(err.message);
return;
}
};
And I have no idea how to even start untangling this into something that appends the current date to the end of the range. I'm going a little crazy, as I'm only halfway through freecodecamp's javascript module. Can anyone help? This question is on here a bunch, where people state the need for OAuth over api key, but with zero explanation on how to do that and it's breaking my newbie brain trying to figure it out.
Tried the google api's documentation for a simple write command. Expected it to work, but here we are. Error 401 returned in browser when launching it against localhost.
$(document).ready(function(){
$("#getLocation").on("click", function(){
$.getJSON('https://geoip-db.com/json/geoip.php?jsonp=?')
.done (function(location) {
$('#city').html(location.city);
});
});
});
This is the current JavaScript I've been using, and here is the link to the CodePen I'm using it for. I'm using the location of the users city to find the weather of that city as well.
I've read on multiple sites about how to use several different API's to get the users city location, but non have worked in my project. Thanks for the help, in advance.
To elaborate on my previous answer, a cleaner and more vanilla JavaScript way to get the coordinates is like so.
This is just a few short lines longer and the benefits are massive:
Don't have to include jQuery library, which is massive and slows down page load times
This means you won't have to rely on a HEAVY EXTERNAL API to make AJAX calls for the same data (and other useless API-specific info e.g. requestID) and will seriously streamline your application.
Avoids the use of many callbacks and thus avoids callback hell.
See image below for results. Super lightweight and fast. For more detailed information, have a look at MDN - Using Geolocation.
if ("geolocation" in navigator) {
// Do something with coordinates returned
function processCoords(position) {
let latitude = position.coords.latitude;
let longitude = position.coords.longitude;
let first_div = document.querySelector('div');
let el_h2 = document.createElement('h2');
// Set h2 text as coordinates
el_h2.innerText = `Latitude: ${latitude}, Longitude: ${longitude}`;
// Append h2 to document
first_div.appendChild(el_h2);
}
// Fetch Coordinates
navigator.geolocation.getCurrentPosition(processCoords);
}
To get the City:
It's usually best practice to store the coordinates only in your db
and then make separate city requests when required. This makes things
easier when you want to implement say a Map View on Mobile or Desktop,
which all use coordinates rather than names for plots.
You can use the Google Maps API and passing in the LatLong data directly. Someone has created a gist on how to do it here.
Benefit of using GMaps instead of Geo-IP:
Google Maps API is heavily, heavily, heavily optimised. From faster
servers to better-written code. You can also import a specific part
of the GMaps API so you can cut down on your source code size. All
of this adds up to a much faster experience.
GMaps can be assumed to be around for longer than a 3rd party site like Geo-Ip.
I found this working
function ipLookUp () {
$.ajax('http://ip-api.com/json')
.then(
function success(response) {
console.log(response.city); //Users City
console.log(response.country); //Users Country
},
function fail(data, status) {
console.log('Request failed. Returned status of',
status);
}
);}ipLookUp()
From what I understand, deploying a Google Script as a Google Execution API allows me to call each function from my script separately as and when I need it.
I have a webpage with some buttons and forms that I want to run the functions within my script on.
I have a Google Script with some (example) functionality:
function addPlayer(name,email,group) {
//name email group
var ss = SpreadsheetApp.openById(SHEET_ID); //Sheet belonging to me, script author.
var sheet = ss.getSheetByName("Players");
sheet.appendRow(new Date(),name,email,group);
}
function updatePlayer() {
//update player row with new data
//name email group
}
function anotherFunction() {
//store some data in another sheet within spreadsheet.
}
function listPlayers()
{
//return data from sheet
}
And a sample webpage which wants to run functions from that script:
function OnLoadCallback() { //on gapi load
gapi.client.setApiKey(API_KEY); //developer dashboard generated browser API key
// Create execution request.
var request = {
'function': 'addPlayer',
'parameters': [name,email,group],
'devMode': true
};
// Make the request.
var op = gapi.client.request({
'root': 'https://script.googleapis.com',
'path': 'v1/scripts/' + scriptId + ':run',
'method': 'POST',
'body': request
});
}
I get a 401 UNAUTHENTICATED error at the moment saying I do not have valid auth credentials.
Is it possible for this webpage to use the API without requiring each webpage visitor to oAuth (which doesn't make sense to me as it's not THEIR data/sheet I am trying to access but my own? I know if I deploy as web app I can set it to execute AS me, but is there any similar equivalent for the Execution API?
I chose to use execution script as I need to be able to run several different functions, and as a webapp my only option would be the doPost() which wouldn't let me differentiate adding to sheets/updating sheets/reading from sheets easily?
Am I missing something completely here? If this is entirely the wrong approach I would be super grateful if someone could point me in the right direction.
Thanks!
Based on this SO question, by adding SpreadsheetApp calls, you've modified the authentication scope required for your script. You need to update your scope to include Spreadsheets.
To use the API, you must supply a valid OAuth token that covers all the scopes used by the script. To find the correct scopes to include in the authentication token, open the project in the script editor, then select File > Project properties and click the Scopes tab.
Here is the link for the list of OAuth scope.
Check also this SO question for more information.
I am using Node.js to create a custom server that will intercept any IP addresses users go to and return the name of the site. For example if a user is going to 64.233.160.4 my server will see that, compare it to the list it already has and return Google.
I was told to use Node.js for this task. I looked up creating a DNS using Node.js and found a link to its API and worked off of that. I used tried the example from the Node.js DNS API page;
var dns = require('dns');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
throw err;
}
console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
});
});
});
and I got the following result;
addresses: ["74.125.24.99","74.125.24.104","74.125.24.103","74.125.24.147","74.125.24.105","74.125.24.106"]
reverse for 74.125.24.99: ["de-in-f99.1e100.net"]
reverse for 74.125.24.104: ["de-in-f104.1e100.net"]
reverse for 74.125.24.103: ["de-in-f103.1e100.net"]
reverse for 74.125.24.147: ["de-in-f147.1e100.net"]
reverse for 74.125.24.105: ["de-in-f105.1e100.net"]
reverse for 74.125.24.106: ["de-in-f106.1e100.net"]
This is no good for me as I need Google returned not de-in-f106.1e100.net, so hence why I am creating a custom DNS.
What I am trying to achieve;
Have a known range of IP Addresses 64.233.160.0 - 64.233.191.255
Read an IP address 64.233.160.25
Compare it to the predefined list and be able to see it is within the range
If it within the range, return Google
I have been told to do this with Node.js and have been scouring the internet for information on how to do this, but I just seem to be getting more and more confused. I know I am expected to show all of the work I have done, but I am still trying to start.
If anyone can give me help and advice, it would be greatly appreciated.
I was using Google Weather API to fetch weather info, but apparently Google had stopped its service. And I am trying to switch to Yahoo Weather API now.
var WOEID = 2502265; //random WOEID
$.ajax({
url: "http://weather.yahooapis.com/forecastjson?w=" + WOEID + "&u=c",
dataType: 'json',
success: function(data) {
console.log(data);
}
});
However, is there a way that I can get the WOEID by JavaScript only? Because back then I can just do
http://www.google.com/ig/api?hl=en&weather=NYC
and that's it.
It says on the Yahoo weather API page,
To find your WOEID, browse or search for your city from the Weather home page. The WOEID is in the URL for the forecast page for that city. You can also get the WOEID by entering your zip code on the home page.
But I want to get it by JavaScript, not manually go to weather.yahoo.com and find out the WOEID.
Don't care about the Cross-Origin Policy because I am using it in an Chrome extension and it does not apply.
Okay I got to know from your comments what exactly you want
You have a place name and you want to get the WOEID of that place name using javascript ajax calls
The url to get that is not defined any where you have to use GeoPlanet service to resolve a place to a WOEID
http://where.yahooapis.com/v1/places.q('Place name')?appid=[yourappidhere]
OR you have to use Direct YQL some what like this ( use percent encoding in the url for your city name ) appropriately and try doing an ajax call to this
http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22Place%20name%22&format=xml
you can get it from yahoo too http://developer.yahoo.com/geo/geoplanet/guide/concepts.html
API Reference
DECEMBER 2018 UPDATE:
Definitely use the Direct YQL technique mentioned above by #aravind.udayashankara. I messed around with the yboss api for awhile only to see it has been discontinued (https://developer.yahoo.com/boss/search/) even though Yahoo still has plenty of documentation on it online.
Try the following instead (it runs off the page but there is code within the URL).
yourLocation = "location" (zip, city name, etc.)
urlQuery = "https://query.yahooapis.com/v1/public/yql?q=select+*+from+geo.places+where+text%3D%22" + yourLocation + "%22&format=json"
To get the Woeid by city name
using (WebClient wc = new WebClient())
{
string results = wc.DownloadString("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22" + CityName + "%22&format=xml");
}
See this article for more details