Check if geo-point is inside or outside of polygon

前端 未结 3 1116
刺人心
刺人心 2020-12-23 17:19

I am using python and I have defined the latitudes and longitudes (in degrees) of a polygon on the map. My goal is to check if a generic point P of coordinates

相关标签:
3条回答
  • 2020-12-23 17:36

    Another way to do it is by using the even-odd algorithm explained in this link https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html The python code is given in wikipedia https://en.wikipedia.org/wiki/Even–odd_rule

    Folks, just remember that the ORDER OF POINTS that make the polygon MATTER! I mean, different order results in different polygons.

    0 讨论(0)
  • 2020-12-23 17:47

    There is also an emerging python library turfpy. which is used for geospatial analysis.

    PyPI

    Github

    Example:

    from turfpy.measurement import boolean_point_in_polygon
    from geojson import Point, Polygon, Feature
    
    point = Feature(geometry=Point((-46.6318, -23.5523)))
    polygon = Polygon(
        [
            [
                (-46.653, -23.543),
                (-46.634, -23.5346),
                (-46.613, -23.543),
                (-46.614, -23.559),
                (-46.631, -23.567),
                (-46.653, -23.560),
                (-46.653, -23.543),
            ]
        ]
    )
    boolean_point_in_polygon(point, polygon)
    
    0 讨论(0)
  • 2020-12-23 18:00

    Here is a possible solution to my problem.

    1. Geographical coordinates must be stored properly. Example np.array([[Lon_A, Lat_A], [Lon_B, Lat_B], [Lon_C, Lat_C]])
    2. Create the polygon
    3. Create the point to be tested
    4. Use polygon.contains(point) to test if point is inside (True) or outside (False) the polygon.

    Here is the missing part of the code:

    from shapely.geometry import Point
    from shapely.geometry.polygon import Polygon
    
    lons_lats_vect = np.column_stack((lons_vect, lats_vect)) # Reshape coordinates
    polygon = Polygon(lons_lats_vect) # create polygon
    point = Point(y,x) # create point
    print(polygon.contains(point)) # check if polygon contains point
    print(point.within(polygon)) # check if a point is in the polygon 
    

    Note: the polygon does not take into account great circles, therefore it is necessary to split the edges into many segments thus increasing the number of vertices.


    Special case: If point lies on borders of Polygon

    E.g. print(Polygon([(0, 0), (1, 0), (1, 1)]).contains(Point(0, 0))) will fail

    So one can use

    print(polygon.touches(point)) # check if point lies on border of polygon 
    
    0 讨论(0)
提交回复
热议问题