def coord_conv(epsg_from,epsg_to,cord_xlong,cord_ylat): # if epsg_from and epsg_to : epsgfrom = SpatialReference() epsgfrom.ImportFromEPSG(epsg_from) epsgto = SpatialReference() epsgto.ImportFromEPSG(epsg_to) # Check for Projection exists if not epsgfrom.GetAttrValue("PROJCS|AUTHORITY", 1): cord_xlong=ddmmss_to_dd(cord_xlong) cord_ylat=ddmmss_to_dd(cord_ylat) psd2_IsProjected=False if epsgto.GetAttrValue("PROJCS|AUTHORITY", 1): psd2_IsProjected=True # Datum_epsg_from = epsgfrom.GetAttrValue("PROJCS|GEOGCS|AUTHORITY", 1) Datum_epsg_from = epsgfrom.GetAttrValue("GEOGCS|AUTHORITY", 1) Datum_epsg_to = epsgto.GetAttrValue("GEOGCS|AUTHORITY", 1) if int(Datum_epsg_from) == 4229: epsgfrom.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) if int(Datum_epsg_to) == 4229: epsgto.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) # ---------------------------- if psd2_IsProjected: FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) x_to,y_to,zcart_to = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) x_to = format(round(x_to,2),'.2f') y_to = format(round(y_to,2),'.2f') else: x_to,y_to,zcart_to=None,None,None # -------- Case Projected To Get the datum from info of epsg2 and calculate lat/long------------------------ epsgto.ImportFromEPSG(int(Datum_epsg_to)) if int(Datum_epsg_to) == 4229: epsgto.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) long_to,lat_to,zcart2_to = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) lat_to = ddmmss_to_dms(dd_to_ddmmss(lat_to)) + " N" long_to = ddmmss_to_dms(dd_to_ddmmss(long_to)) + " E" return (x_to,y_to,zcart_to,long_to,lat_to,zcart2_to)
class Geofile(object): FILENAME = '/tmp/00/mosaic-500m.TIF' def __init__(self, filename=FILENAME): print(f"[INFO] Reading geofile from '{filename}'") self.dataset = gdal.Open(filename, gdal.GA_ReadOnly) self.geotransform = self.dataset.GetGeoTransform() self.band = self.dataset.GetRasterBand(1) srcRef = SpatialReference() srcRef.SetWellKnownGeogCS("WGS84") dstRef = SpatialReference(self.dataset.GetProjection()) self.ct = CoordinateTransformation(srcRef, dstRef) gdalVersion = osgeo.gdal.__version__ print(f"[INFO] Using gdal ver. {gdalVersion}") self.gdalMajorVer = int(gdalVersion[:gdalVersion.find('.')]) def getValue(self, lat, lon): if self.gdalMajorVer < 3: xy = self.ct.TransformPoint(lon, lat) else: xy = self.ct.TransformPoint( lat, lon ) # since gdal ver.3 they flipped order of the arguments (!) x = (xy[0] - self.geotransform[0]) / self.geotransform[ 1] # geotransform : (ulx, xres, xskew, uly, yskew, yres) y = (xy[1] - self.geotransform[3]) / self.geotransform[5] if 0 <= x < self.dataset.RasterXSize and 0 <= y < self.dataset.RasterYSize: try: # in case raster isn't full extent structval = self.band.ReadRaster(xoff=int(x), yoff=int(y), xsize=1, ysize=1, buf_type=self.band.DataType) intval = struct.unpack('f', structval) # assume float val = intval[0] except: val = None else: val = None return val
def transform_extent(extent: GeoRectangle, transform: osr.CoordinateTransformation, sample_count: int = 1000) -> GeoRectangle: """ returns a transformed extent by transforming sample_count points along a given extent """ if transform is None: return extent maxf = float("inf") (out_min_x, out_max_x, out_min_y, out_max_y) = (maxf, -maxf, maxf, -maxf) dx, dy = calc_dx_dy_from_extent_and_count(extent, sample_count) if dx == 0: return GeoRectangle.empty() y = float(extent.min_y) while y <= extent.max_y + dy: x = float(extent.min_x) while x <= extent.max_x + dx: tx, ty, tz = transform.TransformPoint(x, y) x += dx if not math.isfinite(tz): continue out_min_x = min(out_min_x, tx) out_max_x = max(out_max_x, tx) out_min_y = min(out_min_y, ty) out_max_y = max(out_max_y, ty) y += dy return GeoRectangle.from_min_max(out_min_x, out_max_x, out_min_y, out_max_y)
def toWGS84(x, y): epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) latlon2rd = CoordinateTransformation(epsg4326, epsg28992) latlonz = rd2latlon.TransformPoint(x, y) return latlonz
def latLonToUtmPoint(lon, lat, targetEpsg): targetSrs = osr.SpatialReference() targetSrs.ImportFromEPSG(int(targetEpsg)) srs = osr.SpatialReference() srs.ImportFromEPSG(4326) coordTrans = CoordinateTransformation(srs, targetSrs) utmLon, utmLat = coordTrans.TransformPoint(lon, lat)[0:2] return utmLon, utmLat
def geographic2plane(eo, epsg): # Define the Plane Coordinate System (EPSG 5186) plane = SpatialReference() plane.ImportFromEPSG(epsg) # Define the wgs84 system (EPSG 4326) geographic = SpatialReference() geographic.ImportFromEPSG(4326) coord_transformation = CoordinateTransformation(geographic, plane) # Check the transformation for a point close to the centre of the projected grid xy = coord_transformation.TransformPoint(float(eo[0]), float( eo[1])) # The order: Lon, Lat return xy[0:2]
def geographic2plane(eo, epsg=5186): # Define the Plane Coordinate System (e.g. 5186) plane = SpatialReference() plane.ImportFromEPSG(epsg) # Define the wgs84 system (EPSG 4326) geographic = SpatialReference() geographic.ImportFromEPSG(4326) coord_transformation = CoordinateTransformation(geographic, plane) # Check the transformation for a point close to the centre of the projected grid if int(osgeo.__version__[0]) >= 3: # version 3.x # Transform(y,x) will return x,y (Easting, Northing) yx = coord_transformation.TransformPoint(float(eo[1]), float( eo[0])) # The order: Lat, Lon eo[0:2] = yx[0:2][::-1] else: # version 2.x # Transform(x,y) will return x,y (Easting, Northing) xy = coord_transformation.TransformPoint(float(eo[0]), float( eo[1])) # The order: Lon, Lat eo[0:2] = xy[0:2] return eo
def tmcentral2latlon(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) tm2latlon = CoordinateTransformation(epsg5186, epsg4326) # Check the transformation for a point close to the centre of the projected grid lonlat = tm2latlon.TransformPoint(float(eo[0]), float(eo[1])) # The order: x, y eo[0:2] = lonlat[0:2] return eo
def plane2geographic(xy, epsg=32610): # Define the Plane Coordinate System (e.g. 5186) plane = SpatialReference() plane.ImportFromEPSG(epsg) # Define the wgs84 system (EPSG 4326) geographic = SpatialReference() geographic.ImportFromEPSG(4326) coord_transformation = CoordinateTransformation(plane, geographic) # Check the transformation for a point close to the centre of the projected grid latlon = coord_transformation.TransformPoint(float(xy[0]), float( xy[1])) # The order: x, y return latlon[:2]
def latlon2tmcentral(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) latlon2tm = CoordinateTransformation(epsg4326, epsg5186) # Check the transformation for a point close to the centre of the projected grid xy = latlon2tm.TransformPoint(float(eo[0]), float(eo[1])) # The order: Lon, Lat eo[0:2] = xy[0:2] return eo
def convertCoordinateSystem(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) tm2latlon = CoordinateTransformation(epsg5186, epsg4326) latlon2tm = CoordinateTransformation(epsg4326, epsg5186) # Check the transformation for a point close to the centre of the projected grid xy = latlon2tm.TransformPoint(float(eo[0]), float(eo[1])) converted_eo = copy(eo) converted_eo[0:2] = xy[0:2] return converted_eo
def wgs84To28992(lo, la): # Define the Rijksdriehoek projection system (EPSG 28992) epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) # correct the towgs84 epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) latlon2rd = CoordinateTransformation(epsg4326, epsg28992) # Check the transformation for a point close to the centre of the projected grid xy = latlon2rd.TransformPoint(lo, la) return ([xy[0], xy[1]])
def coord_conv(epsg_from, epsg_to, cord_xlong, cord_ylat): # if epsg_from and epsg_to: epsgfrom = SpatialReference() epsgfrom.ImportFromEPSG(epsg_from) if epsg_from != 4326: epsgfrom.SetTOWGS84(-121.8, 98.1, -10.7, 0, 0, 0.554, -0.2263) epsgto = SpatialReference() epsgto.ImportFromEPSG(epsg_to) if epsg_to != 4326: epsgto.SetTOWGS84(-121.8, 98.1, -10.7, 0, 0, 0.554, -0.2263) # ---------------------------- FromTo_psd = CoordinateTransformation(epsgfrom, epsgto) xlong, ylat, zcart = FromTo_psd.TransformPoint(cord_xlong, cord_ylat) # print(xlong,ylat,zcart) return (xlong, ylat, zcart)
def convertCoordinateSystem(eo): # Define the TM central coordinate system (EPSG 5186) epsg5186 = SpatialReference() epsg5186.ImportFromEPSG(5186) # Define the world mercator coordinate system (EPSG 3857) epsg3857 = SpatialReference() epsg3857.ImportFromEPSG(3857) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) tm2latlon = CoordinateTransformation(epsg5186, epsg4326) latlon2tm = CoordinateTransformation(epsg4326, epsg5186) latlon2world = CoordinateTransformation(epsg4326, epsg3857) # Check the transformation for a point close to the centre of the projected grid xy = latlon2tm.TransformPoint(float(eo[0]), float(eo[1])) # The order: Lon, Lat # xy = latlon2world.TransformPoint(float(eo[0]), float(eo[1])) # The order: Lon, Lat eo[0:2] = xy[0:2] return eo
def write_foglio(foglio, destination, point_borders=False, format_name='ESRI Shapefile'): cassini_soldener = '' #Imposto alcune variabile a seconda del codice_comune: #ATTENZIONE: Prima di modificare qui lo SRID controllare che su Postgres le tavole siano impostate adeguatamente nella tavola geometry_columns!!! #ATTENZIONE: se nella definizione della cassini_soldener si inseriscono dei valori fissi di x_0 e y_0 ricordarsi di definire successivamente la local_cassini_soldener in maniera adeguata, cioe' togliendo il riferimento al vettore shift_cassini prima definito. In pratica aggiungere il codice_comune nell'array del primo "if" (verso rigo 103...) if foglio['CODICE COMUNE'] == 'G087': cassini_soldener = '+proj=cass +lat_0=45.007336 +lon_0=7.53725 +x_0=%f +y_0=%f +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'B305': cassini_soldener = '+proj=cass +lat_0=45.067618 +lon_0=7.436827 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I785': cassini_soldener = '+proj=cass +lat_0=37.267029 +lon_0=14.692473 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'G535': cassini_soldener = '+proj=cass +lat_0=44.759075 +lon_0=9.917936 +x_0=-15.5 +y_0=10.5 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'G476': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'L380': cassini_soldener = '+proj=tmerc +lat_0=0 +lon_0=9 +k=0.9996 +x_0=1500000 +y_0=0 +ellps=intl +towgs84=-104.1,-49.1,-9.9,0.971,-2.917,0.714,-11.68 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I258': cassini_soldener = '+proj=cass +lat_0=45.099116 +lon_0=7.356182 +x_0=-1.5 +y_0=0.5 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'C261': cassini_soldener = '+proj=cass +lat_0=45.31413 +lon_0=9.502994 +x_0=1 +y_0=1 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'C722': cassini_soldener = "+proj=cass +lat_0=45.235812 +lon_0=7.602194 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs +wktext" t_srs = '4326' elif foglio['CODICE COMUNE'] == 'A484': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'G793': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I089': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I143': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I307': cassini_soldener = '+proj=cass +lat_0=40.535328 +lon_0=15.324016 +x_0=0 +y_0=0 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'G226': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'B266': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'B868': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'F618': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'F625': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'H683': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I410': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'I451': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'C370': cassini_soldener = '+proj=cass +lat_0=45.558239 +lon_0=10.76357 +x_0=+0.45 +y_0=-1.90 +ellps=intl +units=m +no_defs' t_srs = '4326' elif foglio['CODICE COMUNE'] == 'D292': cassini_soldener = '+proj=cass +lat_0=40.283555 +lon_0=15.483897 +x_0=8.9958 +y_0=-8.3549 +ellps=bessel +towgs84=668.8,146.4,506.5,5.187,-2.54,5.256,0 +units=m +no_defs' target_srs = SpatialReference() try: target_srs.ImportFromEPSG(int(t_srs)) except TypeError: raise target_srs.ImportFromProj4(t_srs) shifts = ((0., 0.), (0., 0.)) shifts = comuni_shift.get(foglio['CODICE COMUNE'], shifts) shifts = comuni_shift.get( (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO']), shifts) shift_cassini, shift_gauss_boaga = shifts ##### Parte eventualmente da MODIFICARE: if foglio['CODICE COMUNE'] in [ 'G535', 'I258', 'L380', 'G476', 'C261', 'A484', 'B266', 'B868', 'F618', 'F625', 'G226', 'G793', 'I307', 'I410', 'I451', 'D292', 'I143', 'I089', 'H683', 'C722', 'B305', 'I785', 'C370' ]: local_cassini_soldener = cassini_soldener else: local_cassini_soldener = cassini_soldener % (-shift_cassini[0], -shift_cassini[1]) source_srs = SpatialReference() source_srs.ImportFromProj4(local_cassini_soldener) trasformation = CoordinateTransformation(source_srs, target_srs) f_comune = FieldDefn('COMUNE', OFTString) f_comune.SetWidth(4) f_foglio = FieldDefn('FOGLIO', OFTString) f_foglio.SetWidth(11) f_tipo = FieldDefn('tipo', OFTString) f_tipo.SetWidth(11) f_part = FieldDefn('PARTICELLA', OFTString) f_part.SetWidth(8) f_numero = FieldDefn('NUMERO', OFTString) f_part.SetWidth(8) f_dimensione = FieldDefn('DIMENSIONE', OFTInteger) f_area = FieldDefn('AREA', OFTInteger) f_angolo = FieldDefn('ANGOLO', OFTReal) f_pos_x = FieldDefn('POSIZIONEX', OFTReal) f_pos_y = FieldDefn('POSIZIONEY', OFTReal) f_interno_x = FieldDefn('P_INTERNOX', OFTReal) f_interno_y = FieldDefn('P_INTERNOY', OFTReal) f_simbolo = FieldDefn('SIMBOLO', OFTInteger) f_etichetta = FieldDefn('etichetta', OFTString) f_etichetta.SetWidth(32) f_testo = FieldDefn('TESTO', OFTString) f_testo.SetWidth(256) create_options = [] if format_name == 'PostgreSQL': #Per passare i parametri del driver nella forma "parametro=valore". Sfortunatamente NON POSSO PASSARE "-APPEND"!!!! #vedi anche: http://www.gdal.org/gdal_tutorial.html papszOptions = ['OVERWRITE=yes'] elif format_name == 'SQLite': #IN SVILUPPO! #per maggiori info vedere: http://www.gdal.org/drv_sqlite.html create_options = [ 'SPATIALITE=YES', 'INIT_WITH_EPSG=YES', 'OGR_SQLITE_SYNCHRONOUS=OFF', 'OVERWRITE=yes' ] #l'opzione Overwrite sul DB non funziona: ho messo una IF oltre papszOptions = ['FORMAT=SPATIALITE', 'OVERWRITE=yes'] #default else: papszOptions = [] if (format_name == 'SQLite') and (os.path.exists(destination)): ds = GetDriverByName(format_name).Open(destination, update=1) #Pensavo in questo modo di ovviare all'errore che mi restituisce lo script nel caso di DB: #ERROR 1: PostgreSQL driver doesn't currently support database creation. Please create database with the `createdb' command. #ma non ho risolto niente... Invece aggiungendo "PG:" il plugin genera le tabelle! elif (format_name == 'PostgreSQL'): # ds = GetDriverByName(format_name).Open(destination) #destination = "PG:%s" % (destination) ds = GetDriverByName(format_name).CreateDataSource( destination, options=create_options) else: ds = GetDriverByName(format_name).CreateDataSource( destination, options=create_options) #per evitare sovrascritture aggiungo anche l'allegato pedice = "%s_%s_%s_%s" % (foglio['CODICE COMUNE'], foglio['NUMERO FOGLIO'], foglio['CODICE ALLEGATO'], foglio['CODICE SVILUPPO']) #PLUGIN QGIS: #Decodifico alcuni campi in modo tale che vengano riconosciuti corretti anche dalle librerie interne di QGis: comune_decode = remove_accents(foglio['CODICE COMUNE']) #oppure potrebbe essere: #comune_decode = foglio['CODICE COMUNE'].encode('utf-8') codice_foglioXX = foglio['CODICE FOGLIO'][5: 9] #cosi' dovrebbe essere "0036" foglio_intero = int(codice_foglioXX.lstrip('0')) # tipo BORDO #bordi = ds.CreateLayer('CATASTO_BORDI', target_srs, wkbPolygon) nome_layer_not_utf = "CATASTO_BORDI_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis bordi = ds.CreateLayer(nome_layer, target_srs, wkbPolygon25D, papszOptions) bordi.CreateField(f_comune) bordi.CreateField(f_foglio) bordi.CreateField(f_tipo) bordi.CreateField(f_part) bordi.CreateField(f_dimensione) bordi.CreateField(f_angolo) bordi.CreateField(f_pos_x) bordi.CreateField(f_pos_y) bordi.CreateField(f_interno_x) bordi.CreateField(f_interno_y) bordi.CreateField(f_area) bordi.CreateField(f_etichetta) for oggetto in foglio['oggetti']['BORDO']: poly = Geometry(wkbPolygon) tabisole = map(int, oggetto['TABISOLE']) # contorno esterno vertici_contorno = int(oggetto['NUMEROVERTICI']) - sum(tabisole) ring = Geometry(wkbLinearRing) for vertice in range(vertici_contorno): x, y = map(float, oggetto['VERTICI'][vertice]) if True: x, y = trasformation.TransformPoint(x, y)[:2] ring.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) ring.CloseRings() poly.AddGeometry(ring) # isole for isola in range(int(oggetto['NUMEROISOLE'])): ring = Geometry(wkbLinearRing) for vertice in range(vertice + 1, vertice + 1 + tabisole[isola]): x, y = map(float, oggetto['VERTICI'][vertice]) if True: x, y = trasformation.TransformPoint(x, y)[:2] ring.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) ring.CloseRings() poly.AddGeometry(ring) etichetta = oggetto['CODICE IDENTIFICATIVO'] if oggetto['CODICE IDENTIFICATIVO'][-1] == '+': etichetta = '' feat = Feature(bordi.GetLayerDefn()) feat.SetField('COMUNE', comune_decode) #plugin in QGis necessita di decodifica #codice_foglioXX = foglio['CODICE FOGLIO'][5:9] #cosi' dovrebbe essere "0036" #feat.SetField('FOGLIO', codice_foglioXX.lstrip('0')) feat.SetField('FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica feat.SetField('tipo', oggetto['tipo']) #feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO']) #voglio togliere il "+" feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO'].rstrip('+')) feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE'])) feat.SetField('ANGOLO', float(oggetto['ANGOLO'])) pos_x, pos_y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY'])) interno_x, interno_y = map( float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY'])) if True: pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2] interno_x, interno_y = trasformation.TransformPoint( interno_x, interno_y)[:2] feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0]) feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1]) feat.SetField('P_INTERNOX', interno_x + shift_gauss_boaga[0]) feat.SetField('P_INTERNOY', interno_y + shift_gauss_boaga[1]) feat.SetField('AREA', oggetto.get('AREA', -1)) feat.SetField('etichetta', etichetta.encode('utf-8')) feat.SetGeometry(poly) bordi.CreateFeature(feat) feat.Destroy() if point_borders: # tipo BORDO_PUNTO #bordi = ds.CreateLayer('CATASTO_PARTICELLE', target_srs, wkbPoint) #nome_layer = "CATASTO_PARTICELLE_%s" % (pedice) nome_layer_not_utf = "CATASTO_PARTICELLE_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis bordi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions) bordi.CreateField(f_comune) bordi.CreateField(f_foglio) bordi.CreateField(f_tipo) bordi.CreateField(f_part) bordi.CreateField(f_dimensione) bordi.CreateField(f_angolo) bordi.CreateField(f_area) bordi.CreateField(f_etichetta) for oggetto in foglio['oggetti']['BORDO']: etichetta = oggetto['CODICE IDENTIFICATIVO'] if oggetto['CODICE IDENTIFICATIVO'][-1] == '+': etichetta = '' feat = Feature(bordi.GetLayerDefn()) #feat.SetField('COMUNE', foglio['CODICE COMUNE']) feat.SetField( 'COMUNE', comune_decode) #plugin in QGis necessita di decodifica #feat.SetField('FOGLIO', foglio['CODICE FOGLIO']) feat.SetField( 'FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica feat.SetField('tipo', oggetto['tipo']) feat.SetField('PARTICELLA', oggetto['CODICE IDENTIFICATIVO']) feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE'])) feat.SetField('ANGOLO', float(oggetto['ANGOLO'])) pos_x, pos_y = map( float, (oggetto['PUNTOINTERNOX'], oggetto['PUNTOINTERNOY'])) if True: pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2] feat.SetField('AREA', oggetto.get('AREA', -1)) feat.SetField('etichetta', etichetta.encode('utf-8')) pt = Geometry(wkbPoint) pt.SetPoint_2D(0, pos_x + shift_gauss_boaga[0], pos_y + shift_gauss_boaga[1]) feat.SetGeometry(pt) bordi.CreateFeature(feat) feat.Destroy() # tipo TESTO #testi = ds.CreateLayer('CATASTO_TESTI', target_srs, wkbPoint) #nome_layer = "CATASTO_TESTI_%s" % (pedice) nome_layer_not_utf = "CATASTO_TESTI_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis testi = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions) testi.CreateField(f_comune) testi.CreateField(f_foglio) testi.CreateField(f_testo) testi.CreateField(f_dimensione) testi.CreateField(f_angolo) testi.CreateField(f_etichetta) for oggetto in foglio['oggetti']['TESTO']: x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY'])) if True: x, y = trasformation.TransformPoint(x, y)[:2] # FIXME: many texts are useless, prun them from etichetta etichetta = remove_accents(oggetto['TESTO']) feat = Feature(testi.GetLayerDefn()) #feat.SetField('COMUNE', foglio['CODICE COMUNE']) feat.SetField('COMUNE', comune_decode) #plugin in QGis necessita di decodifica #feat.SetField('FOGLIO', foglio['CODICE FOGLIO']) feat.SetField('FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica #feat.SetField('TESTO', oggetto['TESTO']) feat.SetField('TESTO', etichetta) feat.SetField('DIMENSIONE', int(oggetto['DIMENSIONE'])) feat.SetField('ANGOLO', float(oggetto['ANGOLO'])) feat.SetField('etichetta', etichetta.encode('utf-8')) pt = Geometry(wkbPoint) pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) feat.SetGeometry(pt) testi.CreateFeature(feat) # tipo SIMBOLO #simboli = ds.CreateLayer('CATASTO_SIMBOLI', target_srs, wkbPoint) #nome_layer = "CATASTO_SIMBOLI_%s" % (pedice) nome_layer_not_utf = "CATASTO_SIMBOLI_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis simboli = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions) simboli.CreateField(f_comune) simboli.CreateField(f_foglio) simboli.CreateField(f_simbolo) simboli.CreateField(f_angolo) for oggetto in foglio['oggetti']['SIMBOLO']: x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY'])) if True: x, y = trasformation.TransformPoint(x, y)[:2] feat = Feature(simboli.GetLayerDefn()) #feat.SetField('COMUNE', foglio['CODICE COMUNE']) feat.SetField('COMUNE', comune_decode) #plugin in QGis necessita di decodifica #feat.SetField('FOGLIO', foglio['CODICE FOGLIO']) feat.SetField('FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO']) feat.SetField('ANGOLO', float(oggetto['ANGOLO'])) pt = Geometry(wkbPoint) pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) feat.SetGeometry(pt) simboli.CreateFeature(feat) # tipo FIDUCIALE #fiduciali = ds.CreateLayer('CATASTO_FIDUCIALI', target_srs, wkbPoint) #nome_layer = "CATASTO_FIDUCIALI_%s" % (pedice) nome_layer_not_utf = "CATASTO_FIDUCIALI_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis fiduciali = ds.CreateLayer(nome_layer, target_srs, wkbPoint, papszOptions) fiduciali.CreateField(f_comune) fiduciali.CreateField(f_foglio) fiduciali.CreateField(f_numero) fiduciali.CreateField(f_simbolo) fiduciali.CreateField(f_pos_x) fiduciali.CreateField(f_pos_y) fiduciali.CreateField(f_etichetta) print 'corrections', shift_cassini, shift_gauss_boaga for oggetto in foglio['oggetti']['FIDUCIALE']: x, y = map(float, (oggetto['POSIZIONEX'], oggetto['POSIZIONEY'])) pos_x, pos_y = map(float, (oggetto['PUNTORAPPRESENTAZIONEX'], oggetto['PUNTORAPPRESENTAZIONEY'])) if True: x, y = trasformation.TransformPoint(x, y)[:2] pos_x, pos_y = trasformation.TransformPoint(pos_x, pos_y)[:2] etichetta = 'PF%02d/%s%s/%s' % (int(oggetto['NUMERO IDENTIFICATIVO']), foglio['CODICE NUMERO FOGLIO'][1:], foglio['CODICE ALLEGATO'], foglio['CODICE COMUNE']) feat = Feature(fiduciali.GetLayerDefn()) #feat.SetField('COMUNE', foglio['CODICE COMUNE']) feat.SetField('COMUNE', comune_decode) #plugin in QGis necessita di decodifica #feat.SetField('FOGLIO', foglio['CODICE FOGLIO']) feat.SetField('FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica feat.SetField('NUMERO', oggetto['NUMERO IDENTIFICATIVO']) feat.SetField('SIMBOLO', oggetto['CODICE SIMBOLO']) feat.SetField('POSIZIONEX', pos_x + shift_gauss_boaga[0]) feat.SetField('POSIZIONEY', pos_y + shift_gauss_boaga[1]) feat.SetField('etichetta', etichetta.encode('utf-8')) pt = Geometry(wkbPoint) pt.SetPoint_2D(0, x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) feat.SetGeometry(pt) fiduciali.CreateFeature(feat) print etichetta, oggetto['CODICE SIMBOLO'], \ float(oggetto['POSIZIONEX']) + shift_cassini[0], float(oggetto['POSIZIONEY']) + shift_cassini[1], \ x + shift_gauss_boaga[0], y + shift_gauss_boaga[1] # tipo LINEA #linee = ds.CreateLayer('CATASTO_LINEE', target_srs, wkbLineString) #nome_layer = "CATASTO_LINEE_%s" % (pedice) nome_layer_not_utf = "CATASTO_LINEE_%s" % (pedice) nome_layer = nome_layer_not_utf.encode('utf-8') #serve per plugin QGis linee = ds.CreateLayer(nome_layer, target_srs, wkbLineString25D, papszOptions) linee.CreateField(f_comune) linee.CreateField(f_foglio) linee.CreateField(f_simbolo) for oggetto in foglio['oggetti']['LINEA']: # contorno esterno vertici = int(oggetto['NUMEROVERTICI']) linea = Geometry(wkbLineString) for vertice in range(vertici): x, y = map(float, oggetto['VERTICI'][vertice]) if True: x, y = trasformation.TransformPoint(x, y)[:2] linea.AddPoint(x + shift_gauss_boaga[0], y + shift_gauss_boaga[1]) feat = Feature(linee.GetLayerDefn()) #feat.SetField('COMUNE', foglio['CODICE COMUNE']) feat.SetField('COMUNE', comune_decode) #plugin in QGis necessita di decodifica #feat.SetField('FOGLIO', foglio['CODICE FOGLIO']) feat.SetField('FOGLIO', foglio_intero) #plugin in QGis necessita di decodifica feat.SetField('SIMBOLO', oggetto['CODICE TIPO DI TRATTO']) feat.SetGeometry(linea) linee.CreateFeature(feat) feat.Destroy() ds.Destroy()
def map_dataframe(dataframe, variable_string1, max_color, mid_color, popup_string1, save_string, variable_string2=None, popup_string2=None, variable_string3=None, popup_string3=None, variable_string4=None, popup_string4=None): """ Map dataframe function Maps the dataframe given as input to a folium map Saves the map in the assigned location :return: None """ with Session() as s: ## Load the location data in a pandas dataframe locationdata = parquet.readLocatie(s).toPandas() ## Used to convert coordinates from RDnew to WGS84 epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) ## Set center of map to center of Utrecht and create map SF_COORDINATES = (52.092876, 5.104480) map = folium.Map(location=SF_COORDINATES, zoom_start=14) ## Set a marker for each location in the dataframe for each in locationdata.iterrows(): for line in dataframe.collect(): if each[1]['MeetpuntRichtingCode'] == line['UniekeMeetpuntRichtingCode'] + '-1' or \ each[1]['MeetpuntRichtingCode'] == line['UniekeMeetpuntRichtingCode']: ## Select all coordinates which are not 'null' if each[1]['XRD'] != '': ## Convert coordinates X, Y, Z = rd2latlon.TransformPoint( int(each[1]['XRD']), int(each[1]['YRD'])) ## Create a marker for each location if variable_string4 != None: if line[variable_string1] > max_color or line[variable_string2] > max_color or \ line[variable_string3] > max_color or line[variable_string4] > max_color: color = 'red' elif line[variable_string1] > mid_color or line[variable_string2] > mid_color or \ line[variable_string3] > mid_color or line[variable_string4] > mid_color: color = 'orange' else: color = 'green' folium.Marker( location=[Y, X], popup=(folium.Popup( popup_string1 + ': ' + str(int(line[variable_string1])) + ', ' + popup_string2 + ': ' + str(int(line[variable_string2])) + ', ' + popup_string3 + ': ' + str(int(line[variable_string3])) + ', ' + popup_string4 + ': ' + str(int(line[variable_string4])), max_width=200)), icon=folium.Icon(color=color, icon='road')).add_to(map) elif variable_string3 != None: if line[variable_string1] > max_color or line[variable_string3] > max_color or \ line[variable_string4] > max_color: color = 'red' elif line[variable_string1] > mid_color or line[ variable_string2] > mid_color or line[ variable_string3] > mid_color: color = 'orange' else: color = 'green' folium.Marker( location=[Y, X], popup=(folium.Popup( popup_string1 + ': ' + str(int(line[variable_string1])) + ', ' + popup_string2 + ': ' + str(int(line[variable_string2])) + ', ' + popup_string3 + ': ' + str(int(line[variable_string3])), max_width=200)), icon=folium.Icon(color=color, icon='road')).add_to(map) elif variable_string2 != None: if line[variable_string1] > max_color or line[ variable_string2] > max_color: color = 'red' elif line[variable_string1] > mid_color or line[ variable_string2] > mid_color: color = 'orange' else: color = 'green' folium.Marker( location=[Y, X], popup=(folium.Popup( popup_string1 + ': ' + str(int(line[variable_string1])) + ', ' + popup_string2 + ': ' + str(int(line[variable_string2])), max_width=200)), icon=folium.Icon(color=color, icon='road')).add_to(map) else: if line[variable_string1] > max_color: color = 'red' elif line[variable_string1] > mid_color: color = 'orange' else: color = 'green' folium.Marker( location=[Y, X], popup=(popup_string1 + ': ' + str(int(line[variable_string1]))), icon=folium.Icon(color=color, icon='road')).add_to(map) ## Save the map to a .html file map.save(save_string)
epsgPurpleBelt.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) epsgRedBelt = SpatialReference() epsgRedBelt.ImportFromEPSG(22992) epsgRedBelt.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) # correct the towgs84 # Egy 1907 7-par # Define the wgs84 system (EPSG 4326) epsgEgypt1907 = SpatialReference() epsgEgypt1907.ImportFromEPSG(4229) epsgEgypt1907.SetTOWGS84(-121.8,98.1,-10.7,0,0,0.554,-0.2263) epsgWgs84 = SpatialReference() epsgWgs84.ImportFromEPSG(4326) Red_WGS_latlon = CoordinateTransformation(epsgRedBelt, epsgWgs84) WGS_Red_latlon2rd = CoordinateTransformation(epsgWgs84, epsgRedBelt) pur_to_red = CoordinateTransformation(epsgPurpleBelt, epsgRedBelt) pur_to_wgs = CoordinateTransformation(epsgPurpleBelt, epsgWgs84) # Check the transformation for a point close to the centre of the projected grid # Red_WGS_latz = Red_WGS_latlon.TransformPoint(615000.0, 810000.0) # print(Red_WGS_latz) # (5.387203018813555, 52.002375635973344, 43.614926571026444) # WGS_longLat_Red = WGS_Red_latlon2rd.TransformPoint(31, 30) # print(WGS_longLat_Red) # (5.387203018813555, 52.002375635973344, 43.614926571026444) Red_xy = pur_to_wgs.TransformPoint(670934.110, 305758.950) print(Red_xy) # (5.387203018813555, 52.002375635973344, 43.614926571026444)
class BoundaryLookup(object): def __init__(self, shapefile_path): #Load resources for coordinate transformations epsg27700 = SpatialReference() epsg27700.ImportFromEPSG(27700) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) self.bng2latlon = CoordinateTransformation(epsg27700, epsg4326) self.latlon2bng = CoordinateTransformation(epsg4326, epsg27700) #Load shapefile r = sfl.Reader(shapefile_path) shapes = r.shapes() #calculate representive coordines for eah point by averaging the bounding box corners bboxes = [s.bbox for s in shapes] x_coords = [b[0] for b in bboxes] + [b[2] for b in bboxes] y_coords = [b[1] for b in bboxes] + [b[3] for b in bboxes] self.high_x = np.max(x_coords) self.high_y = np.max(y_coords) self.low_x = np.min(x_coords) self.low_y = np.min(y_coords) # print "Upper boundary:",self.high_x, self.high_y # print "Lower boundary:", self.low_x, self.low_y self.rep_coords = [((b[0] + b[2]) / 2.0, (b[1] + b[3]) / 2.0) for b in bboxes] self.records = r.records() self.shapely_shapes = [Polygon(shape.points) for shape in shapes] def check_point(self, x, y): return (self.low_x < x < self.high_x) and (self.low_y < y < self.high_y) def which_area(self, x, y): idx = 0 p = Point(float(x), float(y)) for s in self.shapely_shapes: if s.contains(p): return idx idx += 1 return None def which_area_ordered(self, x, y): p = Point(float(x), float(y)) order = self.order_search((p.x, p.y)) for i in order: if self.shapely_shapes[i].contains(p): return i return None def order_search(self, point): return np.argsort([ dist for sublist in cdist(self.rep_coords, [point]) for dist in sublist ]) def lat_lon_to_bng(self, lat, lon): ''' transform a latitude-longitude coordinate to BNG format ''' try: res = self.latlon2bng.TransformPoint(lon, lat) except: print "Error in lat_lon_to_bng." return None return (res[0], res[1]) def lookup_boundary(self, lat, lon): bng = self.lat_lon_to_bng(float(lat), float(lon)) if bng: if self.check_point(*bng): result_idx = self.which_area(bng[0], bng[1]) if result_idx: record = self.records[result_idx] return record return None def lookup_boundary_ordered(self, lat, lon): bng = self.lat_lon_to_bng(float(lat), float(lon)) if bng: if self.check_point(*bng): result_idx = self.which_area_ordered(bng[0], bng[1]) if result_idx: record = self.records[result_idx] return record return None
dist = 50 ###Translate translation to WGS84(EPSG4326) # Define the Rijksdriehoek projection system (EPSG 28992) epsg28992 = SpatialReference() epsg28992.ImportFromEPSG(28992) # correct the towgs84 epsg28992.SetTOWGS84(565.237, 50.0087, 465.658, -0.406857, 0.350733, -1.87035, 4.0812) # Define the wgs84 system (EPSG 4326) epsg4326 = SpatialReference() epsg4326.ImportFromEPSG(4326) rd2latlon = CoordinateTransformation(epsg28992, epsg4326) latlon2rd = CoordinateTransformation(epsg4326, epsg28992) latlon1 = rd2latlon.TransformPoint(lon_1, lat_1) latlon2 = rd2latlon.TransformPoint(lon_2, lat_2) rasterLL = rd2latlon.TransformPoint(origin_x, origin_y) rasterUR = rd2latlon.TransformPoint(ur_x, ur_y) ###Large data formats (DIS, LPF, RCH, VDF) ###Bas bas_file = (r'modflowtest.bas') bas_data = pd.read_csv(bas_file, skiprows=3, delim_whitespace=True) bas_arr = bas_data.to_numpy() basl1 = bas_arr[0:107, :] basl2 = bas_arr[108:216, :] basl3 = bas_arr[217:325, :] basl4 = bas_arr[326:434, :] basl5 = bas_arr[435:543, :] basl6 = bas_arr[544:652, :]