Program for distance between two points on earth
Last Updated :
13 Feb, 2023
Given latitude and longitude in degrees find the distance between two points on the earth.

Image Source : Wikipedia
Examples:
Input : Latitude 1: 53.32055555555556
Latitude 2: 53.31861111111111
Longitude 1: -1.7297222222222221
Longitude 2: -1.6997222222222223
Output: Distance is: 2.0043678382716137 Kilometers
Problem can be solved using Haversine formula:
The great circle distance or the orthodromic distance is the shortest distance between two points on a sphere (or the surface of Earth). In order to use this method, we need to have the co-ordinates of point A and point B.The great circle method is chosen over other methods.
First, convert the latitude and longitude values from decimal degrees to radians. For this divide the values of longitude and latitude of both the points by 180/pi. The value of pi is 22/7. The value of 180/pi is approximately 57.29577951. If we want to calculate the distance between two places in miles, use the value 3, 963, which is the radius of Earth. If we want to calculate the distance between two places in kilometers, use the value 6, 378.8, which is the radius of Earth.
Find the value of the latitude in radians:
Value of Latitude in Radians, lat = Latitude / (180/pi) OR
Value of Latitude in Radians, lat = Latitude / 57.29577951
Find the value of longitude in radians:
Value of Longitude in Radians, long = Longitude / (180/pi) OR
Value of Longitude in Radians, long = Longitude / 57.29577951
Get the co-ordinates of point A in terms of latitude and longitude. Use the above conversion method to convert the values of latitude and longitude in radians. I will call it as lat1 and long1. Do the same for the co-ordinates of Point B and get lat2 and long2.
Now, to get the distance between point A and point B use the following formula:
Distance, d = 3963.0 * arccos[(sin(lat1) * sin(lat2)) + cos(lat1) * cos(lat2) * cos(long2 - long1)]
The obtained distance, d, is in miles. If you want your value to be in units of kilometers, multiple d by 1.609344.
d in kilometers = 1.609344 * d in miles
Thus you can have the shortest distance between two places on Earth using the great circle distance approach.
C++
// C++ program to calculate Distance
// Between Two Points on Earth
#include <bits/stdc++.h>
using namespace std;
// Utility function for
// converting degrees to radians
long double toRadians(const long double & degree)
{
// cmath library in C++
// defines the constant
// M_PI as the value of
// pi accurate to 1e-30
long double one_deg = (M_PI) / 180;
return (one_deg * degree);
}
long double distance(long double lat1, long double long1,
long double lat2, long double long2)
{
// Convert the latitudes
// and longitudes
// from degree to radians.
lat1 = toRadians(lat1);
long1 = toRadians(long1);
lat2 = toRadians(lat2);
long2 = toRadians(long2);
// Haversine Formula
long double dlong = long2 - long1;
long double dlat = lat2 - lat1;
long double ans = pow(sin(dlat / 2), 2) +
cos(lat1) * cos(lat2) *
pow(sin(dlong / 2), 2);
ans = 2 * asin(sqrt(ans));
// Radius of Earth in
// Kilometers, R = 6371
// Use R = 3956 for miles
long double R = 6371;
// Calculate the result
ans = ans * R;
return ans;
}
// Driver Code
int main()
{
long double lat1 = 53.32055555555556;
long double long1 = -1.7297222222222221;
long double lat2 = 53.31861111111111;
long double long2 = -1.6997222222222223;
// call the distance function
cout << setprecision(15) << fixed;
cout << distance(lat1, long1,
lat2, long2) << " K.M";
return 0;
}
// This code is contributed
// by Aayush Chaturvedi
Java
// Java program to calculate Distance Between
// Two Points on Earth
import java.util.*;
import java.lang.*;
class GFG {
public static double distance(double lat1,
double lat2, double lon1,
double lon2)
{
// The math module contains a function
// named toRadians which converts from
// degrees to radians.
lon1 = Math.toRadians(lon1);
lon2 = Math.toRadians(lon2);
lat1 = Math.toRadians(lat1);
lat2 = Math.toRadians(lat2);
// Haversine formula
double dlon = lon2 - lon1;
double dlat = lat2 - lat1;
double a = Math.pow(Math.sin(dlat / 2), 2)
+ Math.cos(lat1) * Math.cos(lat2)
* Math.pow(Math.sin(dlon / 2),2);
double c = 2 * Math.asin(Math.sqrt(a));
// Radius of earth in kilometers. Use 3956
// for miles
double r = 6371;
// calculate the result
return(c * r);
}
// driver code
public static void main(String[] args)
{
double lat1 = 53.32055555555556;
double lat2 = 53.31861111111111;
double lon1 = -1.7297222222222221;
double lon2 = -1.6997222222222223;
System.out.println(distance(lat1, lat2,
lon1, lon2) + " K.M");
}
}
// This code is contributed by Prasad Kshirsagar
Python3
# Python 3 program to calculate Distance Between Two Points on Earth
from math import radians, cos, sin, asin, sqrt
def distance(lat1, lat2, lon1, lon2):
# The math module contains a function named
# radians which converts from degrees to radians.
lon1 = radians(lon1)
lon2 = radians(lon2)
lat1 = radians(lat1)
lat2 = radians(lat2)
# Haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
c = 2 * asin(sqrt(a))
# Radius of earth in kilometers. Use 3956 for miles
r = 6371
# calculate the result
return(c * r)
# driver code
lat1 = 53.32055555555556
lat2 = 53.31861111111111
lon1 = -1.7297222222222221
lon2 = -1.6997222222222223
print(distance(lat1, lat2, lon1, lon2), "K.M")
C#
// C# program to calculate
// Distance Between Two
// Points on Earth
using System;
class GFG
{
static double toRadians(
double angleIn10thofaDegree)
{
// Angle in 10th
// of a degree
return (angleIn10thofaDegree *
Math.PI) / 180;
}
static double distance(double lat1,
double lat2,
double lon1,
double lon2)
{
// The math module contains
// a function named toRadians
// which converts from degrees
// to radians.
lon1 = toRadians(lon1);
lon2 = toRadians(lon2);
lat1 = toRadians(lat1);
lat2 = toRadians(lat2);
// Haversine formula
double dlon = lon2 - lon1;
double dlat = lat2 - lat1;
double a = Math.Pow(Math.Sin(dlat / 2), 2) +
Math.Cos(lat1) * Math.Cos(lat2) *
Math.Pow(Math.Sin(dlon / 2),2);
double c = 2 * Math.Asin(Math.Sqrt(a));
// Radius of earth in
// kilometers. Use 3956
// for miles
double r = 6371;
// calculate the result
return (c * r);
}
// Driver code
static void Main()
{
double lat1 = 53.32055555555556;
double lat2 = 53.31861111111111;
double lon1 = -1.7297222222222221;
double lon2 = -1.6997222222222223;
Console.WriteLine(distance(lat1, lat2,
lon1, lon2) + " K.M");
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
PHP
<?php
function twopoints_on_earth($latitudeFrom, $longitudeFrom,
$latitudeTo, $longitudeTo)
{
$long1 = deg2rad($longitudeFrom);
$long2 = deg2rad($longitudeTo);
$lat1 = deg2rad($latitudeFrom);
$lat2 = deg2rad($latitudeTo);
//Haversine Formula
$dlong = $long2 - $long1;
$dlati = $lat2 - $lat1;
$val = pow(sin($dlati/2),2)+cos($lat1)*cos($lat2)*pow(sin($dlong/2),2);
$res = 2 * asin(sqrt($val));
$radius = 3958.756;
return ($res*$radius);
}
// latitude and longitude of Two Points
$latitudeFrom = 19.017656 ;
$longitudeFrom = 72.856178;
$latitudeTo = 40.7127;
$longitudeTo = -74.0059;
// Distance between Mumbai and New York
print_r(twopoints_on_earth( $latitudeFrom, $longitudeFrom,
$latitudeTo, $longitudeTo).' '.'miles');
// This code is contributed by akash1295
// https://www.geeksforgeeks.org/user/akash1295/contributions/
?>
JavaScript
<script>
// JavaScript program to calculate Distance Between
// Two Points on Earth
function distance(lat1,
lat2, lon1, lon2)
{
// The math module contains a function
// named toRadians which converts from
// degrees to radians.
lon1 = lon1 * Math.PI / 180;
lon2 = lon2 * Math.PI / 180;
lat1 = lat1 * Math.PI / 180;
lat2 = lat2 * Math.PI / 180;
// Haversine formula
let dlon = lon2 - lon1;
let dlat = lat2 - lat1;
let a = Math.pow(Math.sin(dlat / 2), 2)
+ Math.cos(lat1) * Math.cos(lat2)
* Math.pow(Math.sin(dlon / 2),2);
let c = 2 * Math.asin(Math.sqrt(a));
// Radius of earth in kilometers. Use 3956
// for miles
let r = 6371;
// calculate the result
return(c * r);
}
// Driver code
let lat1 = 53.32055555555556;
let lat2 = 53.31861111111111;
let lon1 = -1.7297222222222221;
let lon2 = -1.6997222222222223;
document.write(distance(lat1, lat2,
lon1, lon2) + " K.M");
</script>
Output2.004367838271690 K.M
Time Complexity: O(logn) as inbuilt sqrt function has been used
Auxiliary Space: O(1)
Please suggest if someone has a better solution which is more efficient in terms of space and time.Reference: Wikipedia
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem