Google geocoding returns zero results, Unity3D - google-maps

I am trying to connect to google maps api and get lant/long of place, but no matter what I'm trying to get, I receive ZERO_RESULTS every time. For example if I type
http://maps.googleapis.com/maps/api/geocode/json?address=Moscow+Tverskaya+18 into browser, it gives me correct result, but if I'm trying to send the exact same string via WWW class from unity I get zero results.
IEnumerator GetGoogleCoords() {
var url = "http://maps.googleapis.com/maps/api/geocode/json?";
var qs = "";
// qs += "address=" + savedAddress;
qs += "address=Moscow +Tverskaya+18";
var req = new WWW(url + "?" + qs);
Debug.Log(url + qs);
yield return req;
Debug.Log(req.text);
}
I tried every request and in every order

You have an extra "?" in your url as #Engerlost said.
This post is about how to prevent doing similar mistakes again.
Best programming practice would be to build the full url not in WWW constructor but in a separate line.
var url = "http://maps.googleapis.com/maps/api/geocode/json?";
var qs = "address=Moscow +Tverskaya+18";
var fullUrl = url + "?" + qs
var request = new WWW(fullUrl);
That is, one line should contain only one job. Which makes it much easier to manage the code. In your case, it gets much easier to debug and see there is an error building the full url. Now you are able to easily add a Debug.Log if you suspicious about final url which goes into WWW as parameter.
Debug.Log("Request url: " + fullUrl);
And you would easily see the resulting url contains two "?" characters.

Related

UrlFetchApp function truncates my api json call

This is the code I am running to grab assignments from the Canvas LMS API.
var response = UrlFetchApp.fetch(canvas_link + "api/v1/courses?access_token="+api_key+"&enrollment_state=active");
var courses = JSON.parse(response.getContentText());
var assignments = UrlFetchApp.fetch(canvas_link + "api/v1/courses/" + courses[3].id + "/assignments?access_token="+api_key)
var assignmentsArray = JSON.parse(assignments)
It grabs the cources using an api key then requests assignments for those courses using the course id. Everytime I get the error that it Truncated my output. The assignmentsArray always returns a length of 10 when I know that there is more assignments in the course. And it will return less than 10 if there is less than 10 assignments.
I have tried using the UrlFetchApp.getRequest() function to get the request and put that into my browser it works and returns json for all the assignments.
I have tried adding headers and other options the the options for the UrlFetchApp.fetch(url, options) to see if they did anyting, but it didn't work.

how to use nextPageToken

I have a script that archives old classrooms, until the end of 2021 it was working fine.
In the lasts months I got an error (the script works ok, but terminate with error) and today I was investigating it, the script runs only once per month.
The error is due to a supposed change in .nextPageToken function.
var parametri = {"courseStates": "ARCHIVED"};
var page = Classroom.Courses.list(parametri);
var listaClassi = page.courses;
var xyz = page.nextPageToken;
if (page.nextPageToken !== '') {
parametri.pageToken = page.nextPageToken;
page = Classroom.Courses.list(parametri);
listaClassi = listaClassi.concat(page.courses);
};
var xyz has been added to better understand what was happening.
So, in this case the list does not have pagination, is only one page. var xyz returns "undefined", and the "if" statement results "true", this makes that variable listaClassi got appended the same content a second time. That generate the error and the abnormal end of the script.
I found an issue reported here https://issuetracker.google.com/issues/225941023?pli=1 that may be related with my problem.
Now I could change .nextPageToken with .getNextPageToken but I found no docs on the second function and many issues reporting that is not working, can anyone help me?
When using the nextPageToken value obtained to the response make sure to enter it as a separate parameter with a slightly different name. You will obtain nextPageToken in the response, the pageToken parameter needs to be entered in the request. It does look like you are doing it right, the way you add the parameter is a bit odd, yet it should be functional.
To discard problems with the Classroom API (that we can certainly take a look at) try with this simple code example in a new Google Apps Script project, remember you will need to add an Advanced service, information about advanced services can be found in this documentation article https://developers.google.com/apps-script/guides/services/advanced. Use listFiles as the main method in your Apps Script project.
function listFiles() {
var totalClasses = 0;
nextPageToken = "";
console.log("Found the following classes:")
do {
var response = loadPage(nextPageToken);
var classes = response.courses;
for (let x in classes){
console.log("Class ID: " + classes[x].id + " named: '" + classes[x].name + "'.");
}
totalClasses += classes.length;
} while (nextPageToken = response.nextPageToken)
console.log("There are " + totalClasses + " classes.")
}
function loadPage(token = ""){
return Classroom.Courses.list({
fields: 'nextPageToken,courses(id,name)',
pageSize: 10,
pageToken: token
});
}
When we first make the API call with Apps Script we don't specify a pageToken, since it is the first run we don't have one. All calls to the List method may return a nextPageToken value if the returned page contains an incomplete response.
while (nextPageToken = response.nextPageToken)
In my code at the line above once response.nextPageToken is empty (not in the response) inside the condition block JavaScript will return false, breaking the loop and allowing the code to finish execution.
To have your incident reviewed by a Google Workspace technician you can also submit a form to open a ticket with the Google Workspace API Support team at https://support.google.com/a/contact/wsdev.

