Creating a Random Map with Folium in Python

  • Share this:

Code introduction


This function creates a map using the Folium library, specifying the center point, zoom level, and markers. The map is saved as an HTML file.


Technology Stack : Folium

Code Type : Function

Code Difficulty : Intermediate


                
                    
import folium
import random

def generate_random_map(center, zoom_start, markers):
    """
    This function generates a random map with specified center, zoom level, and markers.
    """
    # Create a map object centered at the specified location with the specified zoom level
    m = folium.Map(location=center, zoom_start=zoom_start)
    
    # Add markers to the map at random locations
    for marker in markers:
        lat, lon = marker
        folium.Marker([lat, lon]).add_to(m)
    
    # Save the map to an HTML file
    m.save('random_map.html')
    return m

# Example usage:
# Define the center of the map and the initial zoom level
center = [34.0522, -118.2437]  # Los Angeles, California
zoom_start = 12

# Define a list of random coordinates for markers
markers = [(34.0522 + random.random(), -118.2437 + random.random()) for _ in range(5)]

# Generate the map
map_instance = generate_random_map(center, zoom_start, markers)                
              
Tags: