Random Map Generator with Folium

  • Share this:

Code introduction


This function generates a random map with markers using the Folium library. The map is centered on the given latitude and longitude, and the zoom level is specified by the function parameters. The colors of the markers are randomly chosen.


Technology Stack : Folium

Code Type : Map generation

Code Difficulty : Intermediate


                
                    
import folium
import random

def generate_random_map(center, zoom_level, markers=None):
    """
    Generates a random map with markers using Folium library.
    """
    # Create a map centered on the given latitude and longitude
    m = folium.Map(location=center, zoom_start=zoom_level)
    
    # Add random markers to the map if provided
    if markers:
        for marker in markers:
            folium.Marker(
                location=marker,
                popup=f"Marker at {marker}",
                icon=folium.Icon(color=random.choice(['red', 'green', 'blue']))
            ).add_to(m)
    
    # Save the map to an HTML file
    m.save('random_map.html')

# Example usage
markers = [(34.052235, -118.243683), (40.712776, -74.005974), (37.774929, -122.419416)]
generate_random_map(center=[34.052235, -118.243683], zoom_level=10, markers=markers)                
              
Tags: