Python Map Visualization: See a route you'll never regret (feat. folium package)
When you're planning a trip to somewhere you've never been before, don't you wish you could see the entire route? In today's post, you'll learn how to visualize your travel route using Python map visualization techniques. We'll use Python's powerful folium libraryto visually represent this journey step by step.
Here's a hypothetical situation JFK Airportand take a taxi or Uber to the Hilton New York Midtown After you get to your hotel, walk to the Manhattan Center Go to the venue. In this tutorial, Python Map Visualization Build your skills and learn how to plot your travel route on a map.
Understanding Python Map Visualization Summaries
Python Map Visualization is a powerful tool for visually representing a variety of data on a map using GPS coordinates. In particular, the folium library allows you to create Google Maps-like maps in Python.
In this example, you'll see how to add markers to three major points in New York City (JFK Airport, the Hilton New York Midtown hotel, and the Manhattan Center venue), show a route connecting each point with a blue line, and display travel time and distance information on the map.
Python code step-by-step
1. Install and load the library
To visualize a map in Python folium Install and import the library.
# import required libraries
import os # Module for manipulating files and directories
import folium # Library for creating and manipulating maps
Create a directory to store # results
result_dir = 'C:/result/'
# os.makedirs(): Create directory. Option exist_ok=True to avoid errors if it already exists
os.makedirs(result_dir, exist_ok=True)2. set up key locations and distance and time data
Define the GPS coordinates for each place, set the distance and estimated time between the two points.
# Geographical coordinates of major places (latitude, longitude)
simplified_locations = {
"JFK Airport": [40.6413, -73.7781],
"Hilton New York Midtown": [40.7625, -73.9780],
"Event Venue (Manhattan Center)": [40.7527, -73.9932]
}
# distance (km) and time (minutes) information
simplified_distances_and_times = {
("JFK Airport", "Hilton New York Midtown"): (25.0, 35),
("Hilton New York Midtown", "Event Venue (Manhattan Center)"): (1.2, 15)
}
Set the # route order
ordered_locations = [
("JFK Airport", "Hilton New York Midtown"),
("Hilton New York Midtown", "Event Venue (Manhattan Center)")
]3. create maps and visualize routes
Create a map centered on New York City, add numbered markers to each point, and connect routes with blue lines.
# Map Creation
# folium.Map(): Create a basic map
# location: coordinates of the center point of the map [latitude, longitude]
# zoom_start: initial zoom level (higher zooms more)
m = folium.Map(location=[40.7200, -73.9000], zoom_start=11)
Add # markers and paths
# enumerate(): Returns the elements of the list together with their indexes, with indexes starting at 1 with start=1
for idx, location in enumerate(simplified_locations.items(), start=1):
loc_name, coords = location
# folium.Marker(): Add a marker to the map
# popup: text to display when clicking on the marker
# icon: set the appearance of the marker
folium.Marker(
coords,
popup=f"{idx}. {loc_name}",
icon=folium.DivIcon(
html=f""""
<div style="text-align: center;">
<div style="font-size: 12pt; font-weight: bold; color: black; background-color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;">
{idx}
</div>
<div style="font-size: 10pt; font-weight: bold; color: navy; margin-top: 10px;">
{loc_name}
</div>
</div>"""
)
).add_to(m)
Add a # route and distance/time information
for (loc1, loc2) in ordered_locations:
# folium.PolyLine(): Draw a line between two points
# color: color of the line, weight: thickness of the line, opacity: transparency of the line
folium.PolyLine([simplified_locations[loc1], simplified_locations[loc2]], color="blue", weight=2.5, opacity=1).add_to(m)
# Get distance and time information
distance_km, time_min = simplified_distances_and_times[(loc1, loc2)]
# Calculate the midpoint coordinates of two points
mid_point = [(simplified_locations[loc1][0] + simplified_locations[loc2][0]) / 2,
(simplified_locations[loc1][1] + simplified_locations[loc2][1]) / 2]
Add a marker with distance and time information at the midpoint of #
folium.Marker(
mid_point,
icon=folium.DivIcon(
html=f'<div style="font-size: 10pt; font-weight: bold; color: red;">{distance_km}km, {time_min}minutes</div>',
)
).add_to(m)4. save the map
Save the completed map to the C:\result folder, and if it completes successfully, it will output the path where the saved map HTML file is saved as shown below.
# Save map as HTML
# os.path.join(): Generate file paths using path separators specific to the operating system
final_corrected_map_path = os.path.join(result_dir, 'ny_business_trip_final_corrected_map_with_distances.html')
m.save(final_corrected_map_path) # Save the generated map as an HTML file
print(f"Map saved to: {final_corrected_map_path}") # Print the path to the saved file
To view the finished map in a browser, all you need to do is click on the HTML file in its folder, as shown below, and you'll see what we asked for.


