def reproj_convert_layer(geojson_path, output_path, file_format, output_crs, input_crs="epsg:4326"): layer_name = output_path.split('/') layer_name = layer_name[len(layer_name) - 1].split('.')[0] in_driver = GetDriverByName("GeoJSON") out_driver = GetDriverByName(file_format) inSpRef = SpatialReference() inSpRef.ImportFromEPSG(int(input_crs.split("epsg:")[1])) outSpRef = SpatialReference() ret_val = outSpRef.ImportFromProj4(output_crs) if not ret_val == 0: raise ValueError("Error when importing the output crs") coords_transform = CoordinateTransformation(inSpRef, outSpRef) f_in = in_driver.Open(geojson_path) input_layer = f_in.GetLayer() f_out = out_driver.CreateDataSource(output_path) output_layer = f_out.CreateLayer(layer_name, outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField( output_lyr_defn.GetFieldDefn(i).GetNameRef(), inFeature.GetField(i)) output_layer.CreateFeature(outFeature) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() if "Shapefile" in file_format: outSpRef.MorphToESRI() with open(output_path.replace(".shp", ".prj"), 'w') as file_proj: file_proj.write(outSpRef.ExportToWkt()) with open(output_path.replace(".shp", ".cpg"), "w") as encoding_file: encoding_file.write("ISO-8859-1") return 0
def convert_ogr_to_geojson(file_path, file_format): regex_field_name = re.compile("[^a-zA-Z0-9_-ëêàáâãæêéèñòóô]+") in_driver = GetDriverByName(file_format) out_driver = GetDriverByName('MEMORY') f_in = in_driver.Open(file_path) input_layer = f_in.GetLayer() outSpRef = SpatialReference() outSpRef.ImportFromEPSG(4326) coords_transform = CoordinateTransformation(input_layer.GetSpatialRef(), outSpRef) f_out = out_driver.CreateDataSource('') output_layer = f_out.CreateLayer('', outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) fieldDefn.SetName(regex_field_name.sub('_', fieldDefn.GetNameRef())) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() nb_field = output_lyr_defn.GetFieldCount() field_names = [ output_lyr_defn.GetFieldDefn(i).GetNameRef() for i in range(nb_field) ] res = [] for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) # Don't try to transform empty geometry : if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) outFeature.SetFID(inFeature.GetFID()) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField(field_names[i], inFeature.GetField(i)) res.append(outFeature.ExportToJson()) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() return ''.join([ '''{"type":"FeatureCollection","features":[''', ','.join(res), ''']}''' ]).encode()
def write(self, fpath, polygons, spatial_reference=None, driver_name=None): """ Convert SCHISM polygon YAML file to a shapefile Parameters ---------- fpath: str output file name polygons: array of schism_polygon.SchismPolygon polygons to write spatial_reference: osgeo.osr.SpatialReference or proj4 string default: NAD83, UTM zone 10N, meter driver_name: osgeo.ogr Driver name default: ESRI Shapefile """ if spatial_reference is None: # Not sure if this changed. it should be EPSG 26910 #spatial_reference = '+proj=utm +zone=10N +ellps=NAD83 +datum=NAD83 +units=m' spatial_reference= '+proj=utm +zone=10 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=m +no_defs' if isinstance(spatial_reference, str): spatial_reference_obj = SpatialReference() try: spatial_reference_obj.ImportFromProj4(spatial_reference) except: raise ValueError("spatial reference could not be created from string: {}".format(spatial_reference)) elif isinstance(spatial_reference, SpatialReference): spatial_reference_obj = spatial_reference else: raise ValueError('Not support spatial_reference type') if driver_name is None: driver_name = 'ESRI Shapefile' driver = GetDriverByName(driver_name) if driver is None: print('%s is not available.' % driver_name) raise RuntimeError() datasource = driver.CreateDataSource(str(fpath)) if datasource is None: raise RuntimeError("Cannot create a GIS file") layer = datasource.CreateLayer('layer', spatial_reference_obj, wkbPolygon) fields = ('name', 'type', 'attribute') for field in fields: layer.CreateField(FieldDefn(field)) feature_defn = layer.GetLayerDefn() feature = Feature(feature_defn) for i, polygon in enumerate(polygons): feature.SetGeometry(CreateGeometryFromWkb(polygon.wkb)) feature.SetField(0, polygon.name) feature.SetField(1, polygon.type) feature.SetField(2, polygon.attribute) layer.CreateFeature(feature) datasource.Destroy()
def write(self, fpath, lines, spatial_reference=None, driver_name=None, **kwargs): """ Parameters ---------- fpath: str output file name lines: array of schism_linestring.LineString list of LineStrings spatial_reference: osgeo.osr.SpatialReference default: NAD83, UTM zone 10N, meter """ # Boilerplate to create a SHP file if spatial_reference is None: spatial_reference = SpatialReference() spatial_reference.ImportFromProj4( '+proj=utm +zone=10N +ellps=NAD83 +datum=NAD83 +units=m') if driver_name is None: driver_name = 'ESRI Shapefile' driver = GetDriverByName(driver_name) if driver is None: print('%s is not available.' % driver_name) raise RuntimeError() datasource = driver.CreateDataSource(fpath) if datasource is None: raise RuntimeError("Cannot create a GIS file") layer = datasource.CreateLayer('layer', spatial_reference, wkbLineString) fields = [] for l in lines: if l.prop is not None: for k in l.prop: if k not in fields and k != 'coordinates': fields.append(k) map(layer.CreateField, [FieldDefn(field) for field in fields]) feature_defn = layer.GetLayerDefn() feature = Feature(feature_defn) for i, line in enumerate(lines): feature.SetGeometry(CreateGeometryFromWkb(line.wkb)) for j, f in enumerate(fields): val = line.prop.get(f) if val is not None: feature.SetField(j, val) layer.CreateFeature(feature) datasource.Destroy()
def reproj_convert_layer(geojson_path, output_path, file_format, output_crs): """ Concert GeoJSON to GML or Shapefile and write it to disk. Convert a GeoJSON FeatureCollection to GML or ESRI Shapefile format and reproject the geometries if needed (used when the user requests an export). Parameters ---------- geojson_path: str Path of the input GeoJSON FeatureCollection to be converted. output_path: str Path for the resulting Shapefile/GML (should be in a directory created by tempfile.TemporaryDirectory). file_format: str The format of the expected result ('ESRI Shapefile' or 'GML' is expected). output_crs: str The output srs to use (in proj4 string format). Returns ------- result_code: int Should return 0 if everything went fine.. """ ## TODO : Use VectorTranslate to make the conversion? input_crs = "epsg:4326" layer_name = output_path.split('/') layer_name = layer_name[len(layer_name) - 1].split('.')[0] in_driver = GetDriverByName("GeoJSON") out_driver = GetDriverByName(file_format) inSpRef = SpatialReference() inSpRef.ImportFromEPSG(int(input_crs.split("epsg:")[1])) outSpRef = SpatialReference() ret_val = outSpRef.ImportFromProj4(output_crs) if not ret_val == 0: raise ValueError("Error when importing the output crs") coords_transform = CoordinateTransformation(inSpRef, outSpRef) f_in = in_driver.Open(geojson_path) input_layer = f_in.GetLayer() f_out = out_driver.CreateDataSource(output_path) output_layer = f_out.CreateLayer(layer_name, outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField( output_lyr_defn.GetFieldDefn(i).GetNameRef(), inFeature.GetField(i)) output_layer.CreateFeature(outFeature) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() if "Shapefile" in file_format: outSpRef.MorphToESRI() with open(output_path.replace(".shp", ".prj"), 'w') as file_proj: file_proj.write(outSpRef.ExportToWkt()) with open(output_path.replace(".shp", ".cpg"), "w") as encoding_file: encoding_file.write("ISO-8859-1") return 0
def convert_ogr_to_geojson(file_path, file_format): """ Convert a layer (in a format supported by ogr) to a GeoJSON layer. Used in fallback, if the conversion failed with 'VectorTranslate'. Parameters ---------- file_path: str Path of the input file. file_format: str Format of the input layer Returns ------- raw_geojson: bytes The resulting GeoJSON FeatureCollection. """ regex_field_name = re.compile("[^a-zA-Z0-9_-ëêàáâãæêéèñòóô]+") in_driver = GetDriverByName(file_format) out_driver = GetDriverByName('MEMORY') f_in = in_driver.Open(file_path) input_layer = f_in.GetLayer() outSpRef = SpatialReference() outSpRef.ImportFromEPSG(4326) coords_transform = CoordinateTransformation(input_layer.GetSpatialRef(), outSpRef) f_out = out_driver.CreateDataSource('') output_layer = f_out.CreateLayer('', outSpRef) input_lyr_defn = input_layer.GetLayerDefn() for i in range(input_lyr_defn.GetFieldCount()): fieldDefn = input_lyr_defn.GetFieldDefn(i) fieldDefn.SetName(regex_field_name.sub('_', fieldDefn.GetNameRef())) output_layer.CreateField(fieldDefn) output_lyr_defn = output_layer.GetLayerDefn() nb_field = output_lyr_defn.GetFieldCount() field_names = [ output_lyr_defn.GetFieldDefn(i).GetNameRef() for i in range(nb_field) ] res = [] for inFeature in input_layer: geom = inFeature.GetGeometryRef() outFeature = OgrFeature(output_lyr_defn) # Don't try to transform empty geometry : if geom: geom.Transform(coords_transform) outFeature.SetGeometry(geom) else: outFeature.SetGeometry(None) outFeature.SetFID(inFeature.GetFID()) for i in range(output_lyr_defn.GetFieldCount()): outFeature.SetField(field_names[i], inFeature.GetField(i)) res.append(outFeature.ExportToJson()) outFeature.Destroy() inFeature.Destroy() f_in.Destroy() f_out.Destroy() return ''.join([ '''{"type":"FeatureCollection","features":[''', ','.join(res), ''']}''' ]).encode()