If you want your Fluent Forms WordPress form to automatically calculate travel distance based on a user’s postcode, and pass that distance to your emails or database, this step-by-step guide will help you set it up — using Google Maps Distance Matrix API for accurate distance calculation.
Why Use Google Maps Distance Matrix API?
Calculating the driving distance between two locations is tricky. The Google Maps Distance Matrix API provides accurate driving distances and durations between origins and destinations, perfect for travel cost estimations or delivery quotes.
What You'll Build
- A Fluent Form with a postcode input and a distance field
- An AJAX-powered postcode lookup that sends the postcode to WordPress backend
- The backend calls Google Maps API to calculate distance from a fixed origin to the postcode destination
- The distance gets returned to JavaScript, populates the distance field, triggers Fluent Forms recalculation, and enables form submission
Step 1: Create Your Fluent Form
Make sure your form includes:
- Postcode field — where the user inputs their postcode
- Distance field — where the calculated distance will be shown and submitted
- Calculated fields (optional) — that use the distance for price or other formulas
- Submit button
Step 2: Add JavaScript to Handle Postcode Blur Event
Here’s a sample JS snippet to send the postcode to the backend and update the distance field:
jQuery(document).ready(function($) {
if ($('#fluentform_6').length === 0) {
return;
}
const $submitBtn = $('#fluentform_6 .ff-btn-submit');
const $distanceField = $('#ff_6_travel_distance');
$submitBtn.prop('disabled', true);
$('#ff_6_address_zip_').on('blur', function() {
const postcode = $(this).val().trim();
if (!postcode) {
$submitBtn.prop('disabled', true);
return;
}
$.ajax({
url: fluent_form_ajax.ajax_url,
method: 'POST',
data: {
action: 'calculate_distance',
postcode: postcode,
security: fluent_form_ajax.nonce
},
success: function(response) {
if(response.success) {
const distanceValue = response.data.distance;
$distanceField.val(distanceValue);
const nativeInputEvent = new Event('input', { bubbles: true });
$distanceField[0].dispatchEvent(nativeInputEvent);
const nativeChangeEvent = new Event('change', { bubbles: true });
$distanceField[0].dispatchEvent(nativeChangeEvent);
$submitBtn.prop('disabled', false);
} else {
console.error('Distance calculation error:', response.data.message);
$submitBtn.prop('disabled', true);
}
},
error: function() {
console.error('AJAX error calculating distance');
$submitBtn.prop('disabled', true);
}
});
});
});
Step 3: Add PHP AJAX Handler with Google Maps API Integration
Add this code to your theme's functions.php
or a custom plugin.
Make sure to replace 'YOUR_GOOGLE_MAPS_API_KEY'
with your actual API key.
phpCopyEditadd_action('wp_ajax_calculate_distance', 'calculate_distance_callback');
add_action('wp_ajax_nopriv_calculate_distance', 'calculate_distance_callback');
function calculate_distance_callback() {
check_ajax_referer('fluent_form_nonce', 'security');
$postcode = sanitize_text_field($_POST['postcode'] ?? '');
if (empty($postcode)) {
wp_send_json_error(['message' => 'Postcode is required']);
}
$origin = '123 Main Street, Your City, Your Country'; // Change to your fixed origin address
$destination = $postcode;
$api_key = 'YOUR_GOOGLE_MAPS_API_KEY';
// Prepare Google Maps Distance Matrix API request
$url = add_query_arg([
'origins' => urlencode($origin),
'destinations' => urlencode($destination),
'key' => $api_key,
'units' => 'metric',
], 'https://maps.googleapis.com/maps/api/distancematrix/json');
$response = wp_remote_get($url);
if (is_wp_error($response)) {
wp_send_json_error(['message' => 'Failed to contact Google Maps API']);
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
if (!$data || $data['status'] !== 'OK') {
wp_send_json_error(['message' => 'Invalid response from Google Maps API']);
}
$elements = $data['rows'][0]['elements'][0] ?? null;
if (!$elements || $elements['status'] !== 'OK') {
wp_send_json_error(['message' => 'No route found to postcode']);
}
// Distance in meters -> convert to kilometers (or miles if you prefer)
$distance_meters = $elements['distance']['value'];
$distance_km = round($distance_meters / 1000, 2);
wp_send_json_success(['distance' => $distance_km]);
}
Step 4: Enqueue Scripts and Localize AJAX URL and Nonce
Add this code to enqueue jQuery and localize the AJAX endpoint and nonce:
<?php
add_action('wp_enqueue_scripts', function() {
if (is_singular()) {
global $post;
if (has_shortcode($post->post_content, 'fluentform') &&
(strpos($post->post_content, 'id="6"') !== false || strpos($post->post_content, 'id=6') !== false)) {
wp_enqueue_script('jquery');
wp_localize_script('jquery', 'fluent_form_ajax', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('fluent_form_nonce'),
]);
}
}
});
Step 5: Test Your Form
- Go to your page with the form.
- Enter a postcode in the postcode field and move out of the input (blur event).
- The distance field should fill with the calculated distance from your fixed origin.
- The submit button becomes enabled.
- Submit the form.
- Check the received email or database entry to confirm the distance was submitted.