Search code examples
python-3.xpandasintersectiongeopandasshapely

Intersection between Geopandas Polygon and Shapely LineString


Let us say we have the following Square Shape as Geopandas DataFrame

import geopandas as gpd
from shapely.geometry import LineString, LinearRing, Point, Polygon

polygon_geom = Polygon(zip([0,1,1,0], [0,0,1,1]))
crs = {'init': 'epsg:4326'}
polygon = gpd.GeoDataFrame(index=[0], crs=crs, geometry=[polygon_geom])

Note: The polygon I'm working with is a shape file imported to Geopandas, and for the sake of example I have created a geopanda dataframe for the polygon.

I have another LineString using Shapely

Point1 = Point(0,1)
Point2 = Point(2,0)
line = LineString([Point1,Point2])

I need to find the intersection points between the polygon and the line. Expected result to be two points (1,0) and (1,0.5)

I have tried intersection method and overly but did not succeed with that. I would really appreciate the support and hints.


Solution

  • In your particular case, you can get the geometry of the polygon as:-

    poly = polygon.geometry.values[0]
    

    This checks if the line and poly are intersecting:-

    line.intersects(poly)
    

    It returns True. So we go ahead with:-

    line.intersection(poly).xy
    

    and get

    (array('d', [0.0, 1.0]), array('d', [1.0, 0.5]))

    as the result.