开发者

Store 3 nearest coordinates

开发者 https://www.devze.com 2023-02-28 08:42 出处:网络
I have an XML file that contains a number of points with their longitude and latitude. My python code at the moment gets the nearest point by simply looping through the XML file, finding the nearest,

I have an XML file that contains a number of points with their longitude and latitude.

My python code at the moment gets the nearest point by simply looping through the XML file, finding the nearest, in miles or whatever, then comparing it with the previous closest point. If its nearer then I assign the variable the value of this new poin开发者_开发百科t. So everything is working in that regard.

Now, what I want to do is actually store the closest 2 or 3 points. How do I go about doing this? The XML file isn't ordered by closest, and besides, the users location will change each time a request is made. Can I do this with an XML file or will I perhaps have to look into storing the data is SQL Server or MySQL?

Thanks for the help. PS, the sample code is available here if anyone is interested. This is part of a college project.


You should store in a list of tuples (for example) all the point pairs and their distances as you parse de xml file.

mypoints = [(distance12, x1, x2),...,(distancenm, xn, xm)]
mypoints.sort()
three_closer = mypoints[:3]

Adapting this to your code:

..............
mypoints = []
for row in rows:
     # Get coords for current record
     curr_coords = row.getAttribute("lat") + ',' + row.getAttribute("lng")
     # Get distance
     tempDistance = distance.distance(user_coords, curr_coords).miles
     mypoints.append((tempDistance, row))

mypoints.sort()
#the three closest points:
mythree_shorter = mypoints[0:3]
for distance, row in mythree_shorter:
    shortestStation = json.dumps(
                            {'number': row.getAttribute("number"),
                             'address': row.getAttribute("address"),
                             'lat': row.getAttribute("lat"),
                             'lng': row.getAttribute("lng"),
                             'open': row.getAttribute("open")},
                             sort_keys=True,
                             indent=4)
    save_in_some_way(shortestStation)   #maybe writing to a file?
..................


Here's a solution that will work for any number of points:

closest = points[:NUM_CLOSEST]
closest.sort()
for point in points[NUM_CLOSEST:]:
    if point.distance < closest[-1].distance:
        closest[-1] = point
        closest.sort()

Obviously, a bit pseudo-cody. The sort() calls will probably need an argument so they are sorted in a useful way, and you'll probably want a function to calculate the distance to replace the distance member.

0

精彩评论

暂无评论...
验证码 换一张
取 消