Given a polygon in JSON, I want to obtain a square grid of coordinates inside a polygon, each 1km apart.
Here is a function that I've written, it's generating coordinates but in some situations I get a grid of coordinates with a spacing of 1.2 km or 0.8km, but I want that distance to be 1km.
def generate_coords_inside_polygon(self, polygon):
try:
bbox = self.helpers.get_polygon_bbox(polygon)
print(bbox)
min_lat, min_lon, max_lat, max_lon = bbox
earth_radius = 6371 # Earth's radius in kilometers
coordinates = []
generated_coords = set()
# Start from the minimum latitude and longitude
current_lat = float(min_lat)
current_lon = float(min_lon)
while current_lat <= float(max_lat):
while float(current_lon) <= float(max_lon):
coordinates.append((current_lon, current_lat))
# Move 1 kilometer to the right (longitude)
# change radius, default 0.2
desired_radius = 1
current_lon += (desired_radius / (earth_radius *
math.cos(math.radians(current_lat))) * 180 / math.pi)
# Reset longitude and move 1 kilometer up (latitude)
current_lon = float(min_lon)
current_lat += desired_radius / earth_radius * 180 / math.pi
for coord in coordinates:
# Check if the point is inside the polygon
cordy = (coord[1], coord[0])
if self.helpers.is_point_in_polygon(polygon, cordy):
generated_coords.add(coord)
This is an example of a polygon:
{
"type": "Feature",
"properties": {},
"geometry": {
"coordinates": [
[
[
2.6561338107105144,
39.59548436489257
],
[
2.62735831717211,
39.587478110591746
],
[
2.6263660587749484,
39.56957313871746
],
[
2.66331309205961,
39.569078212002836
],
[
2.673994461871615,
39.579111036117354
],
[
2.6559587062871515,
39.59409008377054
],
[
2.6561338107105144,
39.59548436489257
]
]
],
"type": "Polygon"
}
}