# How to find the distance of a point from the begning of a StringLine with shapely?

I have a route (represented by StringLine) and a location (Point) and I need to find the progress of the location in the route. The progress is the distance in meters from the begning of the route. The location will not necessarily be excactly on the line so I take a little buffer (lats say 30m).

This is what I got so far though after testing a bit I think this is not the correct solution

``````if point.buffer(float(radius_in_meters)/100000).intersects(route):
distance = route.project(point) * 100000
``````

I'm new to this stuff and i really hope i wont have to implement it my self.

P.S I have no sentiments for shapely so if there is a different recommanded package for python it's also fine.

Why do you think is incorrect?

Supose you have this point and line:

``````ls = LineString([(0,0),(1,1),(2,0),(3,1)])
p = Point(2,-0.2)
`````` By using

``````ls.project(p)
``````

you'll get de distance from the beginning of the line to the nearest point. 2.828 meters, the distance of this part: I think this is what you are asking.

A second option is to include, to the previous part, the distance from the point to the line. Like this: ``````# Calculates the part from the beginning of the line to the closest point
part = cut(ls, ls.project(p))
# Gets the separation line between the given point and the closest point
sep = LineString([p.coords, part.coords[-1]])
# Unions the separation line to the part
partAndSep = part.union(sep)
``````

This gives a distance of 3.028 meters. (The code of the 'cut' method is here)

And a third option, is to change the last vertex of the part to the given point to get the distance: ``````part2 = LineString(part.coords[:-1] + [p])
``````

That gives a distance of 2.976 meters.

Update The nearest segment is calculated like this:

``````closestSeg = LineString(part.coords[-2:])
``````
• Thanks man, This is very helpfull. I got confused because the measurments i got were wrong. Is it possible to get the segment whose closest to the point ? Your examples are an edge case (where there are actually two segments with the same distance from the point, but generally speaking there should only be one). – haki Mar 4 '15 at 16:15
• Take a look at the update, not sure if it's what you want. – cag Mar 5 '15 at 14:54