1

The red dots represents the points in the shape file. I want to find point B (closest point on the shapefile to point A). The B might not be one from the given set of points in the shapefile (as we are finding the closest one.) Any solution to solve thus using Python? I want the coordinates of B.

enter image description here

1

I would suggest creating a linestring from all the points in the shapefile (all the red points in your image). Then I would use the nearest points method from the shapely library to return the point in the linestring that is nearest to point A. The list_of_points variable in the code below is a list of point you have extracted from the shapefile.

from shapely.geometry import Point, LineString
from shapely.ops import nearest_points

pt_a = Point(coordinates of A)
ls = LineString([Point(point.x, point.y) for point in list_of_points)
nearest_pts = [pt for pt in nearest_points(pt_a, ls)

The nearest_pts variable as result will give you a list of 2 points: point A and point B. You can extract the coordinates using point.x and point.y.

  • Didn't know about nearest_points methods before. Works like a charm. Thanks. – GeoJ Feb 19 at 6:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.