Created
January 18, 2014 02:15
-
-
Save whardier/8485288 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE ogr_stream_template (fid integer, the_geom geometry, fields text[], integers int[], floats float[], texts text[]); | |
CREATE OR REPLACE FUNCTION ogr_stream_iterator(path text, layer_name text, srid integer) | |
RETURNS SETOF ogr_stream_template | |
AS $$ | |
import sys | |
sys.path.insert(1, '/usr/local/gis/lib/python2.7/site-packages') | |
import binascii | |
import osgeo.ogr | |
import osgeo.gdalconst | |
import osgeo.osr | |
spatialref = osgeo.osr.SpatialReference() | |
spatialref.ImportFromEPSG(srid) | |
ds = osgeo.ogr.Open(path, osgeo.gdalconst.GF_Read) | |
layer = ds.GetLayerByName(layer_name) | |
if not layer: | |
raise StopIteration | |
transform = osgeo.osr.CoordinateTransformation(layer.GetSpatialRef(), spatialref) | |
feature_defn = layer.GetLayerDefn() | |
feature_fields = [ | |
( | |
idx, | |
feature_defn.GetFieldDefn(idx).GetName(), | |
feature_defn.GetFieldDefn(idx).GetTypeName() | |
) for idx in range(feature_defn.GetFieldCount()) | |
] | |
fields = [field_name for field_idx, field_name, field_type in feature_fields] | |
for feature in layer: | |
integers = [] | |
floats = [] | |
texts = [] | |
the_geom = feature.GetGeometryRef().Clone() | |
the_geom.Transform(transform) | |
for field_idx, field_name, field_type in feature_fields: | |
value = feature.GetField(field_idx) | |
if field_type == 'Real': | |
floats.append(value) | |
if field_type == 'String': | |
texts.append(value) | |
if field_type == 'Integer': | |
integers.append(value) | |
yield { | |
'fid': feature.GetFID(), | |
'the_geom': binascii.b2a_hex(the_geom.ExportToWkb()), | |
'fields': fields, | |
'integers': integers, | |
'floats': floats, | |
'texts': texts, | |
} | |
$$ LANGUAGE plpythonu; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment