Aman
Aman

Reputation: 1642

Is is possible to use jQuery to make Google Maps API calls?

The following does not work:

$.get('http://maps.googleapis.com/maps/api/geocode/json?&sensor=false&region=nz&address=queen', function(response){ 
console.debug(response); 
});

It seems like it is not possible due to Ajax's same origin policy. However, I am trying to do something interactive and I need responses from Google Maps API within javascript in order to do so.

Upvotes: 2

Views: 1607

Answers (2)

Philar
Philar

Reputation: 3897

An alternative to Lee's solution is to make an Ajax Request to your own server script which in turn makes a call to the Google geocoder url. Here's a simple example in PHP. A working example can be found here.

<?php

$address = $_GET['address'];
$address=str_replace(" ","+",$address);
if ($address) {
    $json = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address='.$address.
    '&sensor=true');
    echo $json;
}

?>

The jQuery Code

$.getJSON("getjson.php?address="+address,
        function(response){ 
                //rest of your code
             });

Upvotes: 0

Lee
Lee

Reputation: 13542

The same origin policy may well make it difficult to access google maps URIs directly. But if you use google's provided Javascript API, you'll have no problems.

Upvotes: 4

Related Questions