haki
haki

Reputation: 9759

Finding the distance of coordinates from the beginning of a route in Shapely

I have a list of coordinates (lat/lon) representing a route. Given a certain radius and another coordinate I need to check if the coord is in the route (within the given radius from any point) and its distance from the beginning of the route.

I looked at Shapely and it looks like a good solution.

I started off by creating a StringLine

from shapely.geometry import LineString
route = LineString[(x, y), (x1, y1), ...]

Then to check if the point is near the route I've added a buffer and checked for intersection

from shapely.geometry import Point
p = Point(x, y)
r = 0.5
intersection = p.buffer(r).intersection(route)
if intersection.is_empty: 
    print "Point not on route"
else: 
    # Calculate P distance from the begning of route

I'm stuck calculating the distance. I thought of splitting the route at p and measuring the length of the first half but the intersection result I get is a HeterogeneousGeometrySequence which I'm not sure what I can do with.

I believe I found a solution:

if p.buffer(r).intersects(route):
 return route.project(p)

Upvotes: 2

Views: 2726

Answers (1)

Mike T
Mike T

Reputation: 43642

Rather than buffering a geometry, which is expensive and imperfect (since buffering requires a number of segments and many other options), just see if the point is within a distance threshold:

if route.distance(p) <= r:
    return route.project(p)

Also, you probably realised by now that your distance units are in degrees. If you want linear distances, like meters, you would need to make it much more complicated using different libraries.

Upvotes: 3

Related Questions