How do I make a query to Google Places API? - javascript

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;

Related

HERE-MAPS Altitude Information of Route in 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 ":"

Listen for new urls of ads posted to site

for (var i = 3848450; i > 3848400; i--) {
var query = {
url: 'http://classifieds.rennug.com/classifieds/viewad.cgi?adindex=' + i,
type: 'html',
selector: 'tr',
extract: 'text'
}
,
uriQuery = encodeURIComponent(JSON.stringify(query)),
request = 'http://127.0.0.1:8888//?q=' +
uriQuery + '&callback=?';
jQuery.getJSON(request, function (data) {
var datastring = data[0].results;
var datasplit = datastring.toString().split('Sign');
$('#inner-content').append(datasplit[0]);
});
}
I want to listen for new URLs of ads that are posted without writing some kind of arbitrary code that takes up a lot of memory looping through new URLs, etc. I can do that but it seems redundant and such as my code listed above. Im using noodle.js to get the info from the pages. Now I would like a way to listen for new urls instead of looping through every possible url from a to z. Since I don't know z it's a safe bet I'll be using an if statement but how would one go about incorporating this nth URL without ending up with undefined iterations. Im still learning and find this place has many helpful people. This is simply a fun project I'm doing to learn something new.
If I understand you correcly, you want an external thing to inform your javascript when there's new a URL or JSON data
Unfortunately the web is not built for servers to contact clients, with one exception to my knowleadge: WebSockets
You already seem to have a local server so you meet the requirements plus node ships with them ready for use (also available on the browser). To use noodlejs with websockets you'd have to require the package and set up the WebSocket to send data to your client
Other than pointing you towards that direction, I don't think I can do better than the internet at giving you a tutorial. Hope this helps, Have fun! Also thanks for telling me about noodle, that thing is awesome!

Return list of places within x mile radius of current location

I have a database of places with lat/lng information and I'd like to create a json feed that returns a list of places within an x mile radius of the current lat/lng of a user. What's the best way to do something like this?
My javascript will likely make an ajax call with the current lat/lng and the backend will handle what places get returned. Then I'll render those places using js. (LMK if you think that's the best way to handle this and if so, how does the backend logic work?)
Check out the Geocoder gem. It supports ActiveRecord and several DB engines, including PostgreSQL.
If you have a Venue model, you can add geocoding to it and do things like:
nearby_places = Venue.near([lat, long], distance)
There is also an example on advanced queries at GitHub for this project, quoted in full below.
When querying for objects (if you're using ActiveRecord) you can also look within a square rather than a radius (circle) by using the within_bounding_box scope:
distance = 20
center_point = [40.71, 100.23]
box = Geocoder::Calculations.bounding_box(center_point, distance)
Venue.within_bounding_box(box)
This can also dramatically improve query performance, especially when used in conjunction with indexes on the latitude/longitude columns. Note, however, that returned results do not include distance and bearing attributes. If you want to improve performance AND have access to distance and bearing info, use both scopes:
Venue.near(center_point, distance).within_bounding_box(box)
You can do in this way:
1) make ajax call from your javascript block:
$.ajax({
url: '<%= url_for :action => :find_places %>',
data: {
lat: $('#lat_field').val(),
ing: $('#ing_field').val()
},
dataType: 'json',
success: function( data ) {
response( $.map( data, function( places ) {
// do something with places
// like places.name and so on
// this function will be called for each item in json array
}));
}
});
2) catch this action in your controller
def find_places
#places_array = Array.new
#places_array[0] = {:name => ' ...', :others => '...'}
respond_with #places_array.to_json
end
3) dont forget to add respond_to :json in the beginning of your controller and get 'find_places' in your routes.rb.
Actually it will be more 'Ruby'-style to proceed result of your calculation in find_places.js.erb file which have acces to your controller instance variable. In this case you dont need to use json at all.
Hmm, postgres has a geospatial extension called postgis that's worth looking into. I've actually had better experience with sphinx, which can use any db table (mysql, mongo, sqlite, even csv or xml) as a source.

