Skip to content Skip to sidebar Skip to footer

$.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

Solution 1:

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:2error:parsererrorError:jQuery110209881844320334494_1387726816235wasnotcalled

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).

Solution 2:

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.

Post a Comment for "$.ajax Returns Error When Calling Google Api"