Skip to content

Instantly share code, notes, and snippets.

Created January 23, 2018 14:26
What would you like to do?
Replace tokens in a mapnik sql query with values for a specified tile
#!/usr/bin/env python3
import logging
from optparse import OptionParser
import os
import sys
import mercantile
def _main():
usage = "usage: %prog"
parser = OptionParser(usage=usage,
parser.add_option("-d", "--debug", action="store_true", dest="debug",
help="Turn on debug logging")
parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
help="turn off all logging")
parser.add_option("-t", "--tile", dest="tile", default="14/2599/6317")
(options, args) = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if options.debug else
(logging.ERROR if options.quiet else logging.INFO))
tile_tokens = options.tile.split("/")
if len(tile_tokens) != 3:
logging.error("invalid tile, must be in z/x/y format")
z, x, y = [int(f) for f in tile_tokens]
logging.debug("Using tile %d/%d/%d" % (z, x, y))
if z < 0 or z > 22:
logging.error("Error, invalid zoom")
tile_bounds = mercantile.xy_bounds(x, y, z)
if len(args) == 0 or args[0] == "-":
sql_query = "".join(sys.stdin.readlines())
with open(args[0], "r") as f:
sql_query = str(
pixel_width = 156412
scale_denominator = 559082264.028
for i in range(z):
scale_denominator = scale_denominator / 2.0
pixel_width = pixel_width / 2.0
sql_query = sql_query.replace("!bbox!",
"ST_SetSRID('BOX3D(%f %f,%f %f)'::box3d,900913)" %
(tile_bounds.left, tile_bounds.bottom, tile_bounds.right,
sql_query = sql_query.replace("!scale_denominator!", str(scale_denominator))
sql_query = sql_query.replace("!pixel_width!", str(pixel_width))
sql_query = sql_query.replace("!pixel_height!", str(pixel_width))
if __name__ == "__main__":
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment