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()
""" import argparse import xarray as xr import pandas as pd import matplotlib.pyplot as plt from osgeo.ogr import GetDriverByName import os import sys dir_path = os.path.dirname(os.path.realpath(__file__)) parent = os.path.join(dir_path, os.pardir) sys.path.append(os.path.join(parent,'..')) from utils_grib import coarse_geo_filter, precise_geo_filter # Load the shapefile area filename = os.path.join(dir_path, 'shpfile/italy.shp') driver = GetDriverByName('ESRI Shapefile') shpfile = driver.Open(filename) AREA = shpfile.GetLayer() # DEF_VARIABLES = ( # 'TMP_P0_L103_GLL0', # Temperature # 'DPT_P0_L103_GLL0', # Dew point temperature # 'RH_P0_L103_GLL0', # Relative humidity # 'UGRD_P0_L103_GLL0', # U-component of wind # 'VGRD_P0_L103_GLL0', # V-component of wind # 'GUST_P0_L1_GLL0', # Wind speed (gust) # 'PRMSL_P0_L101_GLL0', # Pressure reduced to MSL # 'TMAX_P8_L103_GLL0_max', # Maximum temperature # 'TMIN_P8_L103_GLL0_min', # Minimum temperature # 'APCP_P8_L1_GLL0_acc', # Total precipitation # 'lat_0', # latitude # 'lon_0', # longitude
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()