I have the following GeoDataFrames: accidents_c = collection of all accidents in austria as points, streets = roads in austria as a linestrings (open street map data) Both have the crs type epsg:3310
Now i want to match every accident to the nearest road. My first attempt was this:
def nearest_street(accident_point, streets):
row_canditates=streets.copy()
nearest_road = None
min_distance = None
row_canditates["distance_road"] = row_canditates.apply(lambda row: accident_point["geometry"].distance(row.geometry),axis=1)
min_distance = row_canditates["distance_road"].min()
min_road = row_canditates.loc[row_canditates["distance_road"] == min_distance]
nearest_road = min_road["osm_id"].values[0]
return nearest_road, min_distance
accidents_c["nearest_road"], accidents_c["distance_road"] = zip(*accidents_c.apply(nearest_street, streets=roads, axis=1))
This works but takes forever. So i was thinking about a way to make it faster by only including roads which are not more than 3000 meters away from the accident point. For this i used the buffer method. And did this:
def nearest_street(accident_point, streets):
row_canditates=streets.copy()
nearest_road = None
min_distance = None
buffered_accident = accident_point["geometry"].buffer(2000)
bounds = buffered_accident.bounds
x_min, x_max, y_min, y_max = buffered_accident.bounds
row_canditates=row_canditates.cx[x_min:x_max, y_min:y_max]
row_canditates["distance_road"] = row_canditates.apply(lambda row: accident_point["geometry"].distance(row.geometry),axis=1)
min_distance = row_canditates["distance_road"].min()
min_road = row_canditates.loc[row_canditates["distance_road"] == min_distance]
nearest_road = min_road["osm_id"].values[0]
return nearest_road, min_distance
accidents_c["nearest_road"], accidents_c["distance_road"] = zip(*accidents_c.apply(nearest_street, streets=roads, axis=1))
This works much faster but the results are worse. Differences are sometimes over 1000 meters between code a and code b. Where do you think is the problem in the code? Do you know any better method to limit the search for the nearest environment?