HERE-MAPS Altitude Information of Route in javascript - javascript

I am trying to get the gradient information of the calculated route from here maps.
According to the documentation I need to add:
returnElevation = True
to cause "all shapes inside routing response to consist of 3 values instead of 2"
this was done here:
jsonAttributes: 1,
linkAttributes: 'sh,sl,ds',
routeAttributes: 'waypoints,shape,boundingBox',
legAttributes: 'boundingBox,shape',
maneuverAttributes: 'po,sh,rn,sp,rs,sa,sq',
returnElevation=true,
representation: 'turnByTurn',
later I receive the data with this:
var geo = links.shape[0].split(",");
latitudes.push(parseFloat(geo[0]));
longitudes.push(parseFloat(geo[1]));
altitude.push(parseFloat(geo[2]));
For some reason, this approach does not work, any Idea what I might be doing wrong?

Try replacing returnElevation=true with returnElevation:true, i think returnElevation=true will work directly in REST API request however javascript needs it with a ":"

Related

How do I make a query to Google Places API?

I'm trying to make a client-side jquery request on an HTML page (in my Spring project) to the Google Places API so I can determine the ratings of a particular business type within a radius of x,y. At the moment I'm trying to do it like so:
function getCafe(){
$(document).ready(function(){
$('.search_latitude').val(marker.getPosition().lat());
$('.search_longitude').val(marker.getPosition().lng());
// These are lat long values calculated by the user's searched location on a google map on the client side
var Lat = marker.getPosition().lat();
console.log(Lat);
var Long = marker.getPosition().lng();
console.log(Long);
var cafeRatings = [];
// Ive disclosed my API Key
var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/xml?location=" + Lat + "," + Long + "&radius=500&type=restaurant&keyword=cruise&key=MY_API_KEY";
$.ajax({
type: "GET",
dataType: "xml",
url: url,
success: function(xml) {
$(xml).find('results').each(function(){
$(this).find("rating").each(function(){
var rating = $(this).text();
cafeRatings.push(rating);
});
});
//This is a simple debug to display the contents of the rating array to ensure the parse worked correctly
alert(cafeRatings.join("\n"));
}
});
});
}
However Michael Geary's answer to this question Google's Places API and JQuery request - Origin http://localhost is not allowed by Access-Control-Allow-Origin has lead me to believe I cannot use an Ajax jquery to access the API this way and I have to "use the Places Library from the Maps API V3. (As I) can't just hit a URL directly from JavaScript or jQuery code."
With that being said I've found the documentation to do this to be quite broad and resources online seem to be quite limited. Has anyone any experience on how to simply get the rating elements from the API stored into an array in JS so I can calculate the average and display it in a text box?
In case it's needed this how the XML formatted API looks
<PlaceSearchResponse>
<status>OK</status>
<result>
<name>Sydney Showboats</name>
<vicinity>32 The Promenade, Sydney</vicinity>
<type>travel_agency</type>
<type>restaurant</type>
<type>food</type>
<type>point_of_interest</type>
<type>establishment</type>
<geometry>
<location>
<lat>-33.8675570</lat>
<lng>151.2015270</lng>
</location>
<viewport>
<southwest>
<lat>-33.8689120</lat>
<lng>151.2001126</lng>
</southwest>
<northeast>
<lat>-33.8662141</lat>
<lng>151.2028105</lng>
</northeast>
</viewport>
</geometry>
<rating>3.8</rating> <------ This is the element im trying to ad to the array
<icon>
https://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png
</icon>
<reference>
CmRSAAAALItuCtuLapozzsjq3dmKqj7NDik149XsgUwHD3ob5AWfHYlZtykuJbQa0cq0GMqX8dRgucTCmitnXgV-ekE3GfV7910rzHhx3ZuadVYNuWMzLDVZDCj2G1yiBw8r_hhgEhCPDXsniaZ2ZrkvYyXFfmQrGhSzdmkAEz4stXNx2qFe-GqAlldzgw
</reference>
<id>ce4ffe228ab7ad49bb050defe68b3d28cc879c4a</id>
<opening_hours>
<open_now>false</open_now>
</opening_hours>
<photo>
<photo_reference>
CmRaAAAAh4dP9hsZ_6515QNxouVnuYFYKemmf8BE01rcaOvkFlILQiwGNe_OAX0ikmobMmWZJvyjsFEsn7j1TFhauHSrek8nY5GsW24_6nwJsqEwHTUC10SL5gQITHhkdam50G1PEhCP-C7Of2mkjqJCTYFeYGWuGhQjVoWASHiGSp3WHm26Bh2sYOglZw
</photo_reference>
<width>2048</width>
<height>1152</height>
<html_attribution>
Sydney Showboats
</html_attribution>
</photo>
<place_id>ChIJjRuIiTiuEmsRCHhYnrWiSok</place_id>
<scope>GOOGLE</scope>
</result>
........
</PlaceSearchResponse>
My previous advice remains the same: you can't use the server-oriented web service version of the Places API. You have to use the JavaScript client library. It is much easier to use than the web service API (even if you were allowed to use that), because you don't have to parse any XML, just access the object properties that the client library provides.
There are several examples in the Places Library documentation. The Place Search example is fairly close to what you are doing. It looks like you want to access the rating for a place, and that is easy with the JavaScript library; simply use the rating property of your place object (or whatever name you give that variable).
I took the Place Search example and updated the fiddle to illustrate accessing the rating property. Try it out and see if it helps answer your question.
In any case, the bottom line is unchanged: you can't use the web service API, you need to use the JavaScript client library, but that is a Good Thing, as the client library does most of the work for you.
If the question is how to compute the average rating for the places you receive back from the API, that is simple: write a loop and do the arithmetic. If you look at the fiddle you will see where it has a loop that iterates over the results variable that the API callback receives. The loop in the fiddle creates a marker for each element of results, but you can do whatever you want there. Just add up all the rating values and divide the total by results.length and you have your average. Of course check that the length is nonzero, so you don't divide by zero.
For example, if you have a results variable with the array of places results, you could do:
var totalRating = 0;
results.forEach( function( place ) {
totalRating += place.rating;
});
var averageRating = results.length == 0 ? 0 : totalRating / results.length;

