Reputation: 459
I have n number of coordinates from which I created a polygon now if there is a coordinate in that polygon then how can I find perpendicular distances of point and polygon?
coords = [(45.888106581826065, 8.512891340789281), (45.89087605100282, 8.51131888355673), (45.89242907135495, 8.51043574866833), (45.88810733356788, 8.512894063368899), (45.890876868519385, 8.51132182341189), (45.892063379278696, 8.510647148893547), (45.89243094789967, 8.510442653438174), (45.88811958097381, 8.512938419782168), (45.89088904461223, 8.51136560966078), (45.89207575921023, 8.510692030810025), (45.89244290698806, 8.51048665710127), (45.88813186579548, 8.512982911786311), (45.89090145183551, 8.511410227156235), (45.89245416375836, 8.510528076647585), (45.88813271861146, 8.512986000437545), (45.89090242476677, 8.511413725908412), (45.89245495631277, 8.510530992872562)]
Point which needs to be checked if its in polygon :
p2 = Point(45.88831, 8.51283)
Checking if coordinates(p2
) are in polygon or not:
poly = MultiPoint(coords).convex_hull
if p2.within(poly):
print("Givien point is in polygon")
I tried to use boundary.distance
function to find distance and I am getting result as 4.7144012366024
but not sure whether it's perpendicular distance or something else!
print(poly.boundary.distance(p2))
#output: 4.71440123660249
Can anyone help me to get the perpendicular distances from the point?
Upvotes: 3
Views: 1078
Reputation: 80187
For every polygon edge AB
make projection of point C
onto AB
using dot product of vectors and get it length:
t = (AB.dot.AC) / (AB.dot.AB) ## ratio of AP / AB
L = length(t*AB - AC) ## CP distance at the picture
Note that for t
parameters outside 0..1
range projection lies on continuation of AB
Example:
import math
def proj(x1,y1,x2,y2,cx,cy):
dx = x2 - x1
dy = y2 - y1
cdx = cx - x1
cdy = cy - y1
t = (cdx * dx + cdy * dy) / (dx * dx + dy * dy)
if t < 0 or t > 1:
print("Projection lies outside segment")
px = x1 + t * dx
py = y1 + t * dy
print("Projection coordinates: %5.1f %5.1f" % (px, py))
nlen = math.hypot(t * dx - cdx, t * dy - cdy)
print("Distance from point to line: %5.1f" % nlen)
alonglen = math.hypot(t * dx, t * dy)
print("Along segment distance: %5.1f" % alonglen)
proj(0, 0, 4, 16/3, 0, 5)
>>
Projection coordinates: 2.4 3.2
Distance from point to line: 3.0
Along segment distance: 4.0
Upvotes: 1