Adding Postcode Validation to a Field with Google Distance Matrix API

We are trying to create some extra validation for a postcode field in part 1 of a multistep form, Using google maps Distance Matrix API to check the distance of the Postcode entered is within 50miles of a specific address (if not, it should stop the user from going any further within the form). Would anyone be able to see if the code is targeting the correct fields correctly, or if the code has errors that won’t allow the feature to work? As I am not an expert in coding and still learning.

Here is the current App without any of the postcode validation JS added -Knack

Here is the code I had added previously in the knack builder JS section (currently removed from live app as did not work) -

<!-- Include Google Maps JavaScript API -->
<script src="https://maps.googleapis.com/maps/api/js?key=mykey"></script>

// Set a fixed address as latitude and longitude coordinates
const yourFixedAddress = { lat: 51.513440, lng: 0.427720 };

// Wait until the 'view_14' view is rendered
$(document).on('knack-view-render.view_14', function(event, view, data) {

  // Attach a click event listener to the form's submit button
  $("#view_14 .kn-submit input[type=submit]").on("click", function(e) {
    
    e.preventDefault();  // Prevent the form from submitting immediately

    // Retrieve the value (postcode) of the input field with ID 'kn-input-field_48'
    var origin = $('#vehicle-reg--number #field_48').val();
    
    // Set the fixed destination for comparison
    var destination = 'yourFixedAddress';

    // Create a new instance of the Google Maps Distance Matrix service
    var service = new google.maps.DistanceMatrixService();

    // Request the distance and duration from the origin to the destination
    service.getDistanceMatrix({
      origins: [origin],
      destinations: [destination],
      travelMode: 'DRIVING',
      unitSystem: google.maps.UnitSystem.METRIC,
    }, function(response, status) {
      
      // If the request was successful
      if (status == 'OK') {
        
        // Extract the origin and destination addresses from the response
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        // Loop through each origin
        for (var i = 0; i < origins.length; i++) {
          
          // Get the result for each destination
          var results = response.rows[i].elements;
          
          // Loop through each destination
          for (var j = 0; j < results.length; j++) {
            
            // Extract the distance from the result
            var element = results[j];
            var distance = element.distance.value;

            // Convert distance from meters to miles
            var distanceInMiles = distance * 0.000621371;

            // If the distance is less than or equal to 50 miles
            if (distanceInMiles <= 50) {
              
              // Remove the previous event handler and submit the form
              $("#vehicle-reg--number .kn-submit").unbind('submit').submit();
            } else {
              
              // If the distance is more than 50 miles, alert the user
              alert('Sorry, your location is not within our service range.');
            }
          }
        }
      } else {
        
        // If there was an error with the request, alert the user
        alert('Error was: ' + status);
      }
    });

    return false;  // Prevent the form from submitting 
  })
});
1 Like