Search code examples
javascriptjquerygoogle-mapsgoogle-distancematrix-api

Why isn't my callback function being evoked when using the Google Distance Matrix Service API


The below code works fine except the callback function is not being evoked. None of the alerts in the callback function are displayed but the Start and End alerts both appear. I've checked the console and Google returns the data you'd expect, example below.

My concerns are;

  • What is the strange code before the Google response (/**/_xdc_._6ct5vb && _xdc_._6ct5vb()

  • What is the URL parameter callback=initMap doing when including the Google javascript file?

Google Response:

/**/_xdc_._6ct5vb && _xdc_._6ct5vb( {
   "destination_addresses" : [ "Church Street, Liverpool L36 9TJ, UK" ],
   "origin_addresses" : [ "Ashmount Rd, Liverpool L17 0BZ, UK" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "5.1 mi",
                  "value" : 8175
               },
               "duration" : {
                  "text" : "16 mins",
                  "value" : 959
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}
 )

Javascript/jQuery:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?php echo GOOGLE_MAPS_API_KEY; ?>&callback=initMap" type="text/javascript"></script><!-- Google Maps -->

  <script>
$( document ).ready(function() {

// validate form
$( "#add_employee_mileage" ).validate({
errorClass: "error-class"
});

$( "#calculateMileage" ).click(function() {
    
alert('Start');
  
var origin = $( "#employee_mileage_start_postcode" ).val();
var destination = $( "#employee_mileage_end_postcode" ).val();

var service = new google.maps.DistanceMatrixService();

service.getDistanceMatrix(
    {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        avoidHighways: false,
        avoidTolls: false
    }, 
    callback
);
  
function callback(response, status) {
    
    alert('Callback');

    if(status=="OK") {
        alert('Ok');
        alert(response.rows[0].elements[0].distance.value);
        $( "#employee_mileage_mileage" ).val(response.rows[0].elements[0].distance.value);
    } else {
        alert("Error: " + status);
    }
    
}

alert('End');
  
});

});
</script>

HTML:

  <form id="add_employee_mileage" name="add_employee_mileage" action="https://www.system-uk.com/admin-area/ajax/add_employee_mileage.php" method="post"><fieldset>
<legend>Mileage Details</legend>

<table class="nobord"><tr><td><table class="nobord"><tr>
    <td class="bold">Employee</td>
    <td class="bold">Vehicle</td>
    <td class="bold">Start Postcode</td>
    <td class="bold">End Postcode</td>
    <td class="bold">Mileage</td>
    <td class="bold">&nbsp;</td>
  </tr><tr>
    <td><select id="employee_mileage_employee_id" name="employee_mileage_employee_id" required></select></td>
    <td><select id="employee_mileage_vehicle_id" name="employee_mileage_vehicle_id" required></select></td><td><input type="text" id="employee_mileage_start_postcode" name="employee_mileage_start_postcode" maxlength="8" style="width:85px;" value="L17" required></td><td><input type="text" id="employee_mileage_end_postcode" name="employee_mileage_end_postcode" maxlength="8" style="width:85px;" value="L3" required></td><td><input type="number" id="employee_mileage_mileage" name="employee_mileage_mileage" min="0" step="any" required></td><td><input type="button" id="calculateMileage" value="Calculate Mileage">&nbsp;<input type="submit" value="Save"></td></tr></table></td></tr></table>

</fieldset></form></div>

Solution

  • The following code worked for me. Notice there is no callback function

      <script>
    $( document ).ready(function() {
    
    // validate form
    $( "#add_employee_mileage" ).validate({
    errorClass: "error-class"
    });
    
    $( "#calculateMileage" ).click(function() {
    
    var origin_postcode = $( "#employee_mileage_start_postcode" ).val();
    var destination_postcode = $( "#employee_mileage_end_postcode" ).val();
    
    var distanceService = new google.maps.DistanceMatrixService();
        distanceService.getDistanceMatrix({
            origins: [origin_postcode],
            destinations: [destination_postcode],
            travelMode: google.maps.TravelMode.DRIVING,
            unitSystem: google.maps.UnitSystem.IMPERIAL,
            avoidHighways: false,
            avoidTolls: false
        },
        function (response, status) {
            if (status !== google.maps.DistanceMatrixStatus.OK) {
                alert('Error: ', status);
            } else {
                $( "#employee_mileage_mileage" ).val((response.rows[0].elements[0].distance.value * 0.000621371).toFixed(2));
            }
        });
    
     });
    
    });
    </script>