def __init__(self, layer, cache_config, layer_name, format='PNG'): """ Initialize the Monkeycache Provider. Cache_config is a complete cache configuration dictionary that you might use in a TileStache setup (http://tilestache.org/doc/#caches). This is where Monkeycache will look for already-rendered tiles. Layer_name is the name of a layer saved in that cache. Format should match the second return value of your original layer's getTypeByExtention() method, e.g. "PNG", "JPEG", or for the Vector provider "GeoJSON" and others. This might not necessarily match the file name extension, though common cases like "jpg"/"JPEG" are accounted for. """ fake_layer_dict = { 'provider': { 'name': 'Proxy', 'url': 'http://localhost/{Z}/{X}/{Y}.png' } } fake_config_dict = { 'cache': cache_config, 'layers': { layer_name: fake_layer_dict } } fake_config = buildConfiguration(fake_config_dict, layer.config.dirpath) self.source_layer = fake_config.layers[layer_name] self.source_cache = fake_config.cache formats = dict(png='PNG', jpg='JPEG', jpeg='JPEG') self.tile_format = formats.get(format.lower(), format)
def run(self): rospy.init_node('rospilot_mapnik_server') os.environ['PGUSER'] = '******' os.environ['PGPASSWORD'] = '******' os.environ['PGHOST'] = 'localhost' style_file = find_in_workspaces(['share'], 'rospilot', 'share/mapnik-style/style.xml', first_match_only=True) if not style_file: rospy.logfatal("Cannot find share/mapnik-style/style.xml") else: style_file = style_file[0] config = expanduser(rospy.get_param('~tilestache_config_file')) # XXX: Monkey patch Mapnik because Tilestache doesn't work with the newest version mapnik.FontEngine.instance = staticmethod(lambda: mapnik.FontEngine) config = buildConfiguration( { "cache": { "name": "Test" }, "layers": { "ex": { "provider": { "name": "mapnik", "mapfile": "style.xml" }, "projection": "spherical mercator" } } }, style_file) app = TileStache.WSGITileServer(config=config) # Mount the application cherrypy.tree.graft(app, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server object server = cherrypy._cpserver.Server() # Configure the server object server.socket_host = "0.0.0.0" server.socket_port = int( rospy.get_param('/rospilot/mapnik_server_port')) server.thread_pool = 5 # Subscribe this server server.subscribe() cherrypy.engine.start() rospy.loginfo("Mapnik server is running") rospy.loginfo(os.path.dirname(os.path.realpath(__file__))) rospy.loginfo(os.getcwd()) rospy.spin() cherrypy.engine.exit()
def run(self): rospy.init_node('rospilot_mapnik_server') os.environ['PGUSER'] = '******' os.environ['PGPASSWORD'] = '******' os.environ['PGHOST'] = 'localhost' style_file = find_in_workspaces(['share'], 'rospilot', 'share/mapnik-style/style.xml', first_match_only=True) if not style_file: rospy.logfatal("Cannot find share/mapnik-style/style.xml") else: style_file = style_file[0] config = expanduser(rospy.get_param('~tilestache_config_file')) # XXX: Monkey patch Mapnik because Tilestache doesn't work with the newest version mapnik.FontEngine.instance = staticmethod(lambda: mapnik.FontEngine) config = buildConfiguration({ "cache": {"name": "Test"}, "layers": { "ex": { "provider": {"name": "mapnik", "mapfile": "style.xml"}, "projection": "spherical mercator" } } }, style_file) app = TileStache.WSGITileServer(config=config) # Mount the application cherrypy.tree.graft(app, "/") # Unsubscribe the default server cherrypy.server.unsubscribe() # Instantiate a new server object server = cherrypy._cpserver.Server() # Configure the server object server.socket_host = "0.0.0.0" server.socket_port = int(rospy.get_param('/rospilot/mapnik_server_port')) server.thread_pool = 5 # Subscribe this server server.subscribe() cherrypy.engine.start() rospy.loginfo("Mapnik server is running") rospy.loginfo(os.path.dirname(os.path.realpath(__file__))) rospy.loginfo(os.getcwd()) rospy.spin() cherrypy.engine.exit()
def __init__(self,layer_name,minzoom,maxzoom,Sbounds,Wbounds,Nbounds,Ebounds): print (layer_name,minzoom,maxzoom,Sbounds,Wbounds,Nbounds,Ebounds) self.ignore_cached = True self.padding = 0 self.totalTile = 0 self.currentTile = 0 self.config_dict = config.get_config(create_cache=True) self.config_path = settings.TILESTACHE_CREATE_CACHE_CONFIG_PATH self.layer_name = layer_name self.config = buildConfiguration(self.config_dict, self.config_path) self.layer = self.config.layers[self.layer_name] self.zooms = range(int(minzoom),int(maxzoom)+1) self.create_bbox(Sbounds,Wbounds,Nbounds,Ebounds) self.extension = self.create_extenstion() self.callback = False self.coordinates = self.generateCoordinates() self.create_tiles()
def __init__(self, layer, cache_config, layer_name, format='PNG'): """ Initialize the Monkeycache Provider. Cache_config is a complete cache configuration dictionary that you might use in a TileStache setup (http://tilestache.org/doc/#caches). This is where Monkeycache will look for already-rendered tiles. Layer_name is the name of a layer saved in that cache. Format should match the second return value of your original layer's getTypeByExtention() method, e.g. "PNG", "JPEG", or for the Vector provider "GeoJSON" and others. This might not necessarily match the file name extension, though common cases like "jpg"/"JPEG" are accounted for. """ fake_layer_dict = {'provider': {'name': 'Proxy', 'url': 'http://localhost/{Z}/{X}/{Y}.png'}} fake_config_dict = {'cache': cache_config, 'layers': {layer_name: fake_layer_dict}} fake_config = buildConfiguration(fake_config_dict, layer.config.dirpath) self.source_layer = fake_config.layers[layer_name] self.source_cache = fake_config.cache formats = dict(png='PNG', jpg='JPEG', jpeg='JPEG') self.tile_format = formats.get(format.lower(), format)
if options.s3_output: access, secret, bucket = options.s3_output tiers.append( dict(name='S3', bucket=bucket, access=access, secret=secret)) if len(tiers) > 1: config_dict['cache'] = dict(name='multi', tiers=tiers) elif len(tiers) == 1: config_dict['cache'] = tiers[0] else: # Leave config_dict['cache'] as-is pass # create a real config object config = buildConfiguration(config_dict, config_dirpath) layer = config.layers[options.layer or 'tiles-layer'] # do the actual work lat1, lon1, lat2, lon2 = options.bbox south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) if not (-90.0 < south < 90.0) or not (-90.0 < north < 90.0): raise KnownUnknown( 'Latitude must be a value between -90 and 90 ' '(Hint: Maybe you did long/lat instead of lat/long?).') if not (-180.0 < west < 180.0) or not (-180.0 < east < 180.0): raise KnownUnknown( 'Longitude must be a value between -180 and 180.')
if options.s3_output: access, secret, bucket = options.s3_output tiers.append(dict(name='S3', bucket=bucket, access=access, secret=secret)) if len(tiers) > 1: config_dict['cache'] = dict(name='multi', tiers=tiers) elif len(tiers) == 1: config_dict['cache'] = tiers[0] else: # Leave config_dict['cache'] as-is pass # create a real config object config = buildConfiguration(config_dict, config_dirpath) layer = config.layers[options.layer or 'tiles-layer'] # do the actual work lat1, lon1, lat2, lon2 = options.bbox south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) for (i, zoom) in enumerate(zooms):
def start_seed(self): print("TilestacheSeeder run seed") options = self.assign_default_value(self.options) config = buildConfiguration(options['config']) layer = config.layers[options['name']] bbox = self.get_bbox(options['bbox']) self.validate_bbox(bbox) northwest = Location(bbox['north'], bbox['west']) southeast = Location(bbox['south'], bbox['east']) ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) coordinates = self.get_coordinates( options, { 'ul': ul, 'lr': lr, 'zooms': options['zooms'], 'padding': options['padding'] }) ignore_cached = options['ignore_cached'] extension = options['extension'] verbose = options['verbose'] for (offset, count, coord) in coordinates: path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom, coord.column, coord.row, options['extension']) progress = {"tile": path, "offset": offset + 1, "total": count} # # Fetch a tile. # attempts = options['enable_retries'] rendered = False while not rendered: if verbose: print('%(offset)d of %(total)d...' % progress, end=' ', file=stderr) # print("{offset} of {total}...".format(offset=progress['offset'], total=progress['total'])) try: mimetype, content = getTile(layer, coord, extension, ignore_cached) if mimetype and 'json' in mimetype and options['callback']: js_path = '%s/%d/%d/%d.js' % (layer.name(), coord.zoom, coord.column, coord.row) js_body = '%s(%s);' % (options['callback'], content) js_size = len(js_body) / 1024 layer.config.cache.save(js_body, layer, coord, 'JS') print('%s (%dKB)' % (js_path, js_size), end=' ', file=stderr) elif options['callback']: print('(callback ignored)', end=' ', file=stderr) except: # # Something went wrong: try again? Log the error? # attempts -= 1 if verbose: print('Failed %s, will try %s more.' % (progress['tile'], ['no', 'once', 'twice' ][attempts]), file=stderr) if attempts == 0: if not options['error_list']: raise fp = open(options['error_list'], 'a') fp.write('%(zoom)d/%(column)d/%(row)d\n' % coord.__dict__) fp.close() break else: # # Successfully got the tile. # rendered = True progress['size'] = '%dKB' % (len(content) / 1024) if verbose: print('%(tile)s (%(size)s)' % progress, file=stderr) if options['progressfile']: fp = open(options['progressfile'], 'w') json_dump(progress, fp) fp.close()
def modify_config(tilestache_config, layers): """ Using the attributes of the given Layer objects, updates the default tilestache configuration object and stores it in the database. Each layer instance is used to create a raster, vector, and selection (vector) layer for each configured attribute. These layers are keyed uniquely by the layer instance id, attribute, and layer type, so they will simply overwrite themselves in the config and accumulate. :param tilestache_config: :param layers: :return: """ if tilestache_config.enable_caching: cache = { "name": "Disk", "path": "/tmp/stache", "umask": "0000" } else: cache = {"name": "Test"} # Get or define the config dict config = tilestache_config.config if isinstance(tilestache_config.config, TileStache.Config.Configuration) else buildConfiguration({ 'logging': "info", 'layers': {}, 'cache': cache, }) for layer in layers: # If the layer contains a style configuration if layer.medium_context: # Render the raster styles for each attribute styled in the layer's medium render_attribute_styles(layer) # Create a vector, raster, and vector select layer for each attribute listed in the medium_context for attribute, medium_context in layer.medium_context['attributes'].items(): create_vector_layer(layer, attribute, config) create_raster_layer(layer, attribute, config) create_layer_selection(layer, attribute, config) tilestache_config.config = config tilestache_config.save()
def get_config(): with open(path.join(settings.STATIC_ROOT, "js/tile_stache_config.js")) as f: json = simplejson.load(f) return buildConfiguration(json)