py-seasonal-hours-clock/seasonal_clock/geo.py

46 lines
1.4 KiB
Python
Raw Normal View History

2022-03-24 07:30:57 +00:00
"""Geolocation helpers for the Seasonal Clock"""
from typing import Tuple
from geopy.geocoders import Nominatim
from tzwhere import tzwhere
from . import __version__
def get_geolocator() -> Nominatim:
"""Get the geolocator service"""
return Nominatim(user_agent=f'gpolonkai-seasonal-clock/{__version__}')
def get_lat_long(country: str, city: str) -> Tuple[float, float]:
"""Get the latitude and longitude based on a country and a city name
This implicitly communicates with OpenStreetMaps API and thus needs a working Internet
connection."""
locator = get_geolocator()
geolocation = locator.geocode(f'{city}, {country}', addressdetails=True)
return geolocation.latitude, geolocation.longitude
def get_country_city(latitude: float, longitude: float) -> Tuple[str, str]:
"""Get the country and city names based on the coordinates
This implicitly communicates with OpenStreetMaps API and thus needs a working Internet
connection."""
locator = get_geolocator()
geolocation = locator.reverse(f'{latitude}, {longitude}', addressdetails=True)
return geolocation.raw['address']['country'], geolocation.raw['address']['city']
def get_timezone(latitude: float, longitude: float) -> str:
"""Get the time zone based on the coordinates"""
tzlocator = tzwhere.tzwhere()
return tzlocator.tzNameAt(latitude, longitude)