osmnx: project point to street segments

907 views Asked by At

I have a point given by lat and lon and I want to find the nearest edge to the point by minimum Euclidean distance. For example

import osmnx as ox
track = [(40.7052, -74.0069)]
fig, ax = ox.plot_graph(G, show=False, close=False)
for pairs in track:
    ax.scatter(pairs[1], pairs[0], c='red')
plt.show()

ox.distance.get_nearest_edge(G, track, return_geom=True, return_dist=True)

and I get

(2350521192,2350521202,0,
<shapely.geometry.linestring.LineString at 0x16569aa30>,
162.22242578930698)

It outputs the vertices of the edge and its geometry. The distance between the point and nearest edge is 162. But how do I find the the projection of my point onto this nearest edge?

1

There are 1 answers

1
gboeing On BEST ANSWER

Here's a complete minimal working example:

import osmnx as ox
from shapely.geometry import Point
ox.config(use_cache=True, log_console=True)

# create point tuple as (lat, lng)
point = (40.7052, -74.0069)
G = ox.graph_from_point(point, network_type='drive')
u, v, k, edge_geom, dist = ox.distance.get_nearest_edge(G, point, return_geom=True, return_dist=True)

# create shapely point geometry object as (x, y), that is (lng, lat)
point_geom = Point(reversed(point))

# use shapely to find the point along the edge that is closest to the reference point
nearest_point_on_edge = edge_geom.interpolate(edge_geom.project(point_geom))
nearest_point_on_edge.coords[0]