0
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>

<script>
APIKEY = "xxxxxxxxx";
requestURL = "https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Queens&mode=transit&key=" + APIKEY + "callback=?";

$.ajax({
            url: requestURL, 
            type: "GET",   
            dataType: 'jsonp',
            cache: false,
            success: function(response){                          
                alert(response);                   
            }           
        }); 
</script>

</body>
</html>

Right now this is returning an error of:

https://maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destin…=Queens&mode=driving&key=[APIKEYHERE]&callback=?
maps.googleapis.com/maps/api/directions/json?origin=Brooklyn&destination=Qu…l7pA&callback=jQuery1102013888467964716256_1429822392524&_=1429822392525:2 Uncaught SyntaxError: Unexpected token :

I can't figure out how to get it to work. The API key is currently a browser API key.

eithel
  • 1
  • 1
  • 2

3 Answers3

3

You cannot use ajax to access googles maps api. It will give you an unknown error response but in reality its an "access denied" due to CORS. The below code will give you valid data for the route between brooklyn and queens, driving, in metrics

<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
        var directionsService = new google.maps.DirectionsService();
        var directionsRequest = {
            origin: "brooklyn",
            destination: "queens",
            travelMode: google.maps.DirectionsTravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.METRIC
        };
        directionsService.route(directionsRequest, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {                    
            //do work with response data
            }
            else
                //Error has occured
        })

reference: http://www.sitepoint.com/find-a-route-using-the-geolocation-and-the-google-maps-api/

imGreg
  • 900
  • 9
  • 24
1

The directions-webservice doesn't support JSONP(or CORS) .

When you want to request the service on clientside you must load the maps-Javascript-API and use the API-methods, see https://developers.google.com/maps/documentation/javascript/directions for more details.

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
1

You are doing it in right way! I got the same error. The only thing you have to change is the datatype from jsonp to json, because the google api returns it in json and not jsonp. That's why you getting that error.

Neza
  • 117
  • 1
  • 7