Haversine formula

For general Flowcode discussion that does not belong in the other sections.
Post Reply
viktor_au
Posts: 55
http://meble-kuchenne.info.pl
Joined: Wed Jul 12, 2023 7:09 am
Has thanked: 8 times
Been thanked: 19 times

Haversine formula

Post by viktor_au »

Hi
Wonder if anybody work with the gps distance calculation.
Any suggestions how to implement the Haversine formula?
Thanks.

chipfryer27
Valued Contributor
Posts: 1767
Joined: Thu Dec 03, 2020 10:57 am
Has thanked: 391 times
Been thanked: 599 times

Re: Haversine formula

Post by chipfryer27 »

Hi Viktor

Whilst not actually doing it myself I did earmark this site as it gave many different ways to calculate, and also mentions a TRS-80 being used to calculate (my second computer)

https://www.movable-type.co.uk/scripts/latlong.html

Might be of some interest.

I found a lot of sites "scary" with their equations, but it isn't too difficult really and the above site also has some excel formulas.

Regards

medelec35
Matrix Staff
Posts: 2190
Joined: Wed Dec 02, 2020 11:07 pm
Has thanked: 664 times
Been thanked: 742 times

Re: Haversine formula

Post by medelec35 »

Hi Victor.
This is what I found:
Haversine Formula - Simple Explanation
The Haversine formula calculates the distance between two points on Earth using their latitude and longitude coordinates. It accounts for Earth being a sphere (roughly), not flat.
What it does: Given two GPS coordinates (lat1, lon1) and (lat2, lon2), it tells you the straight-line distance across Earth's surface.
The Formula Simplified
The formula works in steps:

Calculate the differences in latitude and longitude
Apply sine functions to account for Earth's curvature
Use Earth's radius (6371 km) to convert to actual distance

Implementation in Flowcode
Here's how to break it down into Flowcode calculation icons:
Step 1: Convert degrees to radians
lat1_rad = lat1 × π / 180
lon1_rad = lon1 × π / 180
lat2_rad = lat2 × π / 180
lon2_rad = lon2 × π / 180

Step 2: Calculate differences
dlat = lat2_rad - lat1_rad
dlon = lon2_rad - lon1_rad

Step 3: Haversine calculation
a = sin(dlat/2)² + cos(lat1_rad) × cos(lat2_rad) × sin(dlon/2)²
c = 2 × atan2(√a, √(1-a))
distance = 6371 × c // Result in kilometers

In Flowcode Calculation Icons:
Use separate calculation icons for each step
Store intermediate results in float variables
Use the built-in sin(), cos(), sqrt() and atan() functions

You can then use the link that chipfryer27 posted for testing the formula works.
If will be best if you use floats for the constants, e.g. instead of 2 use 2.0
Martin

Post Reply