~ihabunek/triglav

59770cd8e4a5d160b1d667b4974cb0682383efb9 — Ivan Habunek 3 months ago 3a62b8f
Add haversine geo distance calculation
1 files changed, 22 insertions(+), 0 deletions(-)

A lib/triglav/haversine.ex
A lib/triglav/haversine.ex => lib/triglav/haversine.ex +22 -0
@@ 0,0 1,22 @@
defmodule Triglav.Haversine do
  @radius 6372.8

  @type longitude :: float()
  @type latitude :: float()
  @type coordinates :: {longitude(), latitude()}

  @spec distance(coordinates(), coordinates()) :: float()
  def distance({lon1, lat1}, {lon2, lat2}) do
    lat1 = deg_to_rad(lat1)
    lat2 = deg_to_rad(lat2)
    lon1 = deg_to_rad(lon1)
    lon2 = deg_to_rad(lon2)

    dlat = :math.sin((lat2 - lat1) / 2)
    dlon = :math.sin((lon2 - lon1) / 2)
    a = :math.pow(dlat, 2) + :math.pow(dlon, 2) * :math.cos(lat1) * :math.cos(lat2)
    @radius * 2 * :math.asin(:math.sqrt(a))
  end

  defp deg_to_rad(deg), do: deg * :math.pi() / 180
end