Creating Random Maps with Folium in Python

  • Share this:

Code introduction


This function uses the Folium library in Python to create a map based on the specified center point and zoom level, and optionally adds random markers to the map.


Technology Stack : The code uses the Folium library and technologies such as NumPy for random point generation.

Code Type : The type of code

Code Difficulty :


                
                    
def create_random_map(center, zoom, markers=None):
    """
    This function creates a random map using Folium library in Python.
    The map is centered on the specified coordinates and zoom level.
    It also optionally adds random markers to the map.
    """
    import folium
    import random
    import numpy as np

    # Create a base map with the specified center and zoom level
    m = folium.Map(location=center, zoom_start=zoom)

    # If markers are provided, add them to the map
    if markers:
        for marker in markers:
            folium.Marker(marker['location']).add_to(m)
            folium.Circle(marker['location'], radius=marker['radius'], color='red').add_to(m)

    # Generate random points around the center for demonstration purposes
    num_points = random.randint(5, 20)
    for _ in range(num_points):
        random_point = np.random.uniform(center[0] - 0.1, center[0] + 0.1, 1)
        random_point = np.random.uniform(center[1] - 0.1, center[1] + 0.1, 1)
        folium.Marker([random_point[0], random_point[1]]).add_to(m)

    return m

# Example usage
if __name__ == "__main__":
    map_instance = create_random_map(center=[45.5236, -122.6719], zoom=13)
    map_instance.save('random_map.html')