$就调用谷歌API时返回错误 [英] $.ajax returns error when calling google api

查看:162
本文介绍了$就调用谷歌API时返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要建一个角度应用程序在那里我有一个公共交通部分,我想从谷歌的API方向。我似乎得到一个有效的URL - 当我在浏览器中输入网址,它返回的JSON。但我得到一个错误,当用户$阿贾克斯。

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.

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

功能的角度控制器

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

在此先感谢。
HS。

Thanks in advance. HS.

推荐答案

的原因是因为它需要使用JSONP您没有设置正确的dataType。这就是为什么你可能会得到这个错误(我假设你使用jQuery):

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. 

不过,即使你修复通过重写你的code如下:

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);
    }
});

您会得到另一个错误:

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

这意味着远端(谷歌你的情况)向您发送纯JSON,而不是要求JSONP的。正如David所说,你需要修改您的解决方案,并找到调用谷歌API(例如的另一种方式,你可以尝试使用的谷歌地图API的JavaScript )。

这篇关于$就调用谷歌API时返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