From 6e1b8aadf04460da4b83d3118d674d7aa07abc27 Mon Sep 17 00:00:00 2001 From: Majid Rezaei Date: Mon, 10 Jun 2024 09:34:19 -0400 Subject: [PATCH] add: road processor functionality --- Scripts/road_processor.py | 56 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Scripts/road_processor.py diff --git a/Scripts/road_processor.py b/Scripts/road_processor.py new file mode 100644 index 0000000..1bc324a --- /dev/null +++ b/Scripts/road_processor.py @@ -0,0 +1,56 @@ +from pathlib import Path +from shapely.geometry import Polygon, Point, shape +import json + + +def road_processor(x, y, diff): + """ + Processes a GeoJSON file to find roads that have at least one node within a specified polygon. + + Parameters: + x (float): The x-coordinate of the center of the selection box. + y (float): The y-coordinate of the center of the selection box. + diff (float): The half-width of the selection box. + + Returns: + str: The file path of the output GeoJSON file containing the selected roads. + """ + diff += 2 * diff + # Define the selection polygon + selection_box = Polygon([ + [x + diff, y - diff], + [x - diff, y - diff], + [x - diff, y + diff], + [x + diff, y + diff] + ]) + + # Define input and output file paths + geojson_file = Path("./input_files/roads.json").resolve() + output_file = Path('./input_files/output_roads.geojson').resolve() + + # Initialize a list to store the roads in the region + roads_in_region = [] + + # Read the GeoJSON file + with open(geojson_file, 'r') as file: + roads = json.load(file) + line_features = [feature for feature in roads['features'] if feature['geometry']['type'] == 'LineString'] + + # Check each road feature + for feature in line_features: + road_shape = shape(feature['geometry']) + # Check if any node of the road is inside the selection box + if any(selection_box.contains(Point(coord)) for coord in road_shape.coords): + roads_in_region.append(feature) + + # Create a new GeoJSON structure with the selected roads + output_geojson = { + "type": "FeatureCollection", + "features": roads_in_region + } + + # Write the selected roads to the output file + with open(output_file, 'w') as outfile: + json.dump(output_geojson, outfile) + + return output_file