get_coordinates_by_zipcode.py 3.42 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""
For a given German Zipcode, returns the corresponding WKT Polygon or Multipolygon.
If pyperclip is installed, the WKT gets copied to the clipboard,
e.g. for RegionChooser or download_files_from_LGL_BW.py.

Also accepts multiple Zipcodes, or Zipcode prefix.

    python get_coordinates_by_zipcode.py --help
    usage: get_coordinates_by_zipcode.py [-h] PLZ [PLZ ...]

    Get WKT geometry for desired PLZs

    positional arguments:
    PLZ         desired PLZs

    options:
    -h, --help  show this help message and exit

> python get_coordinates_by_zipcode.py 70174
> python get_coordinates_by_zipcode.py 70567 70569
> python get_coordinates_by_zipcode.py 70
"""

Eric Duminil's avatar
TODOs    
Eric Duminil committed
24
25
26
27
# TODO: Write tests
# TODO: Use caching for shapes
# TODO: Rename functions

28
29
30
31
32
33
34
35
36
import argparse
import json
import re
from pathlib import Path
from shapely.geometry import shape
from shapely.ops import unary_union

INPUT_FOLDER = Path('plz')
PLZ_FILENAME = 'plz-5stellig.geojson'
Eric Duminil's avatar
Eric Duminil committed
37
PLZ_SHAPE_FILE = INPUT_FOLDER / PLZ_FILENAME
38
39


Eric Duminil's avatar
Eric Duminil committed
40
41
def _download_plz_shapes_if_needed():
    if not PLZ_SHAPE_FILE.exists():
42
43
44
45
46
        from tqdm import tqdm
        import requests
        URL = "https://downloads.suche-postleitzahl.org/v2/public/" + PLZ_FILENAME
        response = requests.get(URL, stream=True)
        INPUT_FOLDER.mkdir(exist_ok=True)
Eric Duminil's avatar
Eric Duminil committed
47
        with open(PLZ_SHAPE_FILE, "wb") as handle:
48
49
50
51
            for data in tqdm(response.iter_content(chunk_size=1024), unit='kB'):
                handle.write(data)


Eric Duminil's avatar
Eric Duminil committed
52
def _get_plz_shapes():
53
    print("Parsing %s..." % PLZ_FILENAME)
Eric Duminil's avatar
Eric Duminil committed
54
    _download_plz_shapes_if_needed()
55
    try:
Eric Duminil's avatar
Eric Duminil committed
56
        with open(PLZ_SHAPE_FILE) as f:
57
58
59
            print('  Done')
            return json.load(f)
    except json.decoder.JSONDecodeError:
Eric Duminil's avatar
Eric Duminil committed
60
        PLZ_SHAPE_FILE.unlink()
61
62
63
        raise AttributeError(f"{PLZ_FILENAME} seems to be damaged. Removing it. Please try again!")


Eric Duminil's avatar
Eric Duminil committed
64
def _get_coordinates(data, plz_patterns):
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
    geometries = []
    for plz_pattern in plz_patterns:
        found = False
        for plz_geojson in data['features']:
            if re.match(plz_pattern, plz_geojson['properties']['plz']):
                found = True

                properties = plz_geojson['properties']

                print('## %s' % properties['note'])
                print('Population : %d' % properties['einwohner'])
                print('Area : %.2f km²' % properties['qkm'])
                # NOTE : Geometry can be either a polygon,
                # a MultiPolygon : 98694 Ilmenau
                # or a polygon with holes : 31860 Emmerthal
                print('WKT Polygon : ')

                geometries.append(shape(plz_geojson['geometry']))

        if not found:
            raise AttributeError(f"Sorry, no information could be found for PLZ={plz_pattern}")

    merged = unary_union(geometries)
    wkt_polygon = merged.simplify(0.0001).wkt
    print(wkt_polygon)
    try:
        import pyperclip
        pyperclip.copy(wkt_polygon)
        print("WKT Polygon copied to clipboard.")
    except ModuleNotFoundError:
        pass

    print()
    print("Done!")
    return wkt_polygon


Eric Duminil's avatar
Eric Duminil committed
102
103
104
def get_coordinates_by_zipcode(plzs):
    plz_shapes = _get_plz_shapes()
    return _get_coordinates(plz_shapes, plzs)
105
106
107
108
109
110
111


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Get WKT geometry for desired PLZs')
    parser.add_argument('plzs', metavar='PLZ', type=str, nargs='+',
                        help='desired PLZs')
    args = parser.parse_args()
Eric Duminil's avatar
Eric Duminil committed
112
    get_coordinates_by_zipcode(args.plzs)