Over a million developers have joined DZone.

Scala: Calculating the Distance Between Two Locations

DZone 's Guide to

Scala: Calculating the Distance Between Two Locations

Time to put your trigonometry hats on to see how you can calculate the distance between coordinates on the globe in Scala.

· Java Zone ·
Free Resource

Hey, folks!

Recently I came along a use case where I needed to find out the distance between two location coordinates. In today’s blog, we are going to solve this problem by implementing the haversine formula in Scala.

Just FYI, the haversine formula determines the great-circle distance between two points on a sphere given their longitudes and latitudes. Important in navigation, it is a special case of a more general formula in spherical trigonometry, the law of haversines, that relates the sides and angles of spherical triangles.

Law of Haversines

\operatorname {hav} (c)=\operatorname {hav} (a-b)+\sin(a)\sin(b)\,\operatorname {hav} (C).

Haversine Formula

For any two points on a sphere, the haversine of the central angle between them is given by:

{\displaystyle \operatorname {hav} \left({\frac {d}{r}}\right)=\operatorname {hav} (\varphi _{2}-\varphi _{1})+\cos(\varphi _{1})\cos(\varphi _{2})\operatorname {hav} (\lambda _{2}-\lambda _{1})}


\operatorname {hav} (\theta )=\sin ^{2}\left({\frac {\theta }{2}}\right)={\frac {1-\cos(\theta )}{2}}
  • d is the distance between the two points (along a great circle of the sphere; see spherical distance).
  • r is the radius of the sphere.
  • φ1, φ2: latitude of point 1 and latitude of point 2, in radians.
  • λ1, λ2: longitude of point 1 and longitude of point 2, in radians.

So, without wasting any more time, let’s get started with the code.

case class Location(lat: Double, lon: Double)

trait DistanceCalcular {
    def calculateDistanceInKilometer(userLocation: Location, warehouseLocation: Location): Int

class DistanceCalculatorImpl extends DistanceCalcular {

    private val AVERAGE_RADIUS_OF_EARTH_KM = 6371

    override def calculateDistanceInKilometer(userLocation: Location, warehouseLocation: Location): Int = {
        val latDistance = Math.toRadians(userLocation.lat - warehouseLocation.lat)
        val lngDistance = Math.toRadians(userLocation.lon - warehouseLocation.lon)
        val sinLat = Math.sin(latDistance / 2)
        val sinLng = Math.sin(lngDistance / 2)
        val a = sinLat * sinLat +
        (Math.cos(Math.toRadians(userLocation.lat)) *
            Math.cos(Math.toRadians(warehouseLocation.lat)) *
            sinLng * sinLng)
        val c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
        (AVERAGE_RADIUS_OF_EARTH_KM * c).toInt

new DistanceCalculatorImpl().calculateDistanceInKilometer(Location(10, 20), Location(40, 20))

As you can see, this is the Scala implementation of the haversine formula, and it computes the distance in a pretty simple way.

You can see the compiled version of the code here on Scala Fiddle:

WhatsApp Image 2017-12-01 at 1.30.31 PM

You can also verify your output from here: National Hurricane Center


They are approximately the same. Hence, in this way, we can get the distance between two locations.

If you have any queries, you can contact me here or on twitter:@shiv4nsh

If you liked it, share it with peers!

Just one more thing, we are developing a community of developers and college graduates to help others avoid the same problems we did in our careers. So, if you like the idea and want to be a part of this movement, come and join us: InternityFoundation.

scala ,location data ,java ,distance ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}