Find googleusercontent.com URL for an InlineImage

Whenever I upload an image (i.e. InlineImage) in a Google Doc, it uploads it to a CDN and references a googleusercontent.com URL. If I'm using Google Apps Script on a DocumentApp, I can get an instance of InlineImage. I know I can convert it to a base64 and then create a data URL for this image. However, instead of creating this gigantic URL, I'd rather just use the existing googleusercontent.com URL.
How do I find out the googleusercontent.com URL for an InlineImage?
Essentially you need to do the following:
Set a unique alt description on the InlineImage.
Get the HTML of the entire document.
Use a regex to find the <img tag using the unique alt description from step 1.
function getUrlOfInlineImage(inlineImage) {
var altDescription = inlineImage.getAltDescription(); // warning: assumes that the alt description is a uuid. If it's not unique, this function might return a different image's url. If it's not a UUID, it might contain illegal regex characters and crash.
if (!altDescription) {
inlineImage.setAltDescription(Utilities.getUuid());
// TODO: We currently crash because if we attempt to get the HTML right after calling setAltDescription(), it won't exist in the HTML. We must wait a bit of time before running it again. If there was something like DocumentApp.flush() (similar to how the Spreadsheet App has the same function), it might resolve this issue and we wouldn't need to crash.
throw "Image was missing an alt description. Run again."
}
var html = getGoogleDocumentAsHTML();
var regex = new RegExp('<img alt="' + altDescription + '" src="([^"]+)"');
var matches = regex.exec(html);
if (matches) {
return matches[1];
} else {
return null;
}
}
function getGoogleDocumentAsHTML() {
var id = DocumentApp.getActiveDocument().getId() ;
var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
var param = {
method : "get",
headers : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
muteHttpExceptions:true,
};
var html = UrlFetchApp.fetch(url,param).getContentText();
return html;
}
There is obviously room for improvement with the script (e.g. not making it crash), but this was good enough for my use-case.

How do I use filterByFormula in Airtable API with Google App Scripts?

I am able to retrieve records using views, but I am not sure how to filterByFormula in Google App Scripts
function mwe() {
API_KEY = SECRET;
BASE_URL = BASE;
var url = "https://api.airtable.com/v0/" + BASE_URL + "/TRNO?api_key=" + API_KEY + '&maxRecords=3&view=All%20not%20entered';
var response = UrlFetchApp.fetch(url);
var result = JSON.parse(response.getContentText());
var myResult = result["records"]
Logger.log(myResult);
}
There are a few things that can be done to try to achieve the formula field via the API.
The more in-depth and entwined the data and in the formulas are naturally it becomes harder to scheme JSON from retrieving or query of the base and records. i.e.
lookups
rollups
Nested Ifs with rollups lookups & links
Or concatenates string from link to other formulas in lookups or rollups.
In your case, there is only the need to use an encoded URL try this tool will help you correctly establish the correctly, encoded URL needed. Plus save you some time in the future.
https://codepen.io/airtable/full/rLKkYB
The Endpoint should maybe look something like this below once you play around with it.
var url = "https://api.airtable.com/v0/YOUR_BASE_ID/filterByFormula=NameOfYourFormulaField"/TRNO?api_key=" + API_KEY + '&maxRecords=3&view=All%20not%20entered'";
But when trying to filterByRecords and retrieve records using views the value for filterByFormula should be a string. You can test the formula by creating a formula field from the Airtable UI.
{
pageSize: 50,
filterByFormula: '{Record1} = TRUE()',
sort: [{field: 'Record1 Date',direction: 'desc' }]
}
And just one last thing,If you are wanting to use filterByFormula with record IDs in a linked table, you can create a formula in the linked table that is RECORD_ID(), then add a lookup to that formula field in the main table. and list NameFormalfield
[https://api.airtable.com][2] goes a lot more in-depth into the String formatting etc.
Hope this helps Good Luck.

JSONProxy At http://jsonp.afeld.me/ Error

I am using the following function to get JSON data particular API via JSONP Proxy mentioned above. I want to get the MESSAGE from this API.
function callMe() {
var part1 = 'https://jsonp.afeld.me/?callback=?&url=';
var part2 = 'http://m.icta.lk/services/railwayservicev2/station/getByID?id=168';
var url = part1 + part2;
$.getJSON(url, function(data) {
document.getElementById("stName").innerHTML = data.MESSAGE;
});
}
For the above URL I'm getting a message saying Found 1 Results!. That's OK. Proxy is working fine.
But when this URL is assigned to part2 variable
part2 = http://m.icta.lk/services/railwayservicev2/ticket/getPrice?startStationID=184&endStationID=61&lang=en
I'm getting a message saying Missing Parameters.
Nothing is wrong with above two URLs. You can check. This works well for the first one, But not for the second one. Please help
Since your part2 contains query parameters, the JSONP server doesn't know that you're trying to pass the startStationID= to it, or through to the other API. The solution here is to encode your part2:
var url = part1 + encodeURIComponent(part2);
which turns all the ampersands (&) in part2 to %26.