Random Color Markers on Folium Maps

  • Share this:

Code introduction


This function generates a map with random markers using the Folium library. Each marker has a popup showing the city name and the color of the marker is random.


Technology Stack : Folium

Code Type : Function

Code Difficulty : Intermediate


                
                    
import folium
import random

def random_marker_map(location, zoom_start, markers):
    """
    This function generates a map with random markers using Folium.
    """
    # Create a map object centered at the given location
    map_obj = folium.Map(location=location, zoom_start=zoom_start)
    
    # Iterate over the markers list and add each marker to the map
    for marker in markers:
        folium.Marker(
            location=marker['location'],
            popup=marker['popup'],
            icon=folium.Icon(markerrandom.choice(['red', 'blue', 'green', 'yellow', 'purple']))
        ).add_to(map_obj)
    
    # Return the map object
    return map_obj

# Example usage
markers = [
    {'location': [34.0522, -118.2437], 'popup': 'Los Angeles'},
    {'location': [40.7128, -74.0060], 'popup': 'New York'},
    {'location': [41.8781, -87.6298], 'popup': 'Chicago'}
]

random_marker_map([34.0522, -118.2437], 12, markers)                
              
Tags: