~ihabunek/triglav

ref: 59770cd8e4a5d160b1d667b4974cb0682383efb9 triglav/lib/triglav/haversine.ex -rw-r--r-- 643 bytes
59770cd8Ivan Habunek Add haversine geo distance calculation 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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