#!/usr/bin/python import argparse import configparser from typing import List, Optional from osgeo import ogr from osgeo.ogr import Layer, Feature from osgeo.osr import SpatialReference, CoordinateTransformation def matching_city(cities_geonames: Layer, city_wr: Feature) -> Optional[Feature]: city_name = city_wr['name'] if city_name is None: return spatial_reference_ll = SpatialReference() spatial_reference_ll.ImportFromEPSG(4326) spatial_reference_m = SpatialReference() spatial_reference_m.ImportFromProj4('+proj=merc +lat_ts=47.3') coord_transform = CoordinateTransformation(spatial_reference_ll, spatial_reference_m) a = city_wr.GetGeometryRef().Clone() a.Transform(coord_transform) cities_geonames.SetAttributeFilter("FEATCODE != 'PPLX' AND COUNTRY IN ('AT', 'DE', 'IT', 'CH', 'LI')") matches = [] for city_geonames in cities_geonames: alt_names = city_geonames['ALTNAMES'].split(',') if alt_names == ['']: alt_names = [] if city_name == city_geonames['NAME'] or city_name in alt_names: b = city_geonames.GetGeometryRef().Clone() b.Transform(coord_transform) distance = a.Distance(b) if distance <= 10_000: matches.append(city_geonames) if len(matches) == 1: return matches[0] if len(matches) > 1: print([m['NAME'] for m in matches]) def update_wrcity2(ini_files: List[str]): ogr.UseExceptions() cities_geonames_source = ogr.Open('/home/philipp/projects/winterrodeln/geodata/geonames.org/cities1000.csv') cities_geonames = cities_geonames_source.GetLayerByIndex(0) config = configparser.ConfigParser() config.read(ini_files) host = config.get('mysql', 'host') dbname = config.get('mysql', 'dbname') user = config.get('mysql', 'user_name') passwd = config.get('mysql', 'user_pass') cities_wr_source = ogr.Open(f'MySQL:{dbname},"host={host}","user={user}","password={passwd}","tables=wrcity"') cities_wr = cities_wr_source.GetLayerByIndex(0) for city_wr in cities_wr: if city_wr['geonameid'] is not None: continue # geometry = city_wr.GetGeometryRef() city_geonames = matching_city(cities_geonames, city_wr) if city_geonames is not None: print(f'Yeah, {city_geonames}') city_wr['geonameid'] = int(city_geonames['GEONAMEID']) cities_wr.SetFeature(city_wr) # print(geometry.ExportToWkt()) # print(city_wr.items()) def main(): parser = argparse.ArgumentParser(description='Add the geocityid to the wrcity table.') parser.add_argument('inifile', nargs='+', help='inifile.ini, see: https://www.winterrodeln.org/trac/wiki/ConfigIni') args = parser.parse_args() update_wrcity2(args.inifile) if __name__ == '__main__': main()