简体   繁体   English

JSONP和Google Maps Directions API

[英]JSONP and Google Maps Directions API

I'm trying to hit the Google maps directions API using jquery $.ajax. 我正在尝试使用jquery $ .ajax来访问Google Maps Directions API。

I can see in my dev tools that the XHR request is finished, but I think there is an issue with JSON.parse in the way jquery Ajax handles it. 我可以在我的开发工具中看到XHR请求已完成,但是我认为JSON.parse在jquery Ajax处理它的方式上存在问题。

Here is my code: 这是我的代码:

http://codepen.io/jrdnndtsch/pen/Byrxxo http://codepen.io/jrdnndtsch/pen/Byrxxo

$.ajax({
  url:'https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&&callback=?&sensor=false',
  type: 'GET',
  dataType: 'jsonp',
  success: function(data){
    console.log("it worked");
    console.log(data);
  }
});

So, the URL is correct - I can even see it data in dev tools, but I get this error: 因此,URL是正确的-我什至可以在开发工具中看到它的数据,但出现此错误:

Uncaught SyntaxError: Unexpected token :

I've googled my brains out and really need some direction on where to go next. 我已经绞尽脑汁,确实需要下一步的指导。 Any help? 有什么帮助吗?

it looks like the url is being modified from what you are sending to add a ":2" on the end, which is the source of the error, not the JSON that returns. 看起来该URL已从您发送的内容中被修改,并在末尾添加了“:2”,这是错误的来源,而不是返回的JSON。 not sure why that is happening though. 不知道为什么会这样。 I know it's not a real answer, but it at least answers why that error is happening. 我知道这不是一个真正的答案,但至少可以回答为什么发生此错误。

EDIT: 编辑:

I think you need an API key to accept the json in the way you have your code written, otherwise you will get the cross domain issue 我认为您需要一个API密钥才能以编写代码的方式接受json,否则您将遇到跨域问题

$.ajax({
  url:'https://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&&callback=?&sensor=false&key=YOUR-API-KEY',
  type: 'GET',
  dataType: 'json'
})
.done(function(data){
    console.log("it worked");
    console.log(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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