How do I get JSON from google directions api using jQuery?

最后都变了- 提交于 2019-11-27 08:43:37

问题


<!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 = "AIzaSyC1CCvx0HI78PGLWpO-R67s8r7A0zckEyc";
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>

Right now this is returning an error of:

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 :

I can't figure out how to get it to work. The API key is currently a browser API key.


回答1:


You cannot use ajax to access googles maps api. It will give you an unknown error response but in reality its an "access denied" due to CORS. The below code will give you valid data for the route between brooklyn and queens, driving, in metrics

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

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




回答2:


The directions-webservice doesn't support JSONP(or CORS) .

When you want to request the service on clientside you must load the maps-Javascript-API and use the API-methods, see https://developers.google.com/maps/documentation/javascript/directions for more details.




回答3:


You are doing it in right way! I got the same error. The only thing you have to change is the datatype from jsonp to json, because the google api returns it in json and not jsonp. That's why you getting that error.



来源:https://stackoverflow.com/questions/29834185/how-do-i-get-json-from-google-directions-api-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!