如何使用jQuery从Google Directions api获取JSON?

问题描述 投票:0回答:3
<!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>

现在,这将返回错误:

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 :

我不知道如何使它工作。该API密钥当前是浏览器API密钥。

google-maps google-maps-api-3 directions
3个回答
3
投票
您不能使用Ajax访问Google Maps API。它会给您一个未知的错误响应,但实际上是由于CORS而导致的“访问被拒绝”。以下代码将为您提供布鲁克林和皇后区之间行驶路线的有效数据,以度为单位进行驾驶

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

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

1
投票
directions-webservice不支持JSONP(或CORS)。

[要在客户端上请求服务时,必须加载maps-Javascript-API并使用API​​方法,有关更多详细信息,请参见https://developers.google.com/maps/documentation/javascript/directions


1
投票
您的做法正确!我遇到了同样的错误。您唯一需要更改的是从jsonp到json的数据类型,因为google api返回的是json而不是jsonp。这就是为什么您会收到该错误。
© www.soinside.com 2019 - 2024. All rights reserved.