简体   繁体   中英

$.ajax returns error when calling google api

I'm building an angular app where I have a 'public transportation' section and I want to get directions from the google api. I seem to get a valid url - when I enter the url in my browser, it returns the json. But I get an error when user $.ajax.

Url

http://maps.googleapis.com/maps/api/directions/json?
origin=Assenede,%20Belgi%C3%AB&destination=Industrieweg%20232,Gent-
Mariakerke,belgium&sensor=false&departure_time=1343641500&mode=transit

Function in angular controller

$scope.getDirections = function(){

        var directions_url = "http://maps.googleapis.com/maps/api/directions/json" +
         "?origin=" + $scope.details.formatted_address +
         "&destination=Industrieweg 232,Gent-Mariakerke,belgium" +
         "&sensor=false" + 
         "&departure_time=1343641500"+
         "&mode=transit";

         console.log(directions_url);

        $.ajax({
            type:"GET",
            dataType:"json",
            contentType:"application/jsonp",
            url: directions_url,
            success:function(data){
                alert(data);
            },
            error:function(xhr, status, error){
                console.log('error:' + status + error);
            }
        });
     }

Is there anyone that can come up with a solution?

Thanks in advance. HS.

The reason is that you don't set dataType properly as it's needed for using JSONP. That's why you may get this error (I assume you're using jQuery):

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

But, even if you fix that by rewriting your code as follows:

var url = "http://maps.googleapis.com/maps/api/directions/json?origin=Assenede,%20Belgi%C3%AB&destination=Industrieweg%20232,Gent-Mariakerke,belgium&sensor=false&departure_time=1343641500&mode=transit";

$.ajax({
    dataType:"jsonp",
    url: url,
    success:function(data){
        alert(data);
    },
    error:function(xhr, status, error){
        console.log('error:' + status + error);
    }
});

You'll get another error:

Uncaught SyntaxError: Unexpected token : json:2
error:parsererrorError: jQuery110209881844320334494_1387726816235 was not called 

Which means that the remote side (Google in your case) sends you plain JSON instead of requested JSONP. As David mentioned, you need to revise your solution, and find another way of calling Google API (for instance, you can try to use Google Maps JavaScript API ).

That URL returns plain JSON, but you will need JSONP to make a cross origin request. I'm not sure google has a JSONP option for maps, but you can look into some other ways around it like CORS or a server-side proxy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM