# Find the closest line to a polygon Python Rtree

I have a series of fields and roads I am trying to find the nearest road to each field. I want to add field to each of my polygons with the index/name/etc of the closest road.

Would this be the correct method to find the nearest road for each field?

Below is the code i am trying

So i have loaded my shapes and created an empty index.

``````fieldlyr = fiona.open(fields, 'r')
# search radius, i've changed sizes to make it large enough
areaft = 2500
index = rtree.index.Index()
``````

So i add my fields to the index?

``````for fid, feat in fieldlyr.items():
geometry = shape(feat['geometry'])
index.insert(fid, geometry.bounds)
``````

``````for feat in roadlyr:
geometry = shape(feat['geometry'])
geometry_buffered = geometry.buffer(areaft)
``````

Then i believe this will give me the lists of intersections?

``````fids = [int(i) for i in index.intersection(geometry_buffered.bounds)]
``````

How would i get road id A is nearest to polygon id 2 and so on.

is this even the correct method?

So it seems i was over complicating things.

this appears to work how i need it to. Just thought i would share in case anyone has a similar need or perhaps a better method

``````fieldlyr = fiona.open(fields, 'r')

# dont need the search radius/ buffer for near
index = rtree.index.Index()
``````

Correct on adding to index, this should be the road layer since i want to know which road is closest to an area

``````for fid, feat in roadlyr.items():
geom = shape(feat['geometry'])
index.insert(fid, geom.bounds)
``````

So i had the roads and area reveresed in my original question

``````for afeat in fieldlyr:
geometry = shape(afeat['geometry'])

fids = [int(i) for i in idx.nearest(geometry.bounds)]
``````

And to view the matches

``````print (str(afeat['id']) + " area is nearest to line "+ str(fids))
``````

As if now, this seems to work

• Just remember that you're finding the bounding boxes nearest each other. If you need an exact result you'll want to follow up the rtree query with a shapely `object.distance(other)` routine – mikewatt Nov 19 '19 at 19:11