add a function to convert graph to geojson

This commit is contained in:
Majid Rezaei 2024-06-11 10:02:08 -04:00
parent f97f4f1537
commit 60ce8c03f6
2 changed files with 56 additions and 2 deletions

View File

@ -0,0 +1,54 @@
import json
from shapely import LineString, Point
import networkx as nx
from pathlib import Path
def networkx_to_geojson(graph: nx.Graph) -> Path:
"""
Convert a NetworkX graph to GeoJSON format.
:param graph: A NetworkX graph.
:return: GeoJSON formatted dictionary.
"""
features = []
for u, v, data in graph.edges(data=True):
line = LineString([u, v])
feature = {
"type": "Feature",
"geometry": {
"type": "LineString",
"coordinates": list(line.coords)
},
"properties": {
"weight": data.get("weight", 1.0)
}
}
features.append(feature)
for node, data in graph.nodes(data=True):
point = Point(node)
feature = {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": list(point.coords)[0]
},
"properties": {
"type": data.get("type", "unknown"),
"id": data.get("id", "N/A")
}
}
features.append(feature)
geojson = {
"type": "FeatureCollection",
"features": features
}
output_geojson_file = Path('./output_files/network_graph.geojson').resolve()
with open(output_geojson_file, 'w') as file:
json.dump(geojson, file, indent=4)
return output_geojson_file

View File

@ -2,6 +2,7 @@ from DistrictHeatingNetworkCreator import DistrictHeatingNetworkCreator
from Scripts.road_processor import road_processor
from pathlib import Path
import time
from Scripts.geojson_graph_creator import networkx_to_geojson
location = [45.51663850312751, -73.59854314961274]
start_time = time.perf_counter()
roads_file = road_processor(location[1], location[0], 0.001)
@ -16,7 +17,6 @@ elapsed_time = end_time - start_time
print(f"The simulation took {elapsed_time:.4f} seconds to run.")
for node in network_graph.nodes(data=True):
print(f"Node: {node[0]}, Type: {node[1].get('type', 'unknown')}, ID: {node[1].get('id', 'N/A')}")
networkx_to_geojson(network_graph)
dhn_creator.plot_network_graph()