Creating Random Maps with Folium in Python

  • Share this:

Code introduction


This function creates a random map using the Folium library based on a specified center point and zoom level, and optionally adds markers to the map.


Technology Stack : Folium, Python

Code Type : Function

Code Difficulty : Intermediate


                
                    
import folium
import random

def generate_random_map(center, zoom_level, markers=None):
    """
    Generates a random map using Folium with specified center and zoom level.
    Optionally adds random markers to the map.
    """
    # Create a map object centered on the specified location with the specified zoom level
    m = folium.Map(location=center, zoom=zoom_level)
    
    # If markers are provided, add them to the map
    if markers:
        for marker in markers:
            folium.Marker(
                location=marker['location'],
                popup=marker['popup'],
                icon=folium.Icon(color='green')
            ).add_to(m)
    
    return m

# Usage example
markers = [
    {'location': [34.0522, -118.2437], 'popup': 'Los Angeles'},
    {'location': [40.7128, -74.0060], 'popup': 'New York'},
    {'location': [37.7749, -122.4194], 'popup': 'San Francisco'}
]

random_map = generate_random_map(center=[34.0522, -118.2437], zoom_level=10, markers=markers)

# Save the map to an HTML file
random_map.save('random_map.html')                
              
Tags: