Whilst being an amazingly powerful tool, Tableau Prep isn't exactly known for its spatial handling. Thanks to a Preppin Data challenge (2023: Week 11 by Jenny Martin) however, I understood the way to calculate the closest distance in miles between two locations, which I thought I'd share in this blog. This will done be using the Haversine Formula.
1. Data Preparation
Start by importing your dataset into Tableau Prep. This dataset should contain latitude and longitude coordinates for the locations you want to analyze. If these values are in decimal degrees format, you can use the below step to convert them to radians.
2. Convert Coordinates to Radians
The Haversine formula requires latitude and longitude values in radians. To achieve this, create calculated fields in Tableau Prep for the radian conversions:
- Radian Latitude = [Latitude] * (π / 180)
- Radian Longitude = [Longitude] * (π / 180)
For my dataset, I needed to convert Address and Branch latitudes and longitudes:
3. Applying the Haversine Formula
Now that we have the coordinates in radians, we can calculate the closest distance using the Haversine formula. Create another calculated field that implements this formula:
- Distance (miles) = 3963 * acos((sin(lat 1) * sin(lat 2)) + cos(lat 1) * cos(lat 2) * cos(long 2 – long 1))
When I tried to implement this formula, I was given an error for the part "cos(long 2 – long 1)". I believe tableau prep didn't like the subtraction within the cos function so I brought this part into a separate calculated field.
And we're all done! This powerful technique, which has been made accessible through Preppin Data and Jenny Martin, can be incredibly valuable for anyone dealing with geographical data.