【问题标题】:How do I get JSON from google directions api using jQuery?如何使用 jQuery 从 Google Directions api 获取 JSON?
【发布时间】:2015-07-02 06:32:31
【问题描述】:
<!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


    【解决方案1】:

    您不能使用 ajax 访问 googles maps api。它会给你一个未知的错误响应,但实际上它是由于 CORS 而导致的“访问被拒绝”。 下面的代码将为您提供 brooklyn 和 Queens 之间的路线的有效数据,驾驶,指标中

    <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/

    【讨论】:

      【解决方案2】:

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

      当您想在客户端请求服务时,您必须加载 maps-Javascript-API 并使用 API 方法,有关详细信息,请参阅https://developers.google.com/maps/documentation/javascript/directions。

      【讨论】:

        【解决方案3】:

        你做对了!我得到了同样的错误。您唯一需要更改的是从 jsonp 到 json 的数据类型,因为 google api 在 json 而不是 jsonp 中返回它。这就是您收到该错误的原因。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-05
          • 1970-01-01
          相关资源
          最近更新 更多