4. frequently asked questions (FAQ)
Q1. In a Python map visualization, how do I create a foliumdoes?
A1. foliumis a library that helps you visualize map data using Python. It allows you to visually represent your data in the same way as Google Maps.
Q2. How do I find the coordinates?
A2. Use Google Maps to search for the desired location, then right-click on the location icon and select the coordinates (40.648275456129724, -73.78004682462297) to copy them.

Q3. Is it possible to visualize more complex paths?
A3. Yes, you can. You can extend it by adding more locations, displaying real-time traffic information, and more. You can use the source code in this post to tell the AI what you want to order and have it code it for you.
Q4. Can I save the results of a Python map visualization as an image?
A4. foliumis saved as an HTML file by default, selenium(we'll cover this in a separate post), or you can use a non-programmatic Keyboard shortcut (win+shift+s)to capture a map displayed in HTML.
Organize
In this post, you learned how to use Python map visualization to visually represent travel routes in New York City. This process helps you intuitively understand your data and makes it easy to visualize even complex travel routes or logistics movements. Share this post with Content of AI-enabled promptsto visualize different travel routes, or add more data for an extended project!
If you're preparing a full travel plan, including budget, itinerary, and more, including Python map visualizations, check out this post (Can you plan a ChatGPT trip for Chinese New Year 2024 (feat. map directions)?) for another insight.
#Full integration code
Copy and paste the code below into an integrated development environment such as VS code and execute it. However, if the folium package is not installed, you will get the following warning. You can install the package with the pip install folium command (pip install folium) in the terminal and then execute the integration code below.

# import required libraries
import os # Modules for file system manipulation (directory creation, file path manipulation, etc.)
import folium # Library for creating interactive maps
Create a directory to store # results
result_dir = 'C:/result/'
# os.makedirs(): Create directory. Option exist_ok=True to avoid error if it already exists
os.makedirs(result_dir, exist_ok=True)
# Set coordinates of key places (latitude, longitude)
simplified_locations = {
"JFK Airport": [40.6413, -73.7781],
"Hilton New York Midtown": [40.7625, -73.9780],
"Event Venue (Manhattan Center)": [40.7527, -73.9932]
}
# distance (km) and time (minutes) information
simplified_distances_and_times = {
("JFK Airport", "Hilton New York Midtown"): (25.0, 35),
("Hilton New York Midtown", "Event Venue (Manhattan Center)"): (1.2, 15)
}
Set the # route order
ordered_locations = [
("JFK Airport", "Hilton New York Midtown"),
("Hilton New York Midtown", "Event Venue (Manhattan Center)")
]
# Create a map
# folium.Map(): Create a basic map
# location: Coordinates of the center point of the map [latitude, longitude].
# zoom_start: initial zoom level (higher zooms more)
m = folium.Map(location=[40.7200, -73.9000], zoom_start=11)
Add # markers and paths
# enumerate(): Returns the elements of the list together with their indexes, with indexes starting at 1 with start=1
for idx, location in enumerate(simplified_locations.items(), start=1):
loc_name, coords = location
# folium.Marker(): Add a marker to the map
# popup: text to display when clicking on the marker
# icon: set the appearance of the marker
folium.Marker(
coords,
popup=f"{idx}. {loc_name}",
icon=folium.DivIcon(
html=f""""
<div style="text-align: center;">
<div style="font-size: 12pt; font-weight: bold; color: black; background-color: white; border-radius: 50%; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center;">
{idx}
</div>
<div style="font-size: 10pt; font-weight: bold; color: navy; margin-top: 10px;">
{loc_name}
</div>
</div>"""
)
).add_to(m)
Add a # route and distance/time information
for (loc1, loc2) in ordered_locations:
# folium.PolyLine(): Draw a line between two points
# color: color of the line, weight: thickness of the line, opacity: transparency of the line
folium.PolyLine([simplified_locations[loc1], simplified_locations[loc2]], color="blue", weight=2.5, opacity=1).add_to(m)
# Get distance and time information
distance_km, time_min = simplified_distances_and_times[(loc1, loc2)]
# Calculate the midpoint coordinates of two points
mid_point = [(simplified_locations[loc1][0] + simplified_locations[loc2][0]) / 2,
(simplified_locations[loc1][1] + simplified_locations[loc2][1]) / 2]
Add a marker with distance and time information at the midpoint of #
folium.Marker(
mid_point,
icon=folium.DivIcon(
html=f'<div style="font-size: 10pt; font-weight: bold; color: red;">{distance_km}km, {time_min}minutes</div>',
)
).add_to(m)
# Save map as HTML
# os.path.join(): Generate file paths using path separators specific to the operating system
final_corrected_map_path = os.path.join(result_dir, 'ny_business_trip_final_corrected_map_with_distances.html')
m.save(final_corrected_map_path) # Save the generated map as an HTML file
print(f"Map saved to: {final_corrected_map_path}") # Print the path to the saved file