Get Twitter Feed as JSON without authentication

I wrote a small JavaScript a couple of years ago that grabbed a users (mine) most recent tweet and then parsed it out for display including links, date etc.
It used this json call to retrieve the tweets and it no longer works.
http://twitter.com/statuses/user_timeline/radfan.json
It now returns the error:
{"errors":[{"message":"Sorry, that page does not exist","code":34}]}
I have looked at using the api version (code below) but this requires authentication which I would rather avoid having to do as it is just to display my latest tweet on my website which is public anyway on my profile page:
http://api.twitter.com/1/statuses/radfan.json
I haven't kept up with Twitter's API changes as I no longer really work with it, is there a way round this problem or is it no longer possible?
Previously the Search API was the only Twitter API that didn't require some form of OAuth. Now it does require auth.
Twitter's Search API is acquired from a third party acquisition - they rarely support it and are seemingly unenthused that it even exists. On top of that, there are many limitations to the payload, including but not limited to a severely reduced set of key:value pairs in the JSON or XML file you get back.
When I heard this, I was shocked. I spent a LONG time figuring out how to use the least amount of code to do a simple GET request (like displaying a timeline).
I decided to go the OAuth route to be able to ensure a relevant payload. You need a server-side language to do this. JavaScript is visible to end users, and thus it's a bad idea to include the necessary keys and secrets in a .js file.
I didn't want to use a big library so the answer for me was PHP and help from #Rivers' answer here. The answer below it by #lackovic10 describes how to include queries in your authentication.
I hope this helps others save time thinking about how to go about using Twitter's API with the new OAuth requirement.
You can access and scrape Twitter via advanced search without being logged in:
https://twitter.com/search-advanced
GET request
When performing a basic search request you get:
https://twitter.com/search?q=Babylon%205&src=typd
q (our query encoded)
src (assumed to be the source of the query, i.e. typed)
by default, Twitter returns top 25 results, but if you click on
all you can get the realtime tweets:
https://twitter.com/search?f=realtime&q=Babylon%205&src=typd
JSON contents
More Tweets are loaded on the page via AJAX:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd&include_available_features=1&include_entities=1&last_note_ts=85&max_position=TWEET-553069642609344512-553159310448918528-BD1UO2FFu9QAAAAAAAAETAAAAAcAAAASAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Use max_position to request the next tweets
The following json array returns all you need to scrape the contents:
https://twitter.com/i/search/timeline?f=realtime&q=Babylon%205&src=typd
has_more_items (bool)
items_html (html)
max_position (key)
refresh_cursor (key)
DOM elements
Here comes a list of DOM elements you can use to extract
The authors twitter handle
div.original-tweet[data-tweet-id]
The name of the author
div.original-tweet[data-name]
The user ID of the author
div.original-tweet[data-user-id]
Timestamp of the post
span._timestamp[data-time]
Timestamp of the post in ms
span._timestamp[data-time-ms]
Text of Tweet
p.tweet-text
Number of Retweets
span.ProfileTweet-action–retweet > span.ProfileTweet-actionCount[data-tweet-stat-count]
Number of Favo
span.ProfileTweet-action–favorite > span.ProfileTweet-actionCount[data-tweet-stat-count]
Resources
https://code.recuweb.com/2015/scraping-tweets-directly-from-twitter-without-authentication/
If you're still looking for unauthenticated tweets in JSON, this should work:
https://github.com/cosmocatalano/tweet-2-json
As you can see in the documentation, using the REST API you'll need OAuth Tokens in order to do this. Luckily, we can use the Search (which doesn't use OAuth) and use the from:[USERNAME] operator
Example:
http://search.twitter.com/search.json?q=from:marcofolio
Will give you a JSON object with tweets from that user, where
object.results[0]
will give you the last tweet.
Here is a quick hack (really a hack, should be used with caution as its not future proof) which uses http://anyorigin.com to scrape twitter site for the latest tweets.
http://codepen.io/JonOlick/pen/XJaXBd
It works by using anyorigin (you have to pay to use it) to grab the HTML. It then parses the HTML using jquery to extract out the relevant tweets.
Tweets on the mobile site use a div with the class .tweet-text, so this is pretty painless.
The relevant code looks like this:
$.getJSON('http://anyorigin.com/get?url=mobile.twitter.com/JonOlick&callback=?', function(data){
// Remap ... utf8 encoding to ascii.
var bar = data.contents;
bar = bar.replace(/…/g, '...');
var el = $( '<div></div>' );
el.html(bar);
// Change all links to point back at twitter
$('.twitter-atreply', el).each(function(i){
$(this).attr('href', "https://twitter.com" + $(this).attr('href'))
});
// For all tweets
$('.tweet-text', el).each(function(i){
// We only care about the first 4 tweets
if(i < 4) {
var foo = $(this).html();
$('#test').html($('#test').html() + "<div class=ProfileTweet><div class=ProfileTweet-contents>" + foo + "</div></div><br>");
}
});
});
You can use a Twitter API wrapper, such as TweetJS.com which offers a limited set of the Twitter API's functionality, but does not require authentication. It's called like this;
TweetJs.ListTweetsOnUserTimeline("PetrucciMusic",
function (data) {
console.log(data);
});
You can use the twitter api v1 to take the tweets without using OAuth. For example: this link turns #jack's last 100 tweets.
The timeline documentation is here.
The method "GET statuses/user_timeline" need a user Authentification like you can see on the official documentation :
You can use the search method "GET search" wich not require authentification.
You have a code for starting here : http://jsfiddle.net/73L4c/6/
function searchTwitter(query) {
$.ajax({
url: 'http://search.twitter.com/search.json?' + jQuery.param(query),
dataType: 'jsonp',
success: function(data) {
var tweets = $('#tweets');
tweets.html('');
for (res in data['results']) {
tweets.append('<div>' + data['results'][res]['from_user'] + ' wrote: <p>' + data['results'][res]['text'] + '</p></div><br />');
}
}
});
}
$(document).ready(function() {
$('#submit').click(function() {
var params = {
q: $('#query').val(),
rpp: 5
};
// alert(jQuery.param(params));
searchTwitter(params);
});
})

