Skip to content

Instantly share code, notes, and snippets.

@zabop
Created August 4, 2025 13:42
Show Gist options
  • Select an option

  • Save zabop/240fef277c0872ce6b63c7464763ea04 to your computer and use it in GitHub Desktop.

Select an option

Save zabop/240fef277c0872ce6b63c7464763ea04 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "617d9adc",
"metadata": {},
"outputs": [],
"source": [
"from typing import Literal, Callable\n",
"import shapely.geometry\n",
"import geopandas as gpd\n",
"import numpy as np\n",
"\n",
"maxc = 20037508.342789244\n",
"sidelength: Callable[[int], float] = lambda z: 2 * maxc / (2**z)\n",
"\n",
"def get_ulx_uly_lrx_lry(\n",
" z: int, x: int, y: int\n",
") -> tuple[\n",
" float, float, float, float\n",
"]: # upper left x, upper left y, lower right x, lower right y\n",
"\n",
" ulx = -maxc + sidelength(z) * x\n",
" uly = maxc - sidelength(z) * y\n",
"\n",
" lrx = -maxc + sidelength(z) * (x + 1)\n",
" lry = maxc - sidelength(z) * (y + 1)\n",
"\n",
" return ulx, uly, lrx, lry\n",
"\n",
"z,x,y = 11,1085,595\n",
"\n",
"pixelcount = 40\n",
"ulx, uly, lrx, lry = get_ulx_uly_lrx_lry(z,x,y)\n",
"\n",
"s = shapely.geometry.box(ulx, uly, lrx, lry)\n",
"gpd.GeoSeries(s).set_crs(3857).to_file(\"tile.geojson\")\n",
"\n",
"s = sidelength(z) / pixelcount\n",
"\n",
"pixels : list[shapely.geometry.Polygon] = []\n",
"\n",
"for col_index in range(pixelcount):\n",
" for row_index in range(pixelcount):\n",
" corners: list[np.ndarray[tuple[Literal[2]], np.dtype[np.float64]]] = []\n",
" for each in [[1, 1], [1, -1], [-1, -1], [-1, 1], [1, 1]]:\n",
" tc = np.array([ulx + s * col_index + s/2, uly - s * row_index - s / 2])\n",
" v = 0.5 * np.array([each]) * np.array([s, s])\n",
" [corner] = tc + v\n",
" corners.append(corner)\n",
" p = shapely.geometry.Polygon(corners)\n",
" pixels.append(p)\n",
"\n",
"gpd.GeoSeries(pixels).set_crs(3857).to_file(\"pixels.gpkg\")"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "226ba3e0",
"metadata": {},
"outputs": [],
"source": [
"!open ."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "venv (3.13.2)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.13.2"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment