GMaps Tiling Script

From OpenStreetMap Wiki
Jump to: navigation, search
#!/usr/bin/python

from os import mkdir
from os.path import exists
from PIL import Image
import sys
import getopt
import math

OUTPUT_DIR = ""
INPUT_DIR = ""

__doc__ = """

example:

$ create_map_pngs
 -x, --start-x (start x name)
 -y, --start-y (start y name) 
 -z, --zoom (zoom level)
 -n, --name (png's name)
 -f, --file
 -h, --help
      
"""

class Usage(Exception):
    def __init__(self, msg):
        self.msg = msg

def main(argv=None):

    # harvest command parameters
    PNGSIZE = 256
    startx = 123
    starty = 456
    zoom = 5
    filename = ""
    name = "osm"

    if argv is None:
        argv = sys.argv
    try:
        try:
            opts, args = getopt.getopt(argv[1:],"x:y:z:n:f:h",
                                       ["start-x=", "start-y=", "zoom=", "name=", "file=", "help"])
        except getopt.error, msg:
             raise Usage(msg)

        for option, value in opts:
            if option in ("-x", "--start-x"):
                startx = int(value)
            if option in ("-y", "--start-y"):
                starty = int(value)
            if option in ("-z", "--zoom"):
                zoom = int(value)
            if option in ("-n", "--name"):
                name = value
            if option in ("-f", "--file"):
                filename = value
            if option in ("-h", "--help"):
                raise Usage(__doc__)

        
        # prepare directories ...

	dirs = []
        dirs.append(OUTPUT_DIR+name)
        dirs.append(OUTPUT_DIR+name+'/'+str(zoom))

	for dir in dirs:
            if not exists(dir):
               mkdir(dir)

        if filename == "" : raise Usage('Filename required')

        # process file ...
        im = Image.open(INPUT_DIR+filename)
	im_w  = im.size[0]
	im_h  = im.size[1]
	im_wn = int( math.ceil( im_w / PNGSIZE ) )
	im_hn = int( math.ceil( im_h / PNGSIZE ) )

        try:
	    for i in range( im_wn + 1):  #range( im_wn + 1 ):
	        for j in range( im_hn + 1 ):

	            newim = im.crop((i*PNGSIZE,j*PNGSIZE,(i+1)*PNGSIZE,(j+1)*PNGSIZE))
	            x = startx + i
	            y = starty + j

                    dirs = [] 
	            dirs.append(OUTPUT_DIR+name+'/'+str(zoom)+'/'+str(x))
                    # dirs.append(OUTPUT_DIR+name+'/'+str(zoom)+'/'+str(x)+'/'+str(y))

	            for dir in dirs:
	                if not exists(dir):
                           mkdir(dir)

	            imname = OUTPUT_DIR + "%s/%d/%d/%s_%d_%d_%d.png" % (name,zoom,x,name,zoom,x,y)
	            print imname
                    try:
  	              newim.save(imname,im.format)
                    except:
                      print 'ERROR while writing file!'
        except:
          print 'ERROR while splitting file!'

    except Usage, err:
        print >>sys.stderr, "\n" + sys.argv[0].split("/")[-1] + ": " + str(err.msg)
        print >>sys.stderr, "\nfor help use --help\n"
        return 2


if __name__ == "__main__":
   sys.exit(main())