Certainly! Below is a Python script that creates a simple Graphical User Interface (GUI) using tkinter. This GUI allows users to input a town name, fetches the road network for that town using OSMnx, and displays the network visually within the GUI using matplotlib.
Prerequisites
Before running the script, ensure you have the necessary libraries installed. You can install them using pip:
pip install osmnx matplotlib
Complete Python Script
import tkinter as tk
from tkinter import messagebox
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import osmnx as ox
# Configure OSMnx
ox.config(use_cache=True, log_console=False)
class RoadNetworkApp:
def __init__(self, master):
self.master = master
master.title("Road Network Viewer")
# Create and place the label
self.label = tk.Label(master, text="Enter Town Name:")
self.label.pack(pady=10)
# Create and place the entry widget
self.entry = tk.Entry(master, width=50)
self.entry.pack(pady=5)
# Create and place the fetch button
self.fetch_button = tk.Button(master, text="Fetch Road Network", command=self.fetch_network)
self.fetch_button.pack(pady=10)
# Create a frame for the matplotlib figure
self.plot_frame = tk.Frame(master)
self.plot_frame.pack(fill=tk.BOTH, expand=True)
# Initialize the matplotlib figure
self.fig, self.ax = plt.subplots(figsize=(8, 6))
self.canvas = FigureCanvasTkAgg(self.fig, master=self.plot_frame)
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def fetch_network(self):
town = self.entry.get().strip()
if not town:
messagebox.showwarning("Input Error", "Please enter a town name.")
return
try:
# Fetch the road network using OSMnx
self.ax.clear()
graph = ox.graph_from_place(town, network_type='drive')
ox.plot_graph(graph, ax=self.ax, show=False, close=False, node_size=0, edge_color='black')
self.ax.set_title(f"Road Network of {town}", fontsize=14)
self.canvas.draw()
except Exception as e:
messagebox.showerror("Error", f"An error occurred:\n{e}")
def main():
root = tk.Tk()
root.geometry("800x600")
app = RoadNetworkApp(root)
root.mainloop()
if __name__ == "__main__":
main()
Explanation of the Script
-
Imports:
tkinter: For creating the GUI.
messagebox from tkinter: For showing popup messages.
FigureCanvasTkAgg from matplotlib.backends.backend_tkagg: To embed the matplotlib plot within the tkinter window.
matplotlib.pyplot: For plotting.
osmnx: For fetching and handling the road network data.
-
OSMnx Configuration:
use_cache=True: Enables caching to speed up repeated queries.
log_console=False: Suppresses logging messages in the console.
-
RoadNetworkApp Class:
-
main Function:
- Initializes the tkinter root window.
- Sets the window size to 800x600 pixels.
- Creates an instance of the
RoadNetworkApp.
- Starts the tkinter main event loop.
-
Execution:
- The script checks if it's run as the main program and then calls the
main function to start the application.
Running the Application
-
Save the script to a file, for example, road_network_viewer.py.
-
Open a terminal or command prompt and navigate to the directory containing the script.
-
Run the script using Python:
python road_network_viewer.py
-
A window titled "Road Network Viewer" will appear.
-
Enter the name of a town or city in the input field (e.g., "San Francisco, California") and click the "Fetch Road Network" button.
-
The road network for the specified town will be displayed within the window.
Notes and Potential Enhancements
-
Error Handling: The script includes basic error handling to manage scenarios where the town name is invalid or the network cannot be fetched. You can enhance this by handling specific exceptions or guiding the user to input more precise location names (e.g., including the country or state).
-
Advanced Visualization: Currently, the road network is displayed in black lines without nodes. You can customize the visualization by changing colors, adding interactivity, or integrating with more advanced mapping libraries.
-
Performance Considerations: For larger towns or cities, fetching and plotting the entire road network might be time-consuming. Consider adding a loading indicator or limiting the area size.
-
Additional Features:
- Allow users to specify the type of network (e.g., walking, biking).
- Enable zooming and panning within the plot.
- Provide options to save the plotted network as an image or export the data.
This script provides a foundational GUI application that integrates tkinter, OSMnx, and matplotlib to fetch and display road networks based on user input. You can build upon this foundation to add more features and improve the user experience as needed.