Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
hari86 Avatar asked Jul 03 '26 11:07

hari86


2 Answers

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

like image 200
Paul Tregoing Avatar answered Jul 05 '26 23:07

Paul Tregoing


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.

like image 36
PhonicUK Avatar answered Jul 05 '26 23:07

PhonicUK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!