1. Understand the Goal: The user wants a Python script to generate interactive maps using the folium library.
-
Identify the Key Tool: folium is the standard Python library for this. It builds on Leaflet.js.
-
Determine the Scope: A simple "Hello World" map is not enough to be truly useful. A good script should demonstrate:
- Creating a base map.
- Adding markers (points of interest).
- Customizing markers (popups, tooltips, icons).
- Adding different tile layers (map styles).
- Saving the output to an HTML file.
- (Optional but good) Handling GeoJSON or heatmaps, but maybe keep it simple for a "write a script" request unless asked for advanced features. I should provide a progression from basic to intermediate features.
-
Drafting the Code Structure:
- Import:
import folium
- Step 1: Basic Map. Center coordinates (Latitude, Longitude), Zoom level.
- Step 2: Markers. Add a standard marker. Add a circle marker.
- Step 3: Interactive features. Add popups (HTML content) and tooltips.
- Step 4: Layers/Groups. Group markers together.
- Step 5: Saving. Save to
.html.
-
Refining the Content (Self-Correction/Optimization):
- Location: Let's use a famous location, like New York City (Central Park) or London, or just a generic coordinate. Let's go with London or NYC. Let's use the Eiffel Tower and other Paris landmarks as a cohesive theme. Actually, generic "User Location" comments are good, but providing specific dummy data makes the code runnable immediately. Let's use San Francisco or just general coordinates.
- Let's provide a comprehensive example. A single script that does everything is better than fragmented snippets.
-
Writing the Script (Mental Draft):
import folium
# 1. Create map
m = folium.Map(location=[45.5236, -122.6750], zoom_start=13)
# 2. Add Marker
folium.Marker([45.5236, -122.6750], popup='Portland').add_to(m)
# 3. Save
m.save('index.html')
Too simple. Let's upgrade it.
- Feature 1: Multiple Markers with different colors.
- Feature 2: Custom Icons (FontAwesome).
- Feature 3: HTML Popups.
- Feature 4: Layer Control (switching map tiles).
- Feature 5: A GeoJSON overlay? Maybe too complex for a basic request, but adding a polygon or line is good. Let's add a line between points.
-
Structuring the Output:
- Introduction: Brief explanation of
folium.
- Prerequisites:
pip install folium.
- The Code: A well-commented, runnable Python script.
- Explanation: Breakdown of what each part does (Map object, Markers, LayerControl, Saving).
- Advanced Tip: Brief mention of GeoJSON or Heatmaps.
-
Final Code Polish (Simulating the script generation):
- Define a list of locations (City names, coords).
- Iterate through them to add markers.
- Add a feature group for organization.
- Add a tile layer (e.g., "Stamen Terrain").
- Add
LayerControl to switch between tiles.
-
Constructing the response:
- Start with installation instructions.
- Provide the complete script.
- Add comments in the code.
- Explain the key components.
(Self-Correction during drafting): Make sure to handle the output file path clearly. Use os.path or just a string name. String name is fine.
-
Final Output Generation: (This matches the provided good response).
- Install:
pip install folium
- Script:
- Imports.
- Data definition (List of dicts).
- Map initialization.
- Loop to add markers.
- Add specific markers (Circle, Polyline).
- Add TileLayer.
- Add LayerControl.
- Save.
-
Review against constraints: The user asked for "a Python script". I will provide one comprehensive script that covers the most common use cases.
Refinement: I will create a scenario: "A tour of New York City landmarks". It's relatable and visually distinct.
Script Logic:
- Define NYC coords.
- List landmarks (Statue of Liberty, Empire State, etc.).
- Create Map.
- Loop landmarks -> Add Markers with Popups/Icons.
- Add a line connecting them? No, that looks messy. Just points.
- Add a "heat map" or circle marker variation? Let's stick to standard markers and a feature group.
- Add a "Measure" tool? Folium has plugins. Let's stick to core
folium to avoid plugin dependencies, but maybe mention folium.plugins for HeatMaps. Let's stick to core for the main script.
Let's go with the "Comprehensive Example" approach.
Structure of the explanation:
- Setup.
- Code block.
- Breakdown.
- How to run/view.
This looks solid. I will proceed with generating the response based on this plan.
Here is a complete guide and a Python script to generate interactive maps using the Folium library.
Prerequisites
First, you need to install the library via your terminal/command prompt:
pip install folium
The Python Script
This script covers the most common use cases: creating a base map, adding different types of markers, drawing shapes, adding layers (like Dark Mode or Satellite), and saving the result.
import folium
def create_interactive_map():
# 1. Define coordinates (Example: Central Park, NYC)
center_lat = 40.785091
center_lon = -73.968285
# 2. Create the base Map object
# zoom_start controls how close the camera is (1 = World, 15 = Street)
my_map = folium.Map(
location=[center_lat, center_lon],
zoom_start=13,
control_scale=True
)
# ---------------------------------------------------------
# 3. Add Different Tile Layers (Map Styles)
# ---------------------------------------------------------
# Layer 1: Default OpenStreetMap (already loaded as base)
# Layer 2: CartoDB Dark Matter (Dark mode style)
folium.TileLayer('cartodbdark_matter', name='Dark Mode').add_to(my_map)
# Layer 3: Stamen Terrain (Topographic style)
folium.TileLayer('stamenterrain', name='Terrain View').add_to(my_map)
# ---------------------------------------------------------
# 4. Add Markers (Points of Interest)
# ---------------------------------------------------------
# Simple Marker
tooltip_text = "Click for more info"
folium.Marker(
location=[40.785091, -73.968285],
popup="<b>Central Park</b>",
tooltip=tooltip_text,
icon=folium.Icon(color='green', icon='leaf')
).add_to(my_map)
# Circular Marker (Radius in pixels)
folium.CircleMarker(
location=[40.779437, -73.963244],
radius=30,
popup='The Metropolitan Museum of Art',
color='crimson',
fill=True,
fill_color='crimson'
).add_to(my_map)
# ---------------------------------------------------------
# 5. Add Shapes (Lines and Polygons)
# ---------------------------------------------------------
# Define coordinates for a walking path (Line)
path_coords = [
[40.785091, -73.968285],
[40.780000, -73.960000],
[40.775000, -73.955000]
]
folium.PolyLine(
locations=path_coords,
color='blue',
weight=5,
opacity=0.8,
tooltip='Walking Path'
).add_to(my_map)
# ---------------------------------------------------------
# 6. Add Layer Control (Toggle layers on/off)
# ---------------------------------------------------------
folium.LayerControl().add_to(my_map)
# ---------------------------------------------------------
# 7. Save the map to an HTML file
# ---------------------------------------------------------
output_file = "interactive_map.html"
my_map.save(output_file)
print(f"Map successfully generated and saved as '{output_file}'")
# Return the map object (useful if running inside Jupyter Notebook)
return my_map
if __name__ == "__main__":
create_interactive_map()
How to Run It
- Save the code above into a file named
map_gen.py.
- Run it in your terminal:
python map_gen.py.
- A file named
interactive_map.html will be created in the same folder.
- Open that HTML file with any web browser (Chrome, Firefox, Edge) to see your interactive map.
Explanation of Key Features
folium.Map(...): This initializes the map. You must provide a starting [latitude, longitude].
folium.Marker(...): Creates the standard pin icon.
popup: The HTML content that appears when you click the pin.
tooltip: The text that appears when you hover over the pin.
icon: Allows you to change the color and symbol (using Bootstrap icon names).
folium.TileLayer(...): Allows you to switch the "skin" of the map. Folium supports OpenStreetMap, Stamen, CartoDB, and many others.
folium.LayerControl(): This adds a button in the top-right corner of the map (the "hamburger" icon) that allows the user to switch between the Tile Layers you added (e.g., switch from Street view to Dark Mode).
my_map.save(...): Converts the Python object into an HTML file containing JavaScript code that your browser can run.
Advanced Tip: Heatmaps
If you have a dataset with thousands of points and want to visualize density (e.g., crime rates or traffic), Folium has a plugin for Heatmaps:
from folium.plugins import HeatMap
# Assuming 'data' is a list of [lat, lon] pairs
data = [[40.7, -73.9], [40.72, -73.92], [40.75, -73.97]]
HeatMap(data, radius=15).add_to(my_map)