hari86
hari86

Reputation: 669

Accessing Google Maps API with JavaScript

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script type="text/javascript">
    var url = "https://maps.googleapis.com/maps/api/place/search/json?key=AIzaSyBnEjp_CRcL_APx4mMsmuke9SV1PWZfnww&sensor=false&location=26.526437,-80.163004&radius=500&keyword=Physican%27s+Weight+Loss+Centers&types=";
    jQuery.getJSON(url, function (data) {
        alert(data);
    });

</script>
</body>
</html>

While running the code above, I'm not getting the alert window. The URL doesn't have any callback function. Any help or useful links how to parse/retrieve data from JSON URL using jQuery or Javascript will be appreciated.

Upvotes: 3

Views: 718

Answers (3)

Anders Arpi
Anders Arpi

Reputation: 8397

See Paul Tregoing's post for a good explanation on what is happening and how to get around it in general.

However, in this case there is in fact a proper JavaScript API for Google maps (including Places, which you seem to be using). You can check it out here.

Upvotes: 1

PhonicUK
PhonicUK

Reputation: 13844

The headers returned by google for that request don't allow for cross-domain queries.

HTTP/1.1 200 OK
status: 200 OK
version: HTTP/1.1
cache-control: private
content-encoding: gzip
content-length: 1932
content-type: application/json; charset=UTF-8
date: Mon, 24 Sep 2012 12:27:10 GMT
server: mafe
vary: Accept-Language
x-frame-options: SAMEORIGIN
x-xss-protection: 1; mode=block

So what you actually need to do is have some code in your server grab the data, then pass it along so you don't violate the cross domain rules.

Either that or see if google offer up a JSONP version of the API.

Upvotes: 2

Paul Tregoing
Paul Tregoing

Reputation: 111

I'm assuming this is cross-domain. In which case the following jQuery should work:

$.ajax(url, {
    crossDomain: true,
    dataType: 'jsonp'
}).success(function(data) {
    alert(data);
}).fail(function() {
    alert('fail');
});

Note: jQuery won't give you access to http status codes on cross-domain requests, it'll just fire .success() on a 200 response, and .fail() on non-200 - e.g. you'll struggle to handle 404 vs. 403 client-side. If you want to have finer control consider using something like jquery-jsonp.

Also worth noting: use a browser debugger (firebug/whatever) this should at least tell you what response is coming back on the ajax request - it might well be that your request is getting a non-200 - this would be a failure case for jQuery. You're a bit limited in what you can do in this case.

Some background reading: http://en.wikipedia.org/wiki/Same_origin_policy

Upvotes: 2

Related Questions