Codebird.js for Twitter API won't return more than one tweet in single call

Codebird.js is not working when I try to return a list of n number of tweets by adding to my params object.
It works when I include just the property screen_name to get a single tweet but when I add count in, as below, the response I get is still for only one tweet
params = {
"screen_name": screenName,
"count": "3"
};
I can't seem to find any codebird.js documentation besides the README.MD on the main github page.
Is my syntax correct? Am I approaching this the correct way by adding to params
Solved it. Turns out I was using the wrong api endpoint and should have been using statuses/user_timeline.
Note: Check this part of the docs to see how to map this endpoint's string to the right format https://github.com/jublonet/codebird-js#mapping-api-methods-to-codebird-function-calls

Using Wikia API

I am trying to access the X-men API on wikia, to try and extract the name and image of each character, to then be used on a SPA using javascript.
This is the link too the page on the wiki:
http://x-men.wikia.com/wiki/Category:Characters
I cannot for the life of me figure out how to access the API. It doesn't seem to be RESFTful, and that's all I have any experience in.
Has anyone used the Wikia API successfully before? I can get some articles and such, but nothing useful.
(The documentation is shocking, been searching around for hours.)
Probably you have already found a solution, but I think you should write something like this:
import requests
xmen_url = "http://x-men.wikia.com/api/v1/Articles/List?expand=1&category=Characters&limit=10000"
r = requests.get(xmen_url)
response = r.json()
# print response
a = 0
for item in response['items']:
a += 1
print("{}\t{}\t({})".format(str(a),item['title'].encode(encoding='utf-8'),item['id']))
This will print a list of all the articles of the category Characters (I think there also some subcategories, you should check). If you want to take a deeper look at the json file you can uncomment the commented code.
Hope it helps.

Simple MEAN Stack issue

I have a express route;
router.get('/uni/:queryst', function (req, res) {
var choice = req.params.queryst);}
Where basically I use the queryst value from the URL to use it to query something in my database. On the front end, I need to have an input field where the user types the choice and hits submit and then it translates to something like /uni/valuehere on the browser and sending GET to express where it gets caught by the router I wrote above. I don't know how can I make the input field of HTML turn into a URL of the format /uni/valuehere .
As for testing the code initially I was directly typing the URL manually with the value I intended to verify to check if the data passed. Well, users are not going to type URL's directly to search, they will need a form and that is what I can't get my head around to how to turn the input field into a URL in a format /uni/WhateverTheUserHasTypedInTheFieldShouldAppearHere
Thanks in advance for the help. I am self learning the MEAN stack and have come a long way. I need support of experienced developers as I am currently stuck here.
While sending the request write (in controller):
$http.get('/uni/'+queryst).success(function(response){
// Write code using response
});
While on the server side write:
$http.get('/uni/:queryst',function(req,res){
var choice= req.params.queryst
// Code ....
});

load entire json file into variable as array

I want to take an external json file (locations.json) and load the contents into a variable. I would then like to use this variable using the information provided here: http://www.json.org/js.html
I've had a lot of trouble trying to load the external json to a variable. I've looked at this ( load json into variable ) page quite a bit, and none of that actually populates the variable. When displaying the variable's contents later, it appears to be empty.
$("#testContain").html("<p>" + json + "</p>");
Using methods listed in the last link, this dispays "undefined".
The json file that I am using looks like this:
[{"id":"1","locname":"Dunstable Downs","lat":"51.8646","lng":"-0.536957","address":"Chiltern Gateway Centre","address2":"","city":"","state":"England","postal":"","phone":"","web":"http:\/\/www.nationaltrust.org.uk\/main\/w-dunstabledownscountrysidecentrewhipsnadeestate","hours1":"","hours2":"","hours3":""},
{"id":"2","locname":"West Delta Park","lat":"45.5974","lng":"-122.688","address":"N Broadacre St and N Expo Rd, Portland","address2":"","city":"","state":"OR","postal":"","phone":"","web":"http:\/\/en.wikipedia.org\/wiki\/Delta_Park","hours1":"","hours2":"","hours3":""}]
Anyone have any suggestions?
The problem is that the request is asynchronous. You could make a synchronous call as suggested by the accepted answer to the question that you linked to, but that is generally not a good idea as it will freeze the browser completely while it is waiting for the response.
The variable is assigned just fine, but when you use it after requesting it, you have to make sure that it's after getting the response, not just after sending the request. Using the value in the callback for the getJSON method is the easiest way to make sure that you have the value:
var my_json;
$.getJSON(my_url, function(json) {
my_json = json;
// here you have the value
});
// here you don't have the value, as this happens before the response arrives

Categories