calculate distance between a location and a list of locations

天涯浪子 提交于 2019-12-13 07:23:00

问题


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 = -76.2489},
[4] = {lat = -40.2452, longitude = -76.2489}

and a localition

location = {lat = -40.2452, longitude = -76.2489}

and I want to calculate Which of the locations this Within the distance.

I found a formula that calculates the distance between two points.

but if this list is big!

is there any faster way?

or you can go through the list in a loop ?

FOR LOCATION IN LISTLOCATION DO
    IF GETDISTANCE(LOCATION, LOCATION2) <= DISTANCE
        SAVE THIS LOCATION
    END
END

These values are a example


回答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:

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:

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:

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.




回答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.



来源:https://stackoverflow.com/questions/37664500/calculate-distance-between-a-location-and-a-list-of-locations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!