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 polygon object and an optional number of points parameter, and returns a list of points.
Technology Stack : GeoPandas, Shapely, NumPy, Pandas
Code Type : Custom function
Code Difficulty : Intermediate
import numpy as np
import pandas as pd
import geopandas as gpd
from shapely.geometry import Point
def random_point_within_polygon(polygon, num_points=1):
"""
Generates random points within a given polygon.
Parameters:
polygon (shapely.geometry.Polygon): The polygon within which to generate points.
num_points (int, optional): The number of random points to generate. Default is 1.
Returns:
list of shapely.geometry.Point: A list of random points within the polygon.
"""
points = []
for _ in range(num_points):
random_point = Point(np.random.uniform(polygon.bounds[0], polygon.bounds[2]),
np.random.uniform(polygon.bounds[1], polygon.bounds[3]))
if polygon.contains(random_point):
points.append(random_point)
return points