31 lines
1.1 KiB
Python
31 lines
1.1 KiB
Python
"""Local WGS84 province lookup; coordinates never leave the application."""
|
|
import json
|
|
from functools import lru_cache
|
|
from pathlib import Path
|
|
|
|
CHINA = [73, 3, 135.2, 53.7]
|
|
@lru_cache(maxsize=1)
|
|
def provinces():
|
|
return json.loads((Path(__file__).parent/'map-provinces.json').read_text(encoding='utf8'))['features']
|
|
|
|
def contains(bounds, lon, lat):
|
|
return bounds[0] <= lon <= bounds[2] and bounds[1] <= lat <= bounds[3]
|
|
|
|
def ring_inside(ring, x, y):
|
|
inside=False
|
|
for i,(ax,ay) in enumerate(ring):
|
|
bx,by=ring[i-1]
|
|
if (ay>y)!=(by>y) and x < (bx-ax)*(y-ay)/(by-ay)+ax: inside=not inside
|
|
return inside
|
|
|
|
def locate(lon,lat):
|
|
for f in provinces():
|
|
if not contains(f['properties']['bounds'],lon,lat): continue
|
|
geom=f['geometry'];polygons=geom['coordinates'] if geom['type']=='MultiPolygon' else [geom['coordinates']]
|
|
if any(ring_inside(p[0],lon,lat) and not any(ring_inside(h,lon,lat) for h in p[1:]) for p in polygons):
|
|
return f['properties']
|
|
return None
|
|
|
|
def definitions():
|
|
return {p['properties']['id']:p['properties'] for p in provinces()}
|