Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Split a shapefile into many spatialite files based on TMS tiling
#!/usr/bin/env python
import logging
from optparse import OptionParser
import os
import mercantile
import subprocess
def split_file(source_path, dest_dir, zoom, mercator=False):
for x in range(0, pow(2, zoom)):
for y in range(0, pow(2, zoom)):
dest_path = os.path.join(dest_dir, "%i-%i-%i.sqlite" % (zoom, x, y))
tile_bounds = mercantile.bounds(x, y, zoom)
if mercator:
tile_ll = mercantile.xy(tile_bounds.west, tile_bounds.south)
tile_ur = mercantile.xy(tile_bounds.east, tile_bounds.north)
tile_bounds = (tile_ll[0], tile_ll[1], tile_ur[0], tile_ur[1])
command = ( "ogr2ogr" +
" -f sqlite" +
" -dsco INIT_WITH_EPSG=yes -dsco SPATIALITE=YES -lco FORMAT=SPATIALITE" +
" -spat " + " ".join([str(f) for f in tile_bounds]) +
" " + dest_path + " " + source_path )
print command
subprocess.call(command, shell=True)
def _main():
usage = "usage: %prog source.shp destination"
parser = OptionParser(usage=usage,
description="")
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("-z", "--zoom", action="store", dest="zoom", type="int",
default=4)
parser.add_option("-m", "--mercator", action="store_true", default=False, help="use epsg:3857")
(options, args) = parser.parse_args()
logging.basicConfig(level=logging.DEBUG if options.debug else
(logging.ERROR if options.quiet else logging.INFO))
if len(args) != 2:
print "Error, must specify source file and destination directory"
sys.exit(-1)
if not os.path.exists(args[0]):
print "Error: source file does not exist"
sys.exit(-1)
if os.path.exists(args[1]):
if not os.path.isdir(args[1]):
print "Error: destination is not a directory"
sys.exit(-1)
else:
os.makedirs(args[1])
split_file(args[0], args[1], options.zoom, mercator=options.mercator)
if __name__ == "__main__":
_main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.