diff --git a/lib/xmet/geo.py b/lib/xmet/geo.py index 3949c3f..45fea3f 100644 --- a/lib/xmet/geo.py +++ b/lib/xmet/geo.py @@ -2,21 +2,60 @@ import re import math import shapely -def load_poly_from_file(path: str) -> shapely.Polygon: - points = list() +from typing import Self - with open(path, 'r') as fh: - data = fh.read() +class PointSequence(list): + @staticmethod + def from_file(path: str) -> Self: + ret = PointSequence() - for line in data.split('\n'): - if line == '': - continue + with open(path, 'r') as fh: + data = fh.read() - lat, lon = re.split(r'\s*,\s*', line) + for line in data.split('\n'): + if line == '': + continue - points.append((float(lon), float(lat))) + lat, lon = re.split(r'\s*,\s*', line) - return shapely.Polygon(points) + ret.add(float(lon), float(lat)) + + return ret + + def __init__(self, points: list=None): + super().__init__() + + self.poly = None + + for point in points: + typeof = type(point) + + if typeof is tuple: + self.add(*point) + elif typeof is shapely.Point: + self.append(point) + + def add(self, lon: float, lat: float): + self.append(shapely.Point(lon, lat)) + + def is_closed(self) -> bool: + return self[-1] == self[0] + + def close(self): + if self[-1] != self[0]: + self.append(self[0]) + + self.poly = shapely.Polygon(self) + + def nearest_index(self, point: shapely.Point) -> int: + indices = list() + + for i in range(0, len(self)): + indices.append((i, self[i].distance(point))) + + indices.sort(key=lambda i: i[1]) + + return indices[0][0] def line_heading(p1: shapely.Point, p2: shapely.Point) -> float: dx = p2.x - p1.x