Skip to content

Instantly share code, notes, and snippets.

@TimMcCauley
Last active January 15, 2021 08:28
Show Gist options
  • Save TimMcCauley/575cf3e5db5fc8b1ba22211ad4ee192f to your computer and use it in GitHub Desktop.
Save TimMcCauley/575cf3e5db5fc8b1ba22211ad4ee192f to your computer and use it in GitHub Desktop.
import shapely.wkt
from shapely.geometry import box
def generate_tiles():
# width and height of the tiles to generate
WIDTH, HEIGHT = 1000, 1000
# from user arbitrary polygon, could be buffered
all_bbox = shapely.wkt.loads('POLYGON ((531371.13571106398012489 5658034.45453725103288889, 544256.06067719822749496 5658034.45453725103288889, 544256.06067719822749496 5670266.97823927644640207, 531371.13571106398012489 5670266.97823927644640207, 531371.13571106398012489 5658034.45453725103288889))')
all_area = all_bbox.area
coords = all_bbox.exterior.coords
# reset x
reset_lon = coords[0][0]
# x
lon = coords[0][0]
# y
lat = coords[0][1]
covered = 0
bboxes = []
col_idx = 0
row_idx = 0
while covered < all_area:
bbox = box(lon, lat, lon + WIDTH, lat + HEIGHT)
intersection = all_bbox.intersection(bbox)
covered += intersection.area
bboxes.append(bbox)
# catch the very last top row, the first column may already intersect
if col_idx == 0 and intersection.area < bbox.area:
pass
# increase Y and reset X
elif col_idx > 0 and intersection.area < bbox.area:
# increase row
lat += HEIGHT
lon = reset_lon
col_idx = 0
row_idx += 1
continue
# just increment column index
else:
col_idx += 1
lon += WIDTH
return bboxes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment