Why won't the Google Maps Directions API example in the 'Google Maps' book work for me? - api

I'm using the Petrousos 'Google Maps' book, and trying to run the example in the CHAPTER17/HTML/Directions Service.html downloaded from the book's website at www.mhprofessional.com at item 0071823026.
I had to adjust the table dimensions to get it to display properly, but otherwise made no changes. I'm running it through Firefox.
I set the origin and destination and clicked "Show Directions", at which point nothing happened.
The event called the following function:
function showDirections() {
var start = document.getElementById("origin").value;
var end = document.getElementById("destination").value;
var request = {
origin: start,
destination: end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
printDirections(result);
}
});
}
I get as far as the directionsService.route call, but it is apparently not being executed, and status and result are not defined.
I have no idea how to debug this further, not having access to the API code..
Could the syntax of the call in the example be outdated?
I don't have an API key, but I understand it is not necessary, and I have run other examples without one.

Do you old examples still work? If not, then it's because you don't have an API key. Google will shut you down after you surpassed the quota. I believe the quota is at 50 requests per hours.
Google has the most recent documentation (and it's impressively well documented)
https://developers.google.com/maps/documentation/directions/intro#Audience
Also, can you look at what the object returns? If so, that will usually indicate the quote being surpassed. You can do this by setting a breakpoint at the link
if (status == google.maps.DirectionsStatus.OK) {
If you're using Chrome, you can get to the debugger by right-clicking on the page adn choosing 'Inspect Element', then go to sources, find your line of code and click the link number to set a breakpoint.

Related

parsing JSON returns old data

so I have some database on hosting, I created a PHP script to make this data accessible for my flutter app, so now I'm accessing this data like this.[![enter image description here][1]][1]
getMethod() async {
String theUrl = 'https://tchakrulo.space/getData.php';
var res = await http
.get(Uri.parse(theUrl), headers: {'Accept': 'application/json'});
var responseBody = await json.decode(res.body);
return responseBody;
}
everything works fine except when I'm adding a new entry or updating an existing one somehow my app still returns old data, even after restarting the app, so I want to get new data from json, every time the page loads
Perhaps your values ​​are somehow cached, so if I were you, I would enter the command "flutter clean" into the console and remove the application from your device / emulator, and then reinstall it, if the problem persists, then you probably have a mistake in the code, double-check the correctness of the queries, as well as using the command print("Value: " + value.toString()); to check the values ​​that you get through the console, try to track the path along which the values ​​​​go and you will understand everything. All I can do is just give you an algorithm for solving your problem.

Getting RapidAPI to work with GoogleSheets to extract IMDB data

Google Sheets with RapidAPI
First time trying to get APIs to work! I thought a simple project would be to get a Googlesheet to retrieve movie information based on the title.
Googling around I happened upon RapidAPI which has a Googlesheets add-on. Unfortunately I haven't found much useful documentation so have hit a dead end.
What I've learned so far
There only seems to be one example for how to implement it... by using the =GET() command like so (in this case for pulling finance info):
=GET(”https://investors-exchange-iex-trading.p.rapidapi.com/stock/{symbol}/book”,”quote.companyName”,”YOUR_API_KEY_HERE”,”symbol”,”AAPL”)
I couldn't get this example to work, and the IMDB Code Snippet seems a little different, so I'm not sure how that works at all. Not the curly bracers around {symbol}.
var axios = require("axios").default;
var options = {
method: 'GET',
url: 'https://imdb8.p.rapidapi.com/title/find',
params: {q: 'Dredd'},
headers: {
'x-rapidapi-host': 'imdb8.p.rapidapi.com',
'x-rapidapi-key': '5840855726msh193dee7e1600046p145eddjsnc66aff778896'
}
};
axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});
When I run a typical search on IMDB, I get a URL that looks like this:
https://www.imdb.com/find?q=dredd&ref_=nv_sr_sm
I notice this q parameter there, which seems important...
I'm not sure how I am meant to format this =GET() command for IMDB data. The example suggests one thing, but Googlesheets suggests another: "GET(url, selectPaths, rapidApiKey)"
I'm not sure what the curly bracers are doing in the example URL.
Whatever I try seems to give the same error message:
Error
Request failed for https://imdb8.p.rapidapi.com returned code 400. Truncated server response: 400 - Bad Request (use muteHttpExceptions option to examine full response) (line 98).
Send Help
Does anyone have a better, working tutorial for using this setup? Or could you direct me to some useful reading material that a layperson could understand?
I found a good resource for you. Check out this well-written article on RapidAPI's official blog.
https://rapidapi.com/blog/api-google-sheets/

How do I get sorted results from the Google Photos search API?

I'm using the search API for Google Photos documented here. I'd like the results in the response to be sorted from newest to oldest, but by default, the results are sorted from oldest to newest. Is there a way to reverse the sorting?
I believe your goal as follows.
You want to sort the result values from the method of "Method: mediaItems.search".
You want to sort the values from oldest to newest.
Issue and workaround:
Unfortunately, in the current stage, it seems that there is no parameter for sorting the returned values for the the method of "Method: mediaItems.search" in Google Photos API. Also, it seems that such parameter is not existing in the method of "mediaItems.list".
By the way, it was found that when albumId is used in the request body for the method of "Method: mediaItems.search", the returned values are sorted as the ascending order. If you use the albumn ID, I think that your goal can be achieve by this.
On the other hand, when albumId is NOT used in the request body, the returned values are sorted as the descending order. And also, it seems that when filteres is used in the request body, the returned values are sorted as the descending order.
From your question, I thought that in your situation, albumId might be not used. So in this case, as the current workaround, how about sorting the values using a script after the values are retrieved? In this answer, I would like to propose to use the Web Apps created by Google Apps Script as a wrapper API.
Usage:
1. Create new project of Google Apps Script.
Sample script of Web Apps is a Google Apps Script. So please create a project of Google Apps Script.
If you want to directly create it, please access to https://script.new/. In this case, if you are not logged in Google, the log in screen is opened. So please log in to Google. By this, the script editor of Google Apps Script is opened.
2. Linking Cloud Platform Project to Google Apps Script Project.
About this, you can see the detail flow at here.
And also, please enable Google Photos API at API console.
3. Add scope.
In this case, please addt the scope of https://www.googleapis.com/auth/photoslibrary to the manifest file (appsscript.json).
4. Script.
Please copy and paste the following script (Google Apps Script) to the script editor. This script is for the Web Apps. This Web Apps is used as an API.
function doGet(e) {
const key = "sampleKey"; // This is used for using this Web Apps.
try {
if (e.parameter.key != key) throw new Error("Invalid key.");
const albumId = e.parameter.albumId;
const filters = e.parameter.filters;
const sort = e.parameter.sort;
const headers = {"Authorization": "Bearer " + ScriptApp.getOAuthToken()};
const url = "https://photoslibrary.googleapis.com/v1/mediaItems:search";
let mediaItems = [];
let pageToken = "";
const metadata = {pageSize: 100, pageToken: pageToken};
if (albumId) metadata.albumId = albumId;
if (filters) metadata.filters = JSON.parse(filters);
do {
const params = {
method: "post",
headers: headers,
contentType: "application/json",
payload: JSON.stringify(metadata),
}
const res = UrlFetchApp.fetch(url, params);
const obj = JSON.parse(res.getContentText());
mediaItems = mediaItems.concat(obj.mediaItems);
pageToken = obj.nextPageToken || "";
} while (pageToken);
if (mediaItems.length > 0) {
if (sort && sort == "ascending") {
mediaItems.sort((a, b) => new Date(a.mediaMetadata.creationTime) < new Date(b.mediaMetadata.creationTime) ? -1 : 1);
}
return ContentService.createTextOutput(JSON.stringify({values: mediaItems}));
}
return ContentService.createTextOutput(JSON.stringify({error: "No values."}));
} catch(err) {
return ContentService.createTextOutput(JSON.stringify({error: err.message}));
}
}
5. Deploy Web Apps.
The detail information can be seen at the official document.
On the script editor, at the top right of the script editor, please click "click Deploy" -> "New deployment".
Please click "Select type" -> "Web App".
Please input the information about the Web App in the fields under "Deployment configuration".
Please select "Me" for "Execute as".
This is the important of this workaround.
Please select "Anyone" for "Who has access".
In this case, the user is not required to use the access token. So please use this as a test case.
When you want to use the access token, please set it to Anyone with Google account or Only myself. By this, the user can access to the Web Apps using the access token. When you use the access token, please include the scope of https://www.googleapis.com/auth/drive.readonly or https://www.googleapis.com/auth/drive.
Please click "Deploy" button.
When "The Web App requires you to authorize access to your data" is shown, please click "Authorize access".
Automatically open a dialog box of "Authorization required".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Copy the URL of Web App. It's like https://script.google.com/macros/s/###/exec.
When you modified the Google Apps Script, please redeploy as new version. By this, the modified script is reflected to Web Apps. Please be careful this.
6. Testing.
As the test of this Web Apps, I would like to propose to use the following curl command. Please replace https://script.google.com/macros/s/###/exec with your Web Apps URL.
Simple use:
In this curl command, the result value is returned as the ascending order of oldest to newest.
$ curl -GL -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
Use albumId:
When you want to use the album ID, please use the following curl command.
$ curl -GL -d "albumId=###" -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
In this case, even when -d "sort=ascending" is not used, the result value is returned as the ascending order of oldest to newest.
Use filters:
When you want to use the filters, please use the following curl command.
$ curl -GL -d 'filters={"dateFilter":{"ranges":[{"startDate":{"year":2020},"endDate":{"year":2021}}]}}' -d "key=sampleKey" -d "sort=ascending" https://script.google.com/macros/s/###/exec
In this command, the values of 2020 - 2021 are returned as the ascending order of oldest to newest.
Note:
Although when I searched this at the Google issue tracker, I couldn't find about it. So how about reporting this as the future request? Ref
References:
Method: mediaItems.search
Related thread.
How to use Google Photos API Method: mediaItems.search in Google apps script for a spreadsheet
Google photos api adding photos not working, upload seems to work
Google Apps Scripts: import (upload) media from Google Drive to Google Photos?

Closest Facility Arcgis online javascript not returning data

I am trying to use the Closest Facility (CF) function in ArcGIS API for Javascript. I need to be able to pass a shape coming from a feature service as an incident, and use a feature service with multiple points as the facilities.
Currently when I use the Closest Facility task, nothing happens. No calls are made at all if I look at the network activity.
CFTask.solve(CFParams).then(function (solveResult) {
array.forEach(solveResult.routes, function (route, index) {
console.log(route);
});
});
I understand that i may be passing it incorrect data, but would expect an error message, rather than the nothing I get now.
2 questions:
Does the above code snippet actually run the Closest Facility
function?
How do add data from a feature service to a feature set correctly?
First, verify if an error is triggered inside the promise when you run the code snippet by using catch method:
CFTask.solve(CFParams).then(function (solveResult) {
solveResult.routes.forEach(function(route, index) {
console.log(route);
});
}).catch(console.error);
If you see an error message printed in the console, add it to your question.
Also there is a syntax error in your forEach function

Wit.ai seems to be jumping randomly between stories

I have two separate simple stories on my Wit.ai bot,
the first one takes in the word "Debug", sends "test" then runs a function that outputs context stuff to the console called test_context()
the second one takes in an address, runs a function that changes the context called new_session(), then sends a confirmation of the change to the user structured like "your location has been changed to {address}"
when I type directly into the wit.ai test console it seems to correctly detect the stories and run the corresponding functions, but when I try to use it through the Node.js API it seems to act completely randomly.
Sometimes when typing in an address it will run test_context() followed by new_session(), then output no text, sometimes it will just output the test text followed by the address text and run no functions, sometimes it will act correctly.
The same behavior happens when inputting "Debug" as well.
The back end is set up correctly, as 2 other stories seem to be working perfectly fine.
Both of these stories were working fine earlier today, I have made no changes to the wit stories themselves and no change to the back-end has even touched the debug function.
Is this a known issue?
I encountered this problem as well.
It appears to me as when you do not handle setting context variables in the story from wit.ai correctly (by setting them to null for example), it messes up the story. As a developer it is your own responsability to handle the story correctly "client side", so I can understand wit.ai lets weird stuff happen when you do not do this. Maybe wit.ai decided to jump stories to keep their bot from crashing, still remains a bit mysterious to me. Maybe your problem is of a different kind, just sharing a similair observation and my solution.
Exactly for reasons of testing I created three stories;
handle greetings
tell what the weather in city x is
identify when you want to plan a meeting
The bot is connected to facebook and I handle actions (like planning a meeting) on my nodejs express server.
I said to the bot "I want to plan a meeting tomorrow", resulting in a wit date/time. One timeslot by the way. This is going ok. Then I sent the message "I want to plan a meeting this morning". This resulted in TWO date/time variables in the wit.ai context. In turn, my code could not handle this; two timestamps resulted in null (probably json message getting more complicated and I try to get the wrong field). This in turn resulted in null for the context variable that had to be returned.
So what I did is to catch the error for when the context variable is not filled and just fill in [wit.js could not find date]. This fixed the problem, even though I now of course need to handle this error better.
Old code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
},}
New, working code:
'createAppointment': ({sessionId, context, text, entities}) => {
return new Promise(function(resolve, reject) {
const myDateTime = firstEntityValue(entities, 'datetime');
console.log('the time trying to send ',myDateTime);
if(myDateTime){
createAppointment(context, myDateTime)
context.appointmentText = myDateTime
return resolve(context);
} else {
context.appointmentText = '[wit.js could not find date]'
return resolve(context);
}
});
},
Hope this helps