Measure Distance Between Two Points Using Latitude And Longitude In Java

In this instructional exercise, you will learn how to calculate the distance between the two points using latitude and longitude in Java. In many problems, you have to calculate the distance between the two points using coordinates.

Distance Between Two places using Latitude and Longitude in Java

For calculating the distance between two points you will be given with the two coordinates to calculate the distance.
If you don’t know how to get the distance between coordinates then you are at the right place.
Let’s see how to write the code in java to find the distance between coordinates.

You can do it in two ways:
One way is to simply include static inputs means to take coordinates input that will not change throughout the program,
Another way is to take inputs from the user with the help of the Scanner class.

Here you will learn to find the distance between two points using the second method:-

At first, you have to import the Scanner as well as a Math package.

You can add it by simply writing:-

import java.util.Scanner;
import java.lang.Math.*;

Here is the complete code which will help you to achieve your goal:

import java.util.Scanner;
impoprt java.lang.Math.*;
class Distance
        public static void main(String args[])
           int lat1,lat2;  
           int lon1,lon2;
           double distance;
           Scanner sc=new Scanner(;
           System.out.println("enter one point i.e., lat1");
           System.out.println("enter lon1 point");
           System.out.println("enter lat2 point");
           System.out.println("enter lon2 point");
           distance=Math.sqrt((lat2-lat1)*(lat2-lat1) + (lon2-lon1)*(lon2-lon1));
           System.out.println("distancebetween two points is:"+distance);

The output:-

enter one point i.e.,lat1 5
enter lon1 point 3
enter lat2 point 2
enter lon2 point 3
distancebetween the two points is 3.0

Also read:

Leave a Reply

Your email address will not be published. Required fields are marked *