How to determine 4 nearest adjacent points in grid database around given latitude and longitude using python How to determine 4 nearest adjacent points in grid database around given latitude and longitude using python sqlite sqlite

How to determine 4 nearest adjacent points in grid database around given latitude and longitude using python


def find_adjacent_coords(db, lat, lon, step=0.041667):    """Find coords that are in a +/- step range of lat, lon."""    #XXX disregard values near +/- 90 latitude, +/- 180 longitude    coords_range = lat-step, lat+step, lon-step, lon+step    return db.execute("""select lat, lon from coords where lat > ? and lat < ? andlon > ? and lon < ?""", coords_range).fetchall()

full example with rtree index

Note: this code doesn't include boundaries.

For very efficient range queries if there are millions of coordinates you might need SQLite R-Tree index.

For 1000000 entries the above approach takes ~0.16 seconds, but the function that uses rtree requires less than 1ms. For 10000 entries it is 800 µs vs. 20 µs for rtree-based solution for the data from the test. DISCLAIMER: The numbers are for the code I've posted that I run on my machine.