   # Efficient and speedy logic to find distance between multiple latitude and longitude in java?

119 views

I have a product table which I maintain product details and location in latitude and longitude of each product. Normally I have a simple search based on name, price etc.

Now I going to implement a search nearby location. For that I found some logic for finding distance between two latitude and longitude.

But my scenario is I have more than 10,000 products, each search I wants to find distance between my location with 10,000 product is much more complicated.

Is there any simple way to find?

Note : My location is Dynamic. posted Dec 5, 2014

+1 vote

Basically its not a Java problem what you need an algo which can provide you the distance between two points represented by the Longitude and Latitude.

The logic would be as follows-
1. Find your longitude and latitude (I hope you already have this) say point A.
2. Find the distance between you and all the products i.e. between A and all the products, say d.
3. Sort all the products based on D
4. You are good to go.

Formula for the distance

``````a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 ⋅ atan2( √a, √(1−a) )
d = R ⋅ c
``````

where φ is latitude, λ is longitude, R is earth’s radius (mean radius = 6,371km);
note that angles need to be in radians to pass to trig functions!

JavaScript Code
var R = 6371; // km

var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c; answer Dec 6, 2014
Similar Questions
+1 vote

Given a million list of co-ordinates in the form of longitude and latitude just as Google maps. How will you print closest k cities to a given location .

Given a string and two words which are present in the string, find the minimum distance between the words

Example:
"the brown quick frog quick the", "the" "quick"
Min Distance: 1

"the quick the brown quick brown the frog", "the" "brown"
Min Distance: 2