Check if a geopoint with latitude and longitude is within a shapefile

前端 未结 7 1524
迷失自我
迷失自我 2020-12-02 06:08

How can I check if a geopoint is within the area of a given shapefile?

I managed to load a shapefile in python, but can\'t get any further.

7条回答
  •  时光说笑
    2020-12-02 06:39

    i did almost exactly what you are doing yesterday using gdal's ogr with python binding. It looked like this.

    import ogr
    
    # load the shape file as a layer
    drv    = ogr.GetDriverByName('ESRI Shapefile')
    ds_in  = drv.Open("./shp_reg/satreg_etx12_wgs84.shp")
    lyr_in = ds_in.GetLayer(0)
    
    # field index for which i want the data extracted 
    # ("satreg2" was what i was looking for)
    idx_reg = lyr_in.GetLayerDefn().GetFieldIndex("satreg2")
    
    
    def check(lon, lat):
      # create point geometry
      pt = ogr.Geometry(ogr.wkbPoint)
      pt.SetPoint_2D(0, lon, lat)
      lyr_in.SetSpatialFilter(pt)
    
      # go over all the polygons in the layer see if one include the point
      for feat_in in lyr_in:
        # roughly subsets features, instead of go over everything
        ply = feat_in.GetGeometryRef()
    
        # test
        if ply.Contains(pt):
          # TODO do what you need to do here
          print(lon, lat, feat_in.GetFieldAsString(idx_reg))
    

提交回复
热议问题