python – 检查纬度和经度的地理点是否在shapefile内 - 代码日志

python – 检查纬度和经度的地理点是否在shapefile内

检查地理点是否在给定shapefile的区域内的方法是什么?我试图在python中加载一个shapefile,但是不能进一步。
这是yosukesabai的答案的适应。

我想确保我正在搜索的一点是与shapefile相同的投影系统,所以我已经添加了代码。

我不明白为什么他正在对ply = feat_in.GetGeometryRef()进行包含测试(在我的测试中似乎也没有它),所以我删除了。

我也改进了评论,以更好地解释发生了什么(据我所知)。

#!/usr/bin/python
import ogr
from IPython import embed
import sys

drv = ogr.GetDriverByName('ESRI Shapefile') #We will load a shape file
ds_in = drv.Open("MN.shp")    #Get the contents of the shape file
lyr_in = ds_in.GetLayer(0)    #Get the shape file's first layer

#Put the title of the field you are interested in here
idx_reg = lyr_in.GetLayerDefn().GetFieldIndex("P_Loc_Nm")

#If the latitude/longitude we're going to use is not in the projection
#of the shapefile, then we will get erroneous results.
#The following assumes that the latitude longitude is in WGS84
#This is identified by the number "4326", as in "EPSG:4326"
#We will create a transformation between this and the shapefile's
#project, whatever it may be
geo_ref = lyr_in.GetSpatialRef()
point_ref=ogr.osr.SpatialReference()
point_ref.ImportFromEPSG(4326)
ctran=ogr.osr.CoordinateTransformation(point_ref,geo_ref)

def check(lon, lat):
    #Transform incoming longitude/latitude to the shapefile's projection
    [lon,lat,z]=ctran.TransformPoint(lon,lat)

    #Create a point
    pt = ogr.Geometry(ogr.wkbPoint)
    pt.SetPoint_2D(0, lon, lat)

    #Set up a spatial filter such that the only features we see when we
    #loop through "lyr_in" are those which overlap the point defined above
    lyr_in.SetSpatialFilter(pt)

    #Loop through the overlapped features and display the field of interest
    for feat_in in lyr_in:
        print lon, lat, feat_in.GetFieldAsString(idx_reg)

#Take command-line input and do all this
check(float(sys.argv[1]),float(sys.argv[2]))
#check(-95,47)

This sitethis sitethis site对投影检查有帮助。 EPSG:4326

http://stackoverflow.com/questions/7861196/check-if-a-geopoint-with-latitude-and-longitude-is-within-a-shapefile

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:python – 检查纬度和经度的地理点是否在shapefile内