Querying the Google Places API using jQuery

The Google Places API is now generally available. I am trying to use the .ajax () call in jQuery to call Google Places. The error I keep returning is Unprepared SyntaxError: Unexpected token:

I am using jQuery 1.5.2. I tried 1.5.1 too, but it had the same results. I would prefer not to go to 1.6.1 if I can help him.

I made similar ajax calls similar to these other APIs, but I have problems with Google Places. Below is a very simple code example that you can play with. You will need to get your own key in the Google API console (https://code.google.com/apis/console)

jQuery.noConflict(); jQuery(document).ready(function(){ var url = 'https://maps.googleapis.com/maps/api/place/search/json'; jQuery.ajax({ url: url, dataType: 'jsonp', type: 'GET', data: { location: '33.787794,-117.853111', radius: 1000, name: 'coffee', key: 'your_key', // add your key here sensor: 'false' }, // on success success: function(data, textStatus, jqXHR){ console.log(data); }, // on failure error: function (jqXHR, textStatus, errorThrown){ console.log(jqXHR); console.log(textStatus); console.log(errorThrown); } }); }); 
+3
source share
2 answers

From what I see from the documentation, the Google Places web services API does not support JSONP - only JSON. The error you see is that the response is just JSON, but handled as JSONP, and this causes an error.

Check out the Google Maps JavaScript API — it includes a place library that you can use — see google.maps.places.PlacesServices#search() .

AFAIK seems to shift towards removing JSONP support - for example, the geocoding API used to support JSONP (undocumented) in version 2, but not in v3. Someone suggested that it might be to encourage developers to use the JavaScript API instead.

+4
source

The following is not a direct solution. But, how I got his job ...

Since JSONP is not supported (and I did not understand how client code should use this API in any case), the solution should proxy it through your server ... If you use rails on the server side, the below may work for you:

 class PlacesController < ApplicationController def autocomplete # Using Google Web Services # https://code.google.com/apis/console url = "https://maps.googleapis.com/maps/api/place/autocomplete/json" _params = { :key => "<<< YOUR KEY >>>", :types => "geocode", :sensor => (params[:sensor] or false), :input => params[:q] } ans = %x{curl -G --data-urlencode #{_params.map{|k,v| "#{k}=\"#{v}\""}.join(" --data-urlencode ")} "#{url}"} ans = ActiveSupport::JSON.decode(ans) render :json => ans end end 

PS: To generate an API key, use https://code.google.com/apis/console

+4
source

All Articles