Creating an Interactive Bus Transit Route Map and Distance Calculation with Python: A Stepwise Guide.

David Gyesi Biney
3 min readNov 19, 2023

--

Introduction:

Digital mapping has revolutionized the way we visualize and analyze spatial data, providing valuable insights into geographical patterns and facilitating efficient navigation. In this stepwise guide, we will explore how to create a dynamic and interactive digital map showcasing a bus transit route using popular Python libraries such as Folium, Pandas, and Google Sheets integration. Additionally, we’ll calculate distances between transit routes to enhance the analytical capabilities of our map.

Whether you’re a data scientist, GIS enthusiast, or someone keen on exploring the capabilities of digital mapping, this tutorial will walk you through the process of visualizing bus transit routes, adding markers, creating polylines, and calculating distances. By the end, you’ll have a powerful map that can be shared, analyzed, and further customized to meet specific needs.

Let’s embark on this journey to seamlessly integrate geographic data into a compelling and informative digital map!

Step 1: Mount Google Drive

# Mount Google Drive
from google.colab import drive
drive.mount('/content/drive')

Step 2: Import Required Libraries

# Import necessary libraries
from google.colab import auth
auth.authenticate_user()
import pandas as pd
import folium
import gspread
from google.auth import default

Step 3: Load Data from Google Sheets

# Load data from Google Sheets
data = pd.read_csv('/content/drive/MyDrive/sample bus route coordinates - Sheet1.csv')
data.head()

Step 4: Authenticate with Google Sheets and Create Worksheet

# Authenticate with Google Sheets
credentials, _ = default()

# Authorize the application
gs = gspread.authorize(credentials)

# Create a new worksheet in Google Sheets
spreadsheet = gs.create('coordinate_data')

# Get the first sheet of the created worksheet
worksheet = spreadsheet.get_worksheet(0)

# Update the worksheet with data
worksheet.update([data.columns.tolist()] + data.values.tolist())

Step 5: Create a Folium Map

# Create a Folium map
pt = folium.Map(location=[43.253320172012685, -79.86928707988771], zoom_start=12)

Step 6: Extract Latitude and Longitude from Coordinates

# Extract latitude and longitude from the 'coordinates' column
data[['pt_lat', 'pt_lng']] = data.coordinates.str.split(',', expand=True).astype(float).values.tolist()

Step 7: Add Markers and Polyline to the Map

# Add markers to the map
# Create an empty list to store latitude and longitude pairs
points = []
for index, latitude in enumerate(data['pt_lat']):
folium.Marker([latitude, data['pt_lng'][index]],
popup='Bus station{} \n'.format(index),
icon=folium.Icon(color='red', icon_color='blue', prefix='fa', icon='bus')).add_to(pt)

# Create a polyline
points = list(zip(data['pt_lat'], data['pt_lng']))
folium.PolyLine(locations=points, color='red', dash_array='5', opacity=0.85, tooltip='transit_route').add_to(pt)

Step 8: Save and Display the Map

# Save the map as an HTML file
pt.save('bus_stations_map.html')

# Display the map
pt
Output of GIS display of variable pt.

Step 9: Calculate Distance between Transit Routes

# Import geopy for distance calculation
from geopy.distance import geodesic

# Function to calculate distance between two points using Haversine formula
def calculate_distance(point1, point2):
return geodesic(point1, point2).miles

# Create a new column 'distance' to store the distance at each transit route
data['distance'] = 0.0 # Initialize with 0.0

# Iterate over rows and calculate distance for each row
for i in range(1, len(data)):
coords1 = (data['pt_lat'][i - 1], data['pt_lng'][i - 1])
coords2 = (data['pt_lat'][i], data['pt_lng'][i])
distance = calculate_distance(coords1, coords2)
data.at[i, 'distance'] = distance

data.head()

Notwithstanding this a link notebook: https://nbviewer.org/github/gyesibiney/Digital-mapping/blob/main/digital_mapping.ipynb#

Conclusion:

This stepwise guide covers loading data, creating a Folium map, visualizing bus transit routes, saving the map, and calculating distances between transit routes. Feel free to adapt the steps based on your specific requirements!

References:

THANK YOU FOR READING

contact: gyesidavid@gmail.com,

www.linkedin.com/in/david-gyesi-biney

--

--