Skip to content
Snippets Groups Projects
box_funcitons.py 1.79 KiB
Newer Older
Joakim Aleksandersen's avatar
Joakim Aleksandersen committed

"""
TODO: skriv i readme om hovrdan legge til en bbox i box.json

"""
import json
import math
import os

from sentinelhub import (BBox, CRS)

def create_BBox(box):
    """ Creates a BBox for a box given in the box.json file"""

    x_coords = [coord[0] for coord in box]
    y_coords = [coord[1] for coord in box]

    return BBox((min(x_coords), min(y_coords), max(x_coords), max(y_coords)), CRS.WGS84)

def get_all_box():
    """ Reads box.json and returns every bbox, but only the the upper xy and lower xy (BBox) such that it can be used in
    sentinel get areal inf functions"""

    # but why os
    dir_path = os.path.dirname(os.path.realpath(__file__))
    file_path = os.path.join(dir_path, 'box.json')

    with open(file_path, 'r') as file:
        data = json.load(file)

    box_list = []
    if data['type'] == 'MultiPolygon':
        for polygon in data['coordinates']:
            for box in polygon:
                box_list.append(box)

    return box_list

def get_all_bbox():
    """ Returns all BBoxes, index is equal to id"""
    return [create_BBox(box) for box in get_all_box()]

def get_distance(box, point):
    """ Get the distance from a bbox to a point"""

    x_coords = [coord[0] for coord in box]
    y_coords = [coord[1] for coord in box]

    dx = max(min(x_coords) - point[0], 0, point[0] - max(x_coords))
    dy = max(min(y_coords) - point[1], 0, point[1] - max(y_coords))

    return math.sqrt(dx**2 + dy**2)

def get_closest_bbox_and_id(lon, lat):
    """ Returns the bbox closest to the cords """
    boxes = get_all_box()
    distances = [get_distance(box, (lon, lat)) for box in boxes]

    index = distances.index(min(distances))

    return create_BBox(boxes[index]), index

if __name__ == "__main__":

    test = get_closest_bbox_and_id(10.66, 60.95)

    print("efass")

    pass