Random Point Generation within Polygon

  • Share this:

Code introduction


This function generates one or more random points within a given polygon. It accepts a GeoDataFrame polygon and the number of points to generate as parameters. Then, it randomly selects x and y coordinates within the polygon boundaries and checks if the generated point is within the polygon. If so, it adds the point to the result list.


Technology Stack : GeoPandas, NumPy, Shapely

Code Type : Function

Code Difficulty : Intermediate


                
                    
import numpy as np
import geopandas as gpd
from shapely.geometry import Point, Polygon

def random_point_within_polygon(polygon, num_points=1):
    """
    Generate random points within a given polygon.
    
    Parameters:
    - polygon (geopandas.GeoDataFrame): Polygon to generate points within.
    - num_points (int): Number of random points to generate. Default is 1.
    
    Returns:
    - list: List of random points within the polygon.
    """
    points = []
    for _ in range(num_points):
        x = np.random.uniform(polygon.bounds[0], polygon.bounds[2])
        y = np.random.uniform(polygon.bounds[1], polygon.bounds[3])
        point = Point(x, y)
        if point.within(polygon):
            points.append(point)
    return points