DistanceMatrix AJAX query on Google directions Service route returns error

China☆狼群 提交于 2019-12-25 16:52:27

问题


I am trying to get the JSON response of a DistanceMatrix AJAX call, after successful ("OK" status) of directionsService.route. The route is shown but it always return error on the route data.

var map;
function initMap() {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: -34.397, lng: 150.644 },
    zoom: 8,
});
directionsDisplay.setMap(map);
directionsService.route({
    origin: "Lisbon",
    destination: "Porto",
    travelMode: 'DRIVING'
}, function (response, status) {
    if (status === 'OK') {
        directionsDisplay.setDirections(response);
        $.ajax({
            url: "https://maps.googleapis.com/maps/api/distancematrix/json?units=metric&origins=Washington,DC&destinations=New+York+City,NY&key=MyValidKeyTestedOnBrowser", //Google example
            data: {},
            success: function (data, status) { alert(data.d) },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown != 'abort') debugger; //returns this
            },
            beforeSend: alert("before")
        })
    } else {
        window.alert('Directions request failed due to ' + status);
    }
 });
}

Why the URL from Google example is returning error? textStatusis "error".

来源:https://stackoverflow.com/questions/43956836/distancematrix-ajax-query-on-google-directions-service-route-returns-error

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