json "invalid label" - when parsing google Distance Matrix Request

I'm having hard time with this simple ajax call
function sendreq()
{
$.ajax({
dataType: 'jsonp',
url: 'http://maps.googleapis.com/maps/api/distancematrix/json?origins=Seattle&destinations=San+Francisco&mode=driving&sensor=false',
success: function (jsonp)
{
alert('success');
}
});
}
I'm able to see the api result in json format when i hit the url from browser and seems like jQuery sees the result too but is unable to parse.
it throws an error
invalid label "destination_addresses" : [ "San Francisco, CA, USA" ],
im using jQuery 1.7.1. from ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js
any help would be appreciated
thanks.
You can't get Distance Matrix's data by Ajax, because of Same Origin Policy. If you are using Google Distance Matrix API , the only way you can retrieve that data, is from your server-side script. The other method is, you can use Distance Matrix Service. For both methods(API and Service) you have to notice Usage Limits and Requirements:
Use of the Distance Matrix service must relate to the display of
information on a Google Map; for example, to determine
origin-destination pairs that fall within a specific driving time from
one another, before requesting and displaying those destinations on a
map. Use of the service in an application that doesn't display a
Google map is prohibited.
Maybe you need to use the JavaScript API?
http://www.quora.com/Why-doesnt-the-Google-Maps-API-support-JSONP,
http://blog.futtta.be/2010/04/09/no-more-jsonp-for-google-geocoding-webservice

Categories