A quick trick to create random lat/long coordinates in python (within a defined polygon)

Aayush Sethi
2 min readAug 26, 2021

--

How random is random? A question that itself is quite random. Hence, I too was puzzled when I was tasked with randomizing latitude and longitude coordinates within a predefined polygon.

After searching for solutions to this vague problem, I found the perfect set of tools to answer this question, in case next time I want my random coordinates fast and easy….

Overview

  • Polygon, In geometry, is any closed curve consisting of a set of line segments (sides) connected such that no two segments cross.
  • We will define the polygon with latitude and longitude coordinates — In order to generate random coordinates within the polygon.

I recommend using HeadWall photonics to generate the polygon coordinates.

The Sunset neighborhood in San Francisco, CA.

Importing Modules

  • Make sure to use conda install for the shapely library.
# Importing Modules
import numpy as np
import random
# Use 'conda install shapely' to import the shapely library.
from shapely.geometry import Polygon, Point

Define the shape and coordinates

# Define the desired polygon 

poly = Polygon([(37.75850848099701, -122.50833008408812), (37.75911919711413, -122.49648544907835),(37.751620611284935, -122.4937388670471),(37.74863453749236, -122.50742886185911)])

Define the randomizer function using numpy

Defining the randomization generator
def polygon_random_points (poly, num_points):
min_x, min_y, max_x, max_y = poly.bounds
points = []while len(points) < num_points:
random_point = Point([random.uniform(min_x, max_x), random.uniform(min_y, max_y)])
if (random_point.within(poly)):
points.append(random_point)
return points# Choose the number of points desired. This example uses 20 points.
points = polygon_random_points(poly,20)
# Printing the results.
for p in points:
print(p.x,",",p.y)
#OUTPUT37.75210734489673 , -122.49572485891302
37.75046506608679 , -122.50583612245225
37.75612411999306 , -122.50728172021206
37.75726922992242 , -122.50251213426036
37.75243837156798 , -122.50442682534892
37.7519789637837 , -122.50402178717827
37.750903349294404 , -122.50241414813944
37.75602225181627 , -122.50060819272488
37.757921529607835 , -122.50036152209083
37.75628955086523 , -122.50694962686946
37.7573215112949 , -122.50224043772997
37.75074935869865 , -122.50127064328588
37.7528943256246 , -122.501056716164
37.754832309416386 , -122.50268274843049
37.757352142065265 , -122.50390638094865
37.75055972208169 , -122.50381787073599
37.753482040181844 , -122.49795018201644
37.7578160107123 , -122.50013574926646
37.749592580038346 , -122.50730545397994
37.7514871501036 , -122.49702703770673

Plotting the coordinates

I used Tableau to plot the output. Looking at the picture below we can see that it clearly works and is in fact very accurate.

--

--