Python中找到最近的多边形给定的点坐标
问题描述:
我有一个shapefile与一系列代表各县的多边形。 我想知道一个Python中的函数/模块,它可以派生出给定单点坐标的“边界”多边形。Python中找到最近的多边形给定的点坐标
换句话说,它是一个函数,它使用一个点的经纬度坐标和shapefile,并返回包含该点的shape文件中的多边形。参见图:
正如你所看到的,关键是“蓝”多边形内,这就是我需要的任何给定的点。
据我所知,可能没有内置函数来做到这一点,但任何关于如何去做这件事的建议将是非常好的,谢谢!
答
理查德对类似问题的回答是最好的。
这里找到:https://stackoverflow.com/a/13433127/7019148
以供将来参考下面复制:
#!/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)
我想其他的问题,虽然类似,期望看到一个点是否shape文件的范围内(所有多边形)而不是找出一个点在哪个特定的多边形/对象 - 然后我会看看这些答案,看看它们是否可以改编。 –