问题
I'm Using Python and done something with the following, Given a list of tuple coordinates, find the nearest coord to a specified coord (Google Maps Coords)).
But not accurate nearest coordinates compared with google maps on my code. Please help me.
Here is my code
def find_coords(c, l):
tmp_list = []
(x,y) = l[0]
for (a,b) in l[1:]:
if (x-c[0])**2 + (y-c[1])**2 > (a-c[0])**2 + (b-c[1])**2:
(x,y) = (a,b)
tmp_list.append((x,y))
return tmp_list
ccoordinate_list = [(11.6702634, 72.313323), (11.6723698, 78.114523), (31.67342698, 78.465323), (12.6702634, 72.313323), (12.67342698, 75.465323)]
coordinate = (11.6723698, 78.114523)
while coordinate_list[1:]:
coordinate_list = find_coords(coordinate, coordinate_list)
回答1:
If you want to find the nearest geo coord you should use specific geo-coordinate structures (please see geopy ). In this case, I propose the following solution:
import geopy
import geopy.distance
# your data
ccoordinate_list = [(11.6702634, 72.313323), (11.6723698, 78.114523), (31.67342698, 78.465323), (12.6702634, 72.313323), (12.67342698, 75.465323)]
coordinate = (11.6723698, 78.114523)
# the solution
pts = [ geopy.Point(p[0],p[1]) for p in ccoordinate_list ]
onept = geopy.Point(coordinate[0],coordinate[1])
alldist = [ (p,geopy.distance.distance(p, onept).km) for p in pts ]
nearest_point = min(alldist, key=lambda x: (x[1]))[0] # or you can sort in by distance with sorted function
Please note that Euclidean metric (as in your example) may be incorrect on the globe.
回答2:
The reason your results differ from Google's is that you are using the distance formula for the plane (Pythagoras' Theorem), but the Earth is not a flat plane, and latitude & longitude are not a Cartesian coordinate system.
That flat formula is ok for small distances in regions that are not too close to the poles. For much better results you can use the great circle distance formula.
For even more accuracy, you need to account for the fact that the Earth is not a perfect sphere: it is somewhat flattened at the poles, making it an ellipsoid (almost). To calculate distances on an ellipsoid you can use Vincenty's formulae. Even those formulae aren't perfectly accurate, but the error is quite small.
Update
Vincenty's formulae are not recommended for modern use. They date from the 1970s, and were intended for use on the desk calculators of the time. We now have access to much better computing technology, and there are better ways to calculate distances on the ellipsoid. I recommend C. F. F. Karney's geographiclib. Dr Karney is a major contributor to the Wikipedia articles on geodesics, in particular Geodesics on an ellipsoid, as I mentioned in this answer which has a brief demo of using geographiclib
to compute the distance between 2 points on the WGS84 reference ellipsoid, as well as a link to a more extensive example.
来源:https://stackoverflow.com/questions/28367177/python-given-a-list-of-tuple-coordinates-find-the-nearest-coord-to-a-specifie