Calculated Fields Form Blog

Tips and cases of use for a successful WordPress website with calculated forms.

Blog / Cases of use for a delivery project, transportation or any other project based on distance calculation with Bing Maps

Cases of use for a delivery project, transportation or any other project based on distance calculation with Bing Maps

Calculating the price of transportation service based on distance.


In a previous post we implemented this same project using the DISTANCE operation of the "Distance Operations" module.

Cases of use for a delivery project, transportation or any other project based on distance calculation

The DISTANCE operation is the most efficient and simplest way to obtain the distance between postal addresses. However, it relies on Google APIs (namely the Geocoding and Distance Matrix APIs) which unfortunately are not free and require a valid API Key.

Fortunately, the Calculated Fields Form plugin is a powerful tool with many possibilities, and there are APIs such as BingMaps that also offer distance calculations.

Project description

We will create a form for moving company that calculates the service prices based on the distance from the origin address to destination: $1.05 per mile.

Moving companies calculate the price considering other factors as well. But for simplicity we'll focus on distance.

Form's fields

Our form will include three fields:

  • A "Single Line Text" field for the origin address (fieldname1)
  • A second "Single Line Text" field for destination address (fieldname2)
  • The calculated field to get the distance between address, and multiply it by the factor mentioned above ($1.05)

Form Structure

The equation

To do this, our calculated field equation will call a server-side equation, which I will include below, that queries the distance to the BingMaps API.

PREC(SERVER_SIDE('distance', fieldname1, fieldname2)*1.05, 2)

SERVER_SIDE is an operation included by the "CFF - SERVER SIDE Equations" add-on (distributed with the Developer and Platinum versions of the Calculated Fields Form plugin) to call server-side equations from calculated fields. Its first parameter would be the name of the server-side equation, and the rest of the parameters would be the parameters required by the server-side equation. In this case, the name of the server-side equation is "distance", and I pass as second and third parameters the addresses entered by the user through the fields fieldname1 and fieldname2.

The PREC operation allows you to round numbers by specifying the number of decimal places in the result. Since the result of the equation is a currency value, it must be rounded to two decimal places.

To implement the server-side equation, you must first activate the "CFF - SERVER-SIDE Equations" add-on. In order to activate the add-on, go to the menu option "Calculated Fields Form > Addons", check the box "CFF - SERVER-SIDE Equations", and press the "Activate/Deactivate Addons" button.

The action enables a code editor on the plugin settings page to enter the server-side equations. Please do not edit the code block above the "/********* INCLUDE YOUR CODE FROM HERE **************/" line.

Please, copy the following piece of code and paste it in the server-side equations editor:


$GLOBALS['SERVER_SIDE_EQUATIONS']['distance'] = function ( $address_a, $address_b ){
  $key = 'Your BingMaps API Key';

  $address_a = sanitize_text_field( wp_unslash($address_a));
  $address_b = sanitize_text_field( wp_unslash($address_b));
  $result = '';

  if(!empty($address_a) && !empty($address_b)){
    try{
       $response = wp_remote_get('http://dev.virtualearth.net/REST/v1/Locations?addressLine='.urlencode(strtolower($address_a)).'&maxResults=1&key='.$key);
       if(!is_wp_error($response)){
         $data = json_decode( wp_remote_retrieve_body( $response ), true);
         $coord_a = $data['resourceSets'][0]['resources'][0]['point']['coordinates'];

         $response = wp_remote_get('http://dev.virtualearth.net/REST/v1/Locations?addressLine='.urlencode(strtolower($address_b)).'&maxResults=1&key='.$key);
         if(!is_wp_error($response)){
           $data = json_decode( wp_remote_retrieve_body( $response ), true);
           $coord_b = $data['resourceSets'][0]['resources'][0]['point']['coordinates'];

           $response = wp_remote_get('https://dev.virtualearth.net/REST/v1/Routes/DistanceMatrix?origins='.$coord_a[0].','.$coord_a[1].'&destinations='.$coord_b[0].','.$coord_b[1].'&distanceUnit=mi&travelMode=driving&key='.$key);
           if(!is_wp_error($response)){
             $data = json_decode( wp_remote_retrieve_body( $response ), true);
             $result = $data['resourceSets'][0]['resources'][0]['results'][0]['travelDistance'];
           }
         }
       }
    }  catch( Exception $err) {}

  }
  return $result;
};

The server equation calls the API three times. The first two times to obtain the coordinates corresponding to the addresses, needed to calculate the distance in the third API call. Note you can pass the distanceUnit parameter as "km" to get the distance in kilometers, and the travelMode as driving, walking, or transit to vary travel mode.

In the server-side equation, you must replace the text "Your BingMaps API key" with your corresponding BingMaps API key. To get it, create an account on the www.bingmapsportal.com website (it's free), and generate your API Key. Please read the following BingMaps tutorial on how to generate an API Key:

https://www.microsoft.com/en-us/maps/create-a-bing-maps-key

Equation's result Equation result