Success and Error on the same AJAX call

1

I thought twice before writing this title, but that's the case. This question is related to DistanceMatrix AJAX query on Google directions Service route returns error, but i managed to get the success working. The event is fired when an input is clicked in the MVC View:

<input onclick="initMap()">

Then, on a .js file the method that initiates the map with the route:

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=AIzaSyAuEZxHZusVYyvsDUk8USfi2blK42c5oSo",
            success: alert("success"),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                if (errorThrown != 'abort') alert("error");
            },
        })
    } else {
        window.alert('Directions request failed due to ' + status);
    }
 });
}

When i click on the input, the map appears (not yet with the route selected), and a pop-up "success". You click it, there's another "error" pop-up, that you click and finally you see the route (Lisbon -> Porto), as it should be.

initMap() is only called once, and a breakpoint showed that the AJAX is only being called once.

STRANGE NOTE: if i add dataType: JSON to the AJAX call, i get the "success" alert and after clicking the alert, a Visual Studio error:

Unhandled exception at line 4, column 11992 in http://localhost:31620/Scripts/jquery-3.1.1.min.js //note is a jQuery error
0x800a01b6 - JavaScript runtime error: Object doesn't support property or method 'toLowerCase'

So, my question is, what is happening here, and how can i get DistanceMatrix JSON on a directionsService.route (in short words, get route data after setting a route).

javascript
json
ajax
google-distancematrix-api
asked on Stack Overflow May 13, 2017 by Tiago • edited May 23, 2017 by Community

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0