DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Mocking Kafka for Local Spring Development
  • Why DDoS Protection Is an Architectural Decision for Developers
  • Data Contracts as the "Circuit Breaker" for Model Reliability
  • Your AI Agent Tests Are Passing, But Your Agent Is Still Broken
  1. DZone
  2. Coding
  3. Languages
  4. Scala: Calculating the Distance Between Two Locations

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.

By 
Shivansh Srivastava user avatar
Shivansh Srivastava
·
Dec. 15, 17 · Tutorial
Likes (5)
Comment
Save
Tweet
Share
21.7K Views

Join the DZone community and get the full member experience.

Join For Free

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})}

Where

  • hav is the haversine function: 
\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


Distance

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 (programming language)

Published at DZone with permission of Shivansh Srivastava. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook