You can download this code by clicking the button below.
This code is now available for download.
This function generates random points within a given polygon. It accepts a GeoDataFrame containing a single Polygon geometry and an optional number of points to generate. The function first checks if the input is valid, then generates points on a grid within the polygon's bounding box, and randomly selects a specified number of points from the filtered grid points.
Technology Stack : GeoPandas, NumPy
Code Type : Geographic Data Processing Functions
Code Difficulty : Intermediate
import geopandas as gpd
import numpy as np
def random_point_within_polygon(polygon, num_points=1):
"""
Generate a random point(s) within a given polygon.
:param polygon: A GeoDataFrame with one polygon geometry.
:param num_points: The number of random points to generate.
:return: A GeoDataFrame with the generated points.
"""
# Ensure the input is a GeoDataFrame with one polygon
if not isinstance(polygon, gpd.GeoDataFrame) or len(polygon.geometry.type.unique()) != 1 or polygon.geometry.type.unique()[0] != 'Polygon':
raise ValueError("Input must be a GeoDataFrame with a single Polygon geometry.")
# Create a grid of points within the polygon's bounding box
min_x, min_y, max_x, max_y = polygon.total_bounds
grid_x = np.arange(min_x, max_x, 0.01)
grid_y = np.arange(min_y, max_y, 0.01)
grid_x, grid_y = np.meshgrid(grid_x, grid_y)
# Filter grid points that are within the polygon
grid_points = gpd.GeoDataFrame(geometry=gpd.points_from_xy(grid_x.ravel(), grid_y.ravel()))
grid_points = grid_points[grid_points.geometry.within(polygon.geometry.iloc[0])]
# Randomly select points from the filtered grid points
random_points = grid_points.sample(n=num_points)
return random_points