building_selection_tool/building_selection_tool.py

87 lines
2.7 KiB
Python

"""
Building Selection Tool
SPDX - License - Identifier: LGPL - 3.0 - or -later
Copyright © 2023 Concordia CERC group
Project Coder Koa Wells kekoa.wells@concordia.ca
"""
import json
from pathlib import Path
from shapely import Polygon
from shapely import Point
import helpers
class BuildingSelectionTool:
"""
BuildingSelectionTool class
"""
def __init__(self, geojson_file_path):
geojson_file = Path(geojson_file_path).resolve()
with open(geojson_file, 'r') as file:
self.city = json.load(file)
self.buildings = self.city['features']
self.selected_buildings = []
def select_by_polygon(self, selection_polygon_coordinates):
"""
Get all buildings within a specified polygon and write the output to output_file_path
:param selection_polygon_coordinates: list of coordinates forming the selection polygon
:return: None
"""
selection_polygon = Polygon(selection_polygon_coordinates)
for building in self.buildings:
coordinates = building['geometry']['coordinates'][0]
building_polygon = Polygon(coordinates)
centroid = Point(building_polygon.centroid)
if centroid.within(selection_polygon):
self.selected_buildings.append(building)
def select_by_coordinate(self, coordinate):
"""
:param coordinate: longitude, latitude coordinate of selected
:return: None
"""
longitude = coordinate[0]
latitude = coordinate[1]
point = Point([longitude, latitude])
for building in self.buildings:
building_coordinates = building['geometry']['coordinates'][0]
building_polygon = Polygon(building_coordinates)
if point.within(building_polygon):
self.selected_buildings.append(building)
def select_by_address(self, address):
"""
Select a building by inputting an address
:param address:
:return: None
"""
coordinates = helpers.get_gps_coordinate_by_address(address)
longitude = coordinates[1]
latitude = coordinates[0]
point = Point([longitude, latitude])
for building in self.buildings:
building_coordinates = building['geometry']['coordinates'][0]
building_polygon = Polygon(building_coordinates)
if point.within(building_polygon):
self.selected_buildings.append(building)
def save_selected_buildings(self, output_file_path):
"""
Save all selected buildings to an output file.
:param output_file_path: destination file path including file name and extension
:return: None
"""
output_file = Path(output_file_path).resolve()
output_region = {"type": "FeatureCollection",
"features": self.selected_buildings}
with open(output_file, 'w') as file:
file.write(json.dumps(output_region, indent=2))