Skip to content Skip to sidebar Skip to footer

Calculate Distance Between A Location And A List Of Locations

I have a list of locations , following this pattern: [1] = {lat = -40.2452, longitude = -76.2489}, [2] = {lat = -40.2452, longitude = -76.2489}, [3] = {lat = -40.2452, longitude =

Solution 1:

Basically you have to check each and every point, no other option. The distance formula (Haversine) is indeed slow, since it uses few trigonometric functions. What you actually want is to plot a circle around your point, whose radius R is the distance, and check for each point if it's inside that circle: enter image description here

The problem is that your point are given as (lat, long) pair, not (x,y) pair, so you can't use "regular" trigonometric methods, like the circle's equation. Instead, you have to find a square that bounds that circle. Go 90 degrees to the north and south, find the upper and lower longitudes of that square. Do the same to rhe east and west, find the upper and lower latitudes: enter image description here

Now you can check for each point if it's inside the box, and you can do it easily with simple comparsions:

if lon > lon1 and lon < lon2
   and lat > lat2 and lat < lat1

which is really computionally cheap. The only problem is with points that are inside the blue area: enter image description here

They are inside the square but not inside the circle, so you'll have to use the Haversine formula for them. If most of your points are not in the square, this method will save you time, because eliminating them is pretty easy.

Solution 2:

If you are on Android then you can use the "distanceBetween" method of the Location class. This method has it's implementation in Java (you can do a loop to test the distance between your location and the location list elements), so if you want higher performance you should do it natively (NDK). If you do it natevely you should pass the complete list to the native method and not one by one because the context change between the virtual and the native environment can be costly.

Post a Comment for "Calculate Distance Between A Location And A List Of Locations"