Search code examples
pythonxmlgpscoordinatesgeopy

Store 3 nearest coordinates


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 point. 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.


Solution

  • 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?
    ..................