Wrong Distance Found When Finding Distance To Nearest Edge In Osmnx
Code Hello I'm trying to find the distance to the nearest edge, in meters, using the OSMNx (OpenStreetMap + NetworkX) package. This is my code: def main(): lat = 51.217309 lon = 4
Solution 1:
I was able to solve this by changing the Ox.Point function. I wrote a new function to calculate the haversine distance to each coordinate in the LineString object.
from haversine import haversine, Unit
defclosest_point_on_haversine(point,edge):
closest_point = Nonefor c in edge[0].coords:
if closest_point == None:
closest_point = haversine(tuple(reversed(point)), c, unit='m')
else:
if haversine(tuple(reversed(point)), c, unit='m') < closest_point:
closest_point = haversine(tuple(reversed(point)), c, unit='m')
return closest_point
defget_nearest_edge_with_dist(G, point):
start_time = time.time()
gdf = graph_to_gdfs(G, nodes=False, fill_edge_geometry=True)
graph_edges = gdf[["geometry", "u", "v"]].values.tolist()
edges_with_distances = [
(
graph_edge,
# Point(tuple(reversed(point))).distance(graph_edge[0])
closest_point_on_haversine(point,graph_edge)
)
for graph_edge in graph_edges
]
edges_with_distances = sorted(edges_with_distances, key=lambda x: x[1])
closest_edge_to_point, distance = edges_with_distances[0]
geometry, u, v = closest_edge_to_point
return geometry, u, v, distance
Solution 2:
OSMnx's get_nearest_edge
does return the distance. See the docs, which say "Optionally return the distance in graph’s coordinates’ units between the point and the nearest edge." If you don't want to work in degrees as your units, just project your graph:
import osmnx as ox
from shapely.geometry import Point
ox.config(use_cache=True, log_console=True)
# lat-long point
point = 34.081076, -118.351811
G = ox.graph_from_point(point, network_type='drive')
# project the graph (and point) to a meter projection
Gp = ox.project_graph(G)
point_geom_proj, crs = ox.projection.project_geometry(Point(reversed(point)), to_crs=Gp.graph['crs'])
x, y = point_geom_proj.x, point_geom_proj.y
# find nearest edge as (u, v, key) and distance to it
u, v, key, dist = ox.get_nearest_edge(Gp, (y, x), return_dist=True)
dist # 40.2 meters
Post a Comment for "Wrong Distance Found When Finding Distance To Nearest Edge In Osmnx"