我有一个esri shapefile(从这里: http://pubs.usgs.gov/ds/425/)。我希望在给定的纬度/经度下使用Python从形状文件(在这种情况下表面材料)查找信息。

解决此问题的最佳方法是什么?

谢谢。

最终解决方案:

#!/usr/bin/python

from osgeo import ogr, osr

dataset = ogr.Open('./USGS_DS_425_SHAPES/Surficial_materials.shp')
layer = dataset.GetLayerByIndex(0)
layer.ResetReading()

# Location for New Orleans: 29.98 N, -90.25 E
point = ogr.CreateGeometryFromWkt("POINT(-90.25 29.98)")

# Transform the point into the specified coordinate system from WGS84
spatialRef = osr.SpatialReference()
spatialRef.ImportFromEPSG(4326)
coordTransform = osr.CoordinateTransformation(
        spatialRef, layer.GetSpatialRef())

point.Transform(coordTransform)

for feature in layer:
    if feature.GetGeometryRef().Contains(point):
        break

for i in range(feature.GetFieldCount()):
    print feature.GetField(i)
有帮助吗?

解决方案

您可以使用Python绑定到 GDAL/OGR 工具包。这是一个例子:

from osgeo import ogr

ds = ogr.Open("somelayer.shp")
lyr = ds.GetLayerByName("somelayer")
lyr.ResetReading()

point = ogr.CreateGeometryFromWkt("POINT(4 5)")

for feat in lyr:
    geom = feat.GetGeometryRef()
    if geom.Contains(point):
        sm = feat.GetField(feat.GetFieldIndex("surface_material"))
        # do stuff...

其他提示

结帐 Python Shapefile库

这应该为您提供几何和不同的信息。

另一个选择是使用Shapely(基于GEOS的Python库,PostGis的引擎)和Fiona(基本上是用于阅读/写作文件):

import fiona
import shapely

with fiona.open("path/to/shapefile.shp") as fiona_collection:

    # In this case, we'll assume the shapefile only has one record/layer (e.g., the shapefile
    # is just for the borders of a single country, etc.).
    shapefile_record = fiona_collection.next()

    # Use Shapely to create the polygon
    shape = shapely.geometry.asShape( shapefile_record['geometry'] )

    point = shapely.geometry.Point(32.398516, -39.754028) # longitude, latitude

    # Alternative: if point.within(shape)
    if shape.contains(point):
        print "Found shape for point."

请注意,如果多边形大/复杂(例如,对于某些具有极度不规则海岸线的国家/地区的Shapefiles,进行点数测试可能会很昂贵。在某些情况下,在进行更深入的测试之前,它可以帮助使用边界框快速排除事物:

minx, miny, maxx, maxy = shape.bounds
bounding_box = shapely.geometry.box(minx, miny, maxx, maxy)

if bounding_box.contains(point):
    ...

最后,请记住,加载和解析大/不规则的ShapeFiles(不幸的是,这些类型的多边形通常也很昂贵)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top