def test_render_grid(): """ test old method """ width,height = 256,256 m = create_grid_map(width,height) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(grid,grid_correct) eq_(resolve(grid,0,0),None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid,23,9),expected) eq_(resolve(grid,23,10),expected) eq_(resolve(grid,23,11),expected) # core eq_(resolve(grid,24,8),expected) eq_(resolve(grid,24,9),expected) eq_(resolve(grid,24,10),expected) eq_(resolve(grid,24,11),expected) eq_(resolve(grid,24,12),expected) eq_(resolve(grid,25,8),expected) eq_(resolve(grid,25,9),expected) eq_(resolve(grid,25,10),expected) eq_(resolve(grid,25,11),expected) eq_(resolve(grid,25,12),expected) # bottom row eq_(resolve(grid,26,9),expected) eq_(resolve(grid,26,10),expected) eq_(resolve(grid,26,11),expected)
def test_render_grid(): places_ds = mapnik.PointDatasource() places_ds.add_point(143.10,-38.60,'Name','South East') places_ds.add_point(142.48,-38.60,'Name','South West') places_ds.add_point(142.48,-38.38,'Name','North West') places_ds.add_point(143.10,-38.38,'Name','North East') s = mapnik.Style() r = mapnik.Rule() #symb = mapnik.PointSymbolizer() symb = mapnik.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) label = mapnik.TextSymbolizer(mapnik.Expression('[Name]'), 'DejaVu Sans Book', 10, mapnik.Color('black') ) label.allow_overlap = True label.displacement = (0,-10) #r.symbols.append(label) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = places_ds lyr.styles.append('places_labels') m = mapnik.Map(256,256) m.append_style('places_labels',s) m.layers.append(lyr) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(grid,grid_correct) eq_(resolve(grid,0,0),None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid,23,9),expected) eq_(resolve(grid,23,10),expected) eq_(resolve(grid,23,11),expected) # core eq_(resolve(grid,24,8),expected) eq_(resolve(grid,24,9),expected) eq_(resolve(grid,24,10),expected) eq_(resolve(grid,24,11),expected) eq_(resolve(grid,24,12),expected) eq_(resolve(grid,25,8),expected) eq_(resolve(grid,25,9),expected) eq_(resolve(grid,25,10),expected) eq_(resolve(grid,25,11),expected) eq_(resolve(grid,25,12),expected) # bottom row eq_(resolve(grid,26,9),expected) eq_(resolve(grid,26,10),expected) eq_(resolve(grid,26,11),expected)
def render_grid(self, grid_uri, x, y, z): bbox = self.get_bbox(x, y, z) self.m.resize(self.render_size, self.render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 # Render grid utf_grids = mapnik.render_grid(self.m, self.layer_id, fields=self.fields) if not utf_grids['keys'] or utf_grids['keys'] == [""]: utf_grids = '' json.dump(utf_grids, open(grid_uri, 'w'), encoding='utf-8')
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): """ """ start_time = time() # # Mapnik can behave strangely when run in threads, so place a lock on the instance. # if global_mapnik_lock.acquire(): try: if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax)) if self.layer_id_key is not None: grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map(str, fields) or datasource.fields() grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields) for key in grid['data']: grid['data'][key][self.layer_id_key] = self.mapnik.layers[index].name grids.append(grid) # global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) else: grid = mapnik.Grid(width, height) for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map(str, fields) or datasource.fields() mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields) # global_mapnik_lock.release() outgrid = grid.encode('utf', resolution=self.scale, features=True) except: self.mapnik = None raise finally: global_mapnik_lock.release() logging.debug('TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale)
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): """ """ start_time = time() if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug( 'TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) # # Mapnik can behave strangely when run in threads, so place a lock on the instance. # if global_mapnik_lock.acquire(): self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax)) grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource if type(fields) is list: fields = map(str, fields) else: fields = datasource.fields() grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields) grids.append(grid) global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) logging.debug( 'TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale)
def test_render_grid(): """ test old method """ width, height = 256, 256 m = create_grid_map(width, height) # print mapnik.save_map_to_string(m) ul_lonlat = mapnik.Coord(142.30, -38.20) lr_lonlat = mapnik.Coord(143.40, -38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat, lr_lonlat)) grid = mapnik.render_grid(m, 0, key="Name", resolution=4, fields=["Name"]) eq_(grid, grid_correct_old2, show_grids("old", grid, grid_correct_old2)) eq_(resolve(grid, 0, 0), None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid, 23, 9), expected) eq_(resolve(grid, 23, 10), expected) eq_(resolve(grid, 23, 11), expected)
def test_render_grid2(): """ test old against new""" width,height = 256,256 m = create_grid_map(width,height) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) # new method grid = mapnik.Grid(m.width,m.height,key='Name') mapnik.render_layer(m,grid,layer=0,fields=['Name']) utf1 = grid.encode('utf',resolution=4) eq_(utf1,grid_correct_new) # old method - to be removed utf2 = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(utf2,grid_correct) # for complex polygons these will not be true eq_(len(utf2['grid']),len(utf1['grid'])) eq_(len(utf2['keys']),len(utf1['keys'])) eq_(len(utf2['data']),len(utf1['data'])) # check a full view is the same as a full image grid_view = grid.view(0,0,width,height) # for kicks check at full res too utf3 = grid.encode('utf',resolution=1) utf4 = grid_view.encode('utf',resolution=1) eq_(utf3['grid'],utf4['grid']) eq_(utf3['keys'],utf4['keys']) eq_(utf3['data'],utf4['data']) eq_(resolve(utf4,0,0),None) # resolve some center points in the # resampled view utf5 = grid_view.encode('utf',resolution=4) eq_(resolve(utf5,25,10),{"Name": "North West"}) eq_(resolve(utf5,25,46),{"Name": "North East"}) eq_(resolve(utf5,38,10),{"Name": "South West"}) eq_(resolve(utf5,38,46),{"Name": "South East"})
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): """ """ start_time = time() if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) # # Mapnik can behave strangely when run in threads, so place a lock on the instance. # if global_mapnik_lock.acquire(): self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(mapnik.Envelope(xmin, ymin, xmax, ymax)) grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource if type(fields) is list: fields = map(str, fields) else: fields = datasource.fields() grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields) grids.append(grid) global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale)
def test_render_grid(): ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') f = mapnik.Feature(context,1) f['Name'] = 'South East' f.add_geometries_from_wkt('POINT (143.10 -38.60)') ds.add_feature(f) f = mapnik.Feature(context,2) f['Name'] = 'South West' f.add_geometries_from_wkt('POINT (142.48 -38.60)') ds.add_feature(f) f = mapnik.Feature(context,3) f['Name'] = 'North West' f.add_geometries_from_wkt('POINT (142.48 -38.38)') ds.add_feature(f) f = mapnik.Feature(context,4) f['Name'] = 'North East' f.add_geometries_from_wkt('POINT (143.10 -38.38)') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() symb = mapnik.MarkersSymbolizer() symb.width = 10 symb.height = 10 symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = ds lyr.styles.append('places_labels') m = mapnik.Map(256,256) m.append_style('places_labels',s) m.layers.append(lyr) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(grid,grid_correct) eq_(resolve(grid,0,0),None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid,23,9),expected) eq_(resolve(grid,23,10),expected) eq_(resolve(grid,23,11),expected) # core eq_(resolve(grid,24,8),expected) eq_(resolve(grid,24,9),expected) eq_(resolve(grid,24,10),expected) eq_(resolve(grid,24,11),expected) eq_(resolve(grid,24,12),expected) eq_(resolve(grid,25,8),expected) eq_(resolve(grid,25,9),expected) eq_(resolve(grid,25,10),expected) eq_(resolve(grid,25,11),expected) eq_(resolve(grid,25,12),expected) # bottom row eq_(resolve(grid,26,9),expected) eq_(resolve(grid,26,10),expected) eq_(resolve(grid,26,11),expected)
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom, auth): """ """ start_time = time() # # Mapnik can behave strangely when run in threads, so place a lock on the instance. # if global_mapnik_lock.acquire(): try: if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug( 'TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) for la in self.mapnik.layers: query = """(SELECT * FROM {} WHERE {} IN ({}) ) AS {}""".format( self.table, self.auth_column, ', '.join(str(i) for i in auth), self.table) la.datasource = mapnik.PostGIS( host=str(self.host), geometry_field=str(self.geometry_field), key_field=str(self.key_field), user=str(self.user), password=str(self.password), dbname=str(self.dbname), table=query) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax)) if self.layer_id_key is not None: grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map( str, fields) or datasource.fields() grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields) for key in grid['data']: grid['data'][key][ self. layer_id_key] = self.mapnik.layers[index].name grids.append(grid) # global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) else: grid = mapnik.Grid(width, height) for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map( str, fields) or datasource.fields() mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields) # global_mapnik_lock.release() outgrid = grid.encode('utf', resolution=self.scale, features=True) except: self.mapnik = None raise finally: global_mapnik_lock.release() logging.debug( 'TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale)
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom, auth): """ """ start_time = time() # # Mapnik can behave strangely when run in threads, so place a lock on the instance. # if global_mapnik_lock.acquire(): try: if self.mapnik is None: self.mapnik = get_mapnikMap(self.mapfile) logging.debug('TileStache.Mapnik.GridProvider.renderArea() %.3f to load %s', time() - start_time, self.mapfile) for la in self.mapnik.layers: query = """(SELECT * FROM {} WHERE {} IN ({}) ) AS {}""".format(self.table, self.auth_column, ', '.join(str(i) for i in auth), self.table) la.datasource = mapnik.PostGIS( host=str(self.host), geometry_field=str(self.geometry_field), key_field=str(self.key_field), user=str(self.user), password=str(self.password), dbname=str(self.dbname), table=query) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(Box2d(xmin, ymin, xmax, ymax)) if self.layer_id_key is not None: grids = [] for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map(str, fields) or datasource.fields() grid = mapnik.render_grid(self.mapnik, index, resolution=self.scale, fields=fields) for key in grid['data']: grid['data'][key][self.layer_id_key] = self.mapnik.layers[index].name grids.append(grid) # global_mapnik_lock.release() outgrid = reduce(merge_grids, grids) else: grid = mapnik.Grid(width, height) for (index, fields) in self.layers: datasource = self.mapnik.layers[index].datasource fields = (type(fields) is list) and map(str, fields) or datasource.fields() mapnik.render_layer(self.mapnik, grid, layer=index, fields=fields) # global_mapnik_lock.release() outgrid = grid.encode('utf', resolution=self.scale, features=True) except: self.mapnik = None raise finally: global_mapnik_lock.release() logging.debug('TileStache.Mapnik.GridProvider.renderArea() %dx%d at %d in %.3f from %s', width, height, self.scale, time() - start_time, self.mapfile) return SaveableResponse(outgrid, self.scale)
def test_render_grid(): ds = mapnik.MemoryDatasource() context = mapnik.Context() context.push('Name') f = mapnik.Feature(context,1) f['Name'] = 'South East' f.add_geometries_from_wkt('POINT (143.10 -38.60)') ds.add_feature(f) f = mapnik.Feature(context,2) f['Name'] = 'South West' f.add_geometries_from_wkt('POINT (142.48 -38.60)') ds.add_feature(f) f = mapnik.Feature(context,3) f['Name'] = 'North West' f.add_geometries_from_wkt('POINT (142.48 -38.38)') ds.add_feature(f) f = mapnik.Feature(context,4) f['Name'] = 'North East' f.add_geometries_from_wkt('POINT (143.10 -38.38)') ds.add_feature(f) s = mapnik.Style() r = mapnik.Rule() symb = mapnik.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = ds lyr.styles.append('places_labels') m = mapnik.Map(256,256) m.append_style('places_labels',s) m.layers.append(lyr) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(grid,grid_correct) eq_(resolve(grid,0,0),None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid,23,9),expected) eq_(resolve(grid,23,10),expected) eq_(resolve(grid,23,11),expected) # core eq_(resolve(grid,24,8),expected) eq_(resolve(grid,24,9),expected) eq_(resolve(grid,24,10),expected) eq_(resolve(grid,24,11),expected) eq_(resolve(grid,24,12),expected) eq_(resolve(grid,25,8),expected) eq_(resolve(grid,25,9),expected) eq_(resolve(grid,25,10),expected) eq_(resolve(grid,25,11),expected) eq_(resolve(grid,25,12),expected) # bottom row eq_(resolve(grid,26,9),expected) eq_(resolve(grid,26,10),expected) eq_(resolve(grid,26,11),expected)
def GET(self, tilename, z, x, y, sffx): z = int(z) x = int(x) y = int(y) if (z < 0 or z > 19): return '' cType = { "png":"image/png", "json":"text/plain" } qs = web.input(r='',x='',q='') isCache = False if qs.r == '': isCache = True output = False tilep = Tilep() web.header("Access-Control-Allow-Origin", "*") dbfilet = tilep.getDb(tilename) if dbfilet: cont = lite.connect(dbfilet) curt = cont.cursor() if isCache and dbfilet: if (qs.q == '') : sql = "SELECT * from tiles WHERE z = ? AND x = ? AND y = ? AND sffx = ? AND (q is null or q = ?);" else : sql = "SELECT * from tiles WHERE z = ? AND x = ? AND y = ? AND sffx = ? AND q = ?;" curt.execute(sql,[z,x,y,sffx,qs.q]) rows = curt.fetchall() for row in rows: output = zlib.decompress(row[7]) if output: web.header("Content-Type", cType[sffx]) return output if not output: isforce = True if qs.x == '': isforce = False xmlstr = tilep.getXml(tilename,isforce,qs.q) if not xmlstr: return '' else: box = tilep.getBbox(z=z,x=x,y=y) geo_extent = Box2d(box[0],box[1],box[2],box[3]) geo_proj = Projection('+init=epsg:4326') merc_proj = Projection('+init=epsg:3857') transform = ProjTransform(geo_proj,merc_proj) merc_extent = transform.forward(geo_extent) mp = mapnik.Map(256,256) mapnik.load_map_from_string(mp,xmlstr) mp.zoom_to_box(merc_extent) if sffx == 'png': im = Image(mp.width,mp.height) mapnik.render(mp,im) output = im.tostring('png') if dbfilet: minx = box[0] miny = box[1] maxx = box[2] maxy = box[3] sql = "INSERT INTO tiles VALUES (?,?,?,?,?,?,?,?,?,?);" curt.execute(sql,[z,x,y,minx,miny,maxx,maxy,lite.Binary(zlib.compress(output)),sffx,qs.q]) cont.commit() curt.close() #if zoomcache >= z : # mapnik.render_to_file(mp, str(afile)) web.header("Content-Type", cType[sffx]) return output elif sffx == 'json': xmldoc = minidom.parseString(xmlstr) itemlist = xmldoc.getElementsByTagName('Layer') nlay = len(itemlist) fields = [] resolution = 4 #Pixel resolution of output. li = 0 for ly in range(0, nlay): resolution = 4 dat = itemlist[ly].getElementsByTagName('Datasource')[0] par = dat.getElementsByTagName('Parameter') for s in par : dv = s.attributes['name'].value dck = False if (dv[6:] == ''): dck = True elif (dv[6:].isdigit()): dck = (z >= int(dv[6:])) if dv[:6] == 'fields' and dck and fields == [] : text = s.childNodes[0].nodeValue.encode("utf-8") fields = text.split(",") li = ly if dv == 'resolution': res = s.childNodes[0].nodeValue.encode("utf-8") resolution = int(res) layer_index = li #First layer on the map - index in m.layers key = "__id__" #Field used for the key in mapnik (should probably be unique) enfix = "" #if ly > 0: # enfix = "_"+str(ly) #return str(len(fields)) if len(fields) > 0: d = mapnik.render_grid(mp, layer_index, key, resolution, fields) #returns a dictionary output = "grid("+json.dumps(d)+")" else: output = '' if output != '': if dbfilet: minx = box[0] miny = box[1] maxx = box[2] maxy = box[3] sql = "INSERT INTO tiles VALUES (?,?,?,?,?,?,?,?,?,?);" curt.execute(sql,[z,x,y,minx,miny,maxx,maxy,lite.Binary(zlib.compress(output)),sffx,qs.q]) cont.commit() curt.close() #if zoomcache >= z : # f = open(afile,'wb') # f.write(output) # f.close() web.header("Content-Type", cType[sffx]) return output else: return ''
def main(argv): b = "-180,-90,180,90" i = "" o = "" l = "0" try: opts, args = getopt.getopt(argv,"hb:i:o:l:",["bbox","inputXml","output","layerGrid"]) except getopt.GetoptError: print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>' sys.exit() elif opt in ("-b", "--bbox"): b = arg elif opt in ("-i", "--inputXml"): i = arg elif opt in ("-o", "--output"): o = arg elif opt in ("-l", "--layerGrid"): l = arg if not os.path.exists(os.path.dirname(o+".png")): os.makedirs(os.path.dirname(o+".png")) box = [] for s in b.split(",") : box.append(float(s)) geo_extent = Box2d(box[0],box[1],box[2],box[3]) lgrids = [] for s in l.split(",") : lgrids.append(int(s)) geo_proj = Projection('+init=epsg:4326') merc_proj = Projection('+init=epsg:3857') transform = ProjTransform(geo_proj,merc_proj) merc_extent = transform.forward(geo_extent) image = o+".png" mp = mapnik.Map(256,256) mapnik.load_map(mp, i) mp.zoom_to_box(merc_extent) mapnik.render_to_file(mp, image) print "rendered image to '%s'" % image xmldoc = minidom.parse(i) itemlist = xmldoc.getElementsByTagName('Layer') for ly in lgrids : dat = itemlist[ly].getElementsByTagName('Datasource')[0] par = dat.getElementsByTagName('Parameter') for s in par : if s.attributes['name'].value == 'fields': text = s.childNodes[0].nodeValue.encode("utf-8") fields = text.split(",") layer_index = ly #First layer on the map - index in m.layers key = "__id__" #Field used for the key in mapnik (should probably be unique) resolution = 4 #Pixel resolution of output. enfix = "" if ly > 0: enfix = "_"+ly d = mapnik.render_grid(mp, layer_index, key, resolution, fields) #returns a dictionary d = "grid("+json.dumps(d)+")" f = open(o+enfix+".json",'wb') f.write(d) f.close()
def main(argv): b = "-180,-90,180,90" i = "" o = "" l = "-1" try: opts, args = getopt.getopt(argv,"hb:i:o:l:",["bbox","inputXml","output","layerGrid"]) except getopt.GetoptError: print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>' sys.exit(2) for opt, arg in opts: if opt == '-h': print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>' sys.exit() elif opt in ("-b", "--bbox"): b = arg elif opt in ("-i", "--inputXml"): i = arg elif opt in ("-o", "--output"): o = arg elif opt in ("-l", "--layerGrid"): l = arg box = [] for s in b.split(",") : box.append(float(s)) geo_extent = Box2d(box[0],box[1],box[2],box[3]) geo_proj = Projection('+init=epsg:4326') merc_proj = Projection('+init=epsg:3857') transform = ProjTransform(geo_proj,merc_proj) merc_extent = transform.forward(geo_extent) mp = mapnik.Map(256,256) #sys.exit(i) if i.find('http') >= 0: xmlurl=urllib2.urlopen(i) xmlstr=xmlurl.read() #xmlstr = '<Map srs="+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"><Style name="Style1"><Rule><PolygonSymbolizer fill="#ffbf00" fill-opacity="0.5"/><LineSymbolizer stroke="#ff7b00" stroke-width="1" stroke-opacity="1" stroke-linejoin="bevel"/></Rule></Style><Layer name="Layer1" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs "><StyleName>Style1</StyleName><Datasource><Parameter name="type">postgis</Parameter><Parameter name="host">localhost</Parameter><Parameter name="dbname">webgisPEP</Parameter><Parameter name="username">iyo</Parameter><Parameter name="password">SAlamaH</Parameter><Parameter name="table">(SELECT * FROM sxz51_iyo_data_6) as layer1</Parameter><Parameter name="geometry_field">the_geom</Parameter><Parameter name="srid">EPSG:4326</Parameter><Parameter name="fields">gid,nama_kebun,sk</Parameter></Datasource></Layer></Map>' mapnik.load_map_from_string(mp,xmlstr) xmldoc = minidom.parseString(xmlstr) else: mapnik.load_map(mp, i) xmldoc = minidom.parse(i) mp.zoom_to_box(merc_extent) printed = 0 if o == 'png': im = Image(mp.width,mp.height) mapnik.render(mp,im) fd, path = tempfile.mkstemp() os.write(fd,im.tostring('png')) os.fsync(fd) print path elif o == 'json': printed = 1 else: image = o+".png" if not os.path.exists(os.path.dirname(image)): try: os.makedirs(os.path.dirname(image)) except: pass mapnik.render_to_file(mp, image) if l == '-1': print image #print ((time.time())-(t0))*1000 #sys.exit() lgrids = [] if l != '-1': for s in l.split(",") : lgrids.append(s) else: sys.exit() itemlist = xmldoc.getElementsByTagName('Layer') fields = [] resolution = 4 #Pixel resolution of output. printed = 0 for lysl in lgrids : lys = lysl.split(":") ly = int(lys[0]) lz = '' if (len(lys) == 2): lz = lys[1] dat = itemlist[ly].getElementsByTagName('Datasource')[0] par = dat.getElementsByTagName('Parameter') for s in par : dv = s.attributes['name'].value dck = False if (dv[6:] == '' or lz == ''): dck = True elif (dv[6:].isdigit() and lz.isdigit()): dck = (int(lz) >= int(dv[6:])) if dv[:6] == 'fields' and dck and fields == [] : text = s.childNodes[0].nodeValue.encode("utf-8") #print "fields "+text fields = text.split(",") #elif dv[:6] == 'fields': # ly = ly + 1 if dv == 'resolution': res = s.childNodes[0].nodeValue.encode("utf-8") #print "resolution "+res resolution = int(res) layer_index = ly #First layer on the map - index in m.layers key = "__id__" #Field used for the key in mapnik (should probably be unique) enfix = "" if ly > 0: enfix = "_"+str(ly) d = mapnik.render_grid(mp, layer_index, key, resolution, fields) #returns a dictionary d = "grid("+json.dumps(d)+")" if o == 'json' and printed == 0: print d printed = 1 elif o == 'png': printed = 1 else: print d f = open(o+enfix+".json",'wb') f.write(d) f.close()