217 words, 2 min read

When working with GPS data, comparing two coordinates directly is unreliable. Due to natural precision loss and device variations, even two readings from the same spot can differ slightly in latitude and longitude. Instead of checking for equality, you should compare their distance — for example, ensuring they’re within a few meters of each other.

Here’s a simple way to do this in Elixir using the Haversine formula, which calculates the great-circle distance between two points on Earth.

defmodule GeoUtils do
@earth_radius 6_371_000 # in meters
def same_location?([lat1, lon1], [lat2, lon2], threshold_meters \\ 50) do
distance = haversine_distance(lat1, lon1, lat2, lon2)
distance <= threshold_meters
end
defp haversine_distance(lat1, lon1, lat2, lon2) do
lat1 = deg2rad(lat1)
lon1 = deg2rad(lon1)
lat2 = deg2rad(lat2)
lon2 = deg2rad(lon2)
dlat = lat2 - lat1
dlon = lon2 - lon1
a =
:math.pow(:math.sin(dlat / 2), 2) +
:math.cos(lat1) * :math.cos(lat2) * :math.pow(:math.sin(dlon / 2), 2)
c = 2 * :math.atan2(:math.sqrt(a), :math.sqrt(1 - a))
@earth_radius * c
end
defp deg2rad(deg), do: deg * :math.pi / 180
end

Example usage:

loc1 = [51.123271, 3.676921]
loc2 = [51.123275, 3.676927]
GeoUtils.same_location?(loc1, loc2)
# true (they’re within 50 meters)

This approach gives you a reliable, real-world comparison between GPS points.

You can easily tweak the threshold_meters argument depending on how strict your definition of “same location” needs to be.