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

前端 未结 3 925
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 08:07



  
  jQuery.getJSON demo
  

        
相关标签:
3条回答
  • 2020-12-12 08:17

    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/

    0 讨论(0)
  • 2020-12-12 08:23

    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.

    0 讨论(0)
  • 2020-12-12 08:40

    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.

    0 讨论(0)
提交回复
热议问题