Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python to lookup information at specific latitude/longitude in a ESRI shapefile?

I have a ESRI shapefile (from here: http://pubs.usgs.gov/ds/425/). I looking to use python to lookup information from the shape file (surficial material in this case) at a given latitude/longitude.

What is the best way to go about solving this problem?

Thanks.

Final solution:

#!/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)
like image 539
arkottke Avatar asked Jan 04 '11 18:01

arkottke


2 Answers

Checkout the Python Shapefile Library

This should give you geometry and different info.

like image 115
milkypostman Avatar answered Oct 05 '22 23:10

milkypostman


You can use the python bindings to the gdal/ogr toolkit. Here's an example:

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...
like image 39
albertov Avatar answered Oct 06 '22 01:10

albertov