You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

49 lines
1.3 KiB

  1. #!/usr/bin/env python3
  2. import re
  3. from typing import Union
  4. from kosmorrolib import Position
  5. from openlocationcode import openlocationcode
  6. from .i18n.utils import _
  7. def _parse_latitude_longitude(from_str: str) -> Position:
  8. if not re.search(r"^([\d.-]+)[,;]([\d.-]+)$", from_str):
  9. raise ValueError(_('The given position ("%s") is not valid.' % from_str))
  10. latitude_longitude = from_str.split(";")
  11. if len(latitude_longitude) == 1:
  12. latitude_longitude = from_str.split(",")
  13. return Position(float(latitude_longitude[0]), float(latitude_longitude[1]))
  14. def _parse_plus_code(from_str: str) -> Union[None, Position]:
  15. if not openlocationcode.isValid(from_str):
  16. return None
  17. if not openlocationcode.isFull(from_str):
  18. raise ValueError(
  19. _(
  20. "The given Plus Code seems to be a short code, please provide a full code."
  21. )
  22. )
  23. pos = openlocationcode.decode(from_str)
  24. return Position(
  25. latitude=(pos.latitudeLo + pos.latitudeHi) / 2,
  26. longitude=(pos.longitudeLo + pos.longitudeHi) / 2,
  27. )
  28. def get_position(from_str: str) -> Position:
  29. pos = _parse_plus_code(from_str)
  30. if pos is not None:
  31. return pos
  32. return _parse_latitude_longitude(from_str)