Create closed polygon from boundary points

后端 未结 3 2011
盖世英雄少女心
盖世英雄少女心 2021-01-13 02:45

I have an array of longitude-latitude points that defines the boundaries of an area. I would like to create a polygon based on these points and plot the polygon on a map and

3条回答
  •  庸人自扰
    2021-01-13 03:35

    I recommend using the original Shapefile, which is in a format appropriate for storing polygons. As an alternative to OGR you could use Shapely, or export the polygon to Wkt etc.

    import ogr
    import matplotlib.path as mpath
    import matplotlib.patches as patches
    import matplotlib.pyplot as plt
    
    ds = ogr.Open('lmes_64.shp')
    lyr = ds.GetLayer(0)
    ft = lyr.GetFeature(38)
    geom = ft.GetGeometryRef()
    ds = None
    
    codes = []
    all_x = []
    all_y = []
    
    if (geom.GetGeometryType() == ogr.wkbPolygon):
      for i in range(geom.GetGeometryCount()):
    
        r = geom.GetGeometryRef(i)
        x = [r.GetX(j) for j in range(r.GetPointCount())]
        y = [r.GetY(j) for j in range(r.GetPointCount())]
    
        codes += [mpath.Path.MOVETO] + (len(x)-1)*[mpath.Path.LINETO]
        all_x += x
        all_y += y
    
    if (geom.GetGeometryType() == ogr.wkbMultiPolygon):
      codes = []
      for i in range(geom.GetGeometryCount()):
        # Read ring geometry and create path
        r = geom.GetGeometryRef(i)
        for part in r:
          x = [part.GetX(j) for j in range(part.GetPointCount())]
          y = [part.GetY(j) for j in range(part.GetPointCount())]
          # skip boundary between individual rings
          codes += [mpath.Path.MOVETO] + (len(x)-1)*[mpath.Path.LINETO]
          all_x += x
          all_y += y
    
    carib_path = mpath.Path(np.column_stack((all_x,all_y)), codes)    
    carib_patch = patches.PathPatch(carib_path, facecolor='orange', lw=2)
    
    poly1 = patches.Polygon([[-80,20],[-75,20],[-75,15],[-80,15],[-80,20]], zorder=5, fc='none', lw=3)
    poly2 = patches.Polygon([[-65,25],[-60,25],[-60,20],[-65,20],[-65,25]], zorder=5, fc='none', lw=3)
    
    
    fig, ax = plt.subplots(1,1)
    
    for poly in [poly1, poly2]:
        if carib_path.intersects_path(poly.get_path()):
            poly.set_edgecolor('g')
        else:
            poly.set_edgecolor('r')
    
        ax.add_patch(poly)
    
    ax.add_patch(carib_patch)
    ax.autoscale_view()
    

    enter image description here

    Also checkout Fiona (wrapper for OGR) if you want really easy Shapefile handling.

提交回复
热议问题