Random Point Generation Within a Polygon

  • Share this:

Code introduction


This function generates random points within a given polygon. It first generates random points within the bounding box of the polygon, and then filters out the points that are within the polygon using the `contains` method.


Technology Stack : GeoPandas, NumPy

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
import geopandas as gpd
import numpy as np
import random

def random_point_within_polygon(polygon, num_points=1):
    """
    Generates random points within a given polygon.
    """
    # Generate random points within the bounding box of the polygon
    x_coords = np.random.uniform(polygon.total_bounds[0], polygon.total_bounds[2], num_points)
    y_coords = np.random.uniform(polygon.total_bounds[1], polygon.total_bounds[3], num_points)
    random_points = gpd.points_from_xy(x_coords, y_coords)

    # Filter points that are within the polygon
    mask = polygon.contains(random_points)
    return random_points[mask]