Android – Distance between two points on the Earth

When working with geo data, it is sometimes necessary to calculate the distance between two geolocations on the surface of the Earth. This is also a problem where I came upon and I will therefore describe my findings in this post.

Working in this area means that one has to brush of his trigonometry skills. But luckily there are some good resources on the web, that explain the theory perfectly. The formula you need is the haversine formula, which gets its name from the use of the haversine function:
haversin(/Theta) = sin^2(/Theta / 2) .

The haversine formula is:

R = earth’s radius (mean radius = 6367.45 km)

/Delta lat = lat_2 - lat_1

/Delta long = long_2 - long_1

a = sin^2(/Delta lat / 2) + cos(lat_1)cos(lat_2)sin^2(/Delta long / 2)

c = 2 atan2(/sqrt{a}, /sqrt{(1-a)})

d = Rc

Here the distance d in kilometers will be calculated based on the latitudes and longitudes of the two points on the earth, expressed in radians. To convert from degrees to radians, simply multiply the value in degrees by /pi / 180 . The atan2() function is a function implemented in many computer languages and is a variation on the arctangent function.

The error of this formula in calculating distances is about 0.1% and mostly due to the fact that the Earth is not a perfect sphere (see the resources below for a more in-depth discussion). Also numerical rounding errors can occur, but this is mainly an issue when the two locations are very nearly antipodal (on opposite sites of the Earth), which is generally not something you will use very often.

But enough now of the theoretics, I will show how to put this to a practical use. The code to calculate the distance between two points can be expressed in Java code as:

One thing you need to make sure, is that the latitude and longitude are expressed in radians (see above).
Put this code into a method and you are done.

This post is based on a few web resources, that will give a bit more information on distance calculations. There is a nice wikipedia article on the Haversine formula. Here and here you can find a bit more information on calculating distances on a sphere.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值