def __getitem__(self, key): if self.cache_responses: if key in self.seen_layers: return self.seen_layers[key] elif key in self.lookup_failures: # If we are caching, raise KnownUnknown if we have previously failed to find this layer raise TileStache.KnownUnknown("Layer %s previously not found", key) logging.debug("Requesting layer %s", self.url_root + "/layer/" + key) res = urlopen(self.url_root + "/layer/" + key) if (res.getcode() != 200): logging.info("Config response code %s for %s", res.getcode(), key) if (self.cache_responses): self.lookup_failures.add(key) raise TileStache.KnownUnknown("Layer %s not found", key) try: layer = self.parse_layer(res) self.seen_layers[key] = layer return layer except ValueError: logging.error("Invalid JSON response seen for %s", key) if (self.cache_responses): # If caching responses, cache this failure self.lookup_failures.add(key) # KnownUnknown seems like the appropriate thing to raise here since this is akin # to a missing configuration. raise TileStache.KnownUnknown( "Failed to parse JSON configuration for %s", key)
def tiles(request, service_slug, z, x, y, extension): """ Proxy to tilestache {X} - coordinate column. {Y} - coordinate row. {B} - bounding box. {Z} - zoom level. {S} - host. """ service = TileService.objects.get(slug=service_slug) config = { "cache": {"name": "Test"}, "layers": {} } config["layers"][service_slug]={ "provider": { 'name': 'mapnik', "mapfile": service.mapfile } } config = TileStache.Config.buildConfiguration(config) path_info = "%s/%s/%s/%s.%s" % (service_slug, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] mimetype, content = TileStache.getTile(config.layers[service_slug], coord, extension) return HttpResponse(content, mimetype=mimetype)
def seed_resource_cache(): datatype_factory = DataTypeFactory() zooms = range(settings.CACHE_SEED_MAX_ZOOM + 1) extension = 'pbf' lat1, lon1, lat2, lon2 = GeoUtils().get_bounds_from_geojson(settings.CACHE_SEED_BOUNDS) south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) padding = 0 datatypes = [ d.pk for d in models.DDataType.objects.filter(isgeometric=True)] nodes = models.Node.objects.filter( graph__isresource=True, datatype__in=datatypes) for node in nodes: datatype = datatype_factory.get_instance(node.datatype) count = models.TileModel.objects.filter( data__has_key=str(node.nodeid)).count() if datatype.should_cache(node) and count > 0: config = TileStache.parseConfig(get_tileserver_config(node.nodeid)) layer = config.layers[str(node.nodeid)] ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) coordinates = generateCoordinates(ul, lr, zooms, padding) for (offset, count, coord) in coordinates: path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom, coord.column, coord.row, extension) progress = {"tile": path, "offset": offset + 1, "total": count} attempts = 3 rendered = False while not rendered: print '%(offset)d of %(total)d...' % progress, try: mimetype, content = TileStache.getTile( layer, coord, extension, True) except: attempts -= 1 print 'Failed %s, will try %s more.' % (progress['tile'], ['no', 'once', 'twice'][attempts]) if attempts == 0: print 'Failed %(zoom)d/%(column)d/%(row)d, trying next tile.\n' % coord.__dict__ break else: rendered = True progress['size'] = '%dKB' % (len(content) / 1024) print '%(tile)s (%(size)s)' % progress
def seed_resource_cache(): zooms = range(settings.CACHE_SEED_MAX_ZOOM + 1) extension = 'pbf' lat1, lon1, lat2, lon2 = settings.CACHE_SEED_BOUNDS south, west = min(lat1, lat2), min(lon1, lon2) north, east = max(lat1, lat2), max(lon1, lon2) northwest = Location(north, west) southeast = Location(south, east) padding = 0 datatypes = [ d.pk for d in models.DDataType.objects.filter(isgeometric=True) ] nodes = models.Node.objects.filter(graph__isresource=True, datatype__in=datatypes) for node in nodes: datatype = datatype_factory.get_instance(node.datatype) count = models.TileModel.objects.filter( data__has_key=str(node.nodeid)).count() if datatype.should_cache(node) and count > 0: config = TileStache.parseConfig(get_tileserver_config(node.nodeid)) layer = config.layers[str(node.nodeid)] ul = layer.projection.locationCoordinate(northwest) lr = layer.projection.locationCoordinate(southeast) coordinates = generateCoordinates(ul, lr, zooms, padding) for (offset, count, coord) in coordinates: path = '%s/%d/%d/%d.%s' % (layer.name(), coord.zoom, coord.column, coord.row, extension) progress = {"tile": path, "offset": offset + 1, "total": count} attempts = 3 rendered = False while not rendered: print '%(offset)d of %(total)d...' % progress, try: mimetype, content = TileStache.getTile( layer, coord, extension, True) except: attempts -= 1 print 'Failed %s, will try %s more.' % ( progress['tile'], ['no', 'once', 'twice' ][attempts]) if attempts == 0: print 'Failed %(zoom)d/%(column)d/%(row)d, trying next tile.\n' % coord.__dict__ break else: rendered = True progress['size'] = '%dKB' % (len(content) / 1024) print '%(tile)s (%(size)s)' % progress
def tilestache(request, layer_name, z, x, y, extension): """ Proxy to tilestache {X} - coordinate column. {Y} - coordinate row. {B} - bounding box. {Z} - zoom level. {S} - host. """ config = get_config() path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] mimetype, content = TileStache.getTile(config.layers[layer_name], coord, extension) return HttpResponse(content, mimetype=mimetype)
def render(self, config, input_img, coord): layer_img, color_img, mask_img = None, None, None if self.layername: layer = config.layers[self.layername] mime, body = TileStache.handleRequest(layer, coord, 'png') layer_img = PIL.Image.open(StringIO(body)) if self.maskname: layer = config.layers[self.maskname] mime, body = TileStache.handleRequest(layer, coord, 'png') mask_img = PIL.Image.open(StringIO(body)).convert('L') if self.colorname: color = makeColor(self.colorname) color_img = PIL.Image.new('RGBA', input_img.size, color) output_img = input_img.copy() if layer_img and color_img and mask_img: raise Exception('could be ugly') elif layer_img and color_img: output_img.paste(color_img, None, color_img) output_img.paste(layer_img, None, layer_img) elif layer_img and mask_img: # need to combine the masks here layermask_img = PIL.Image.new('RGBA', layer_img.size, (0, 0, 0, 0)) layermask_img.paste(layer_img, None, mask_img) output_img.paste(layermask_img, None, layermask_img) elif color_img and mask_img: output_img.paste(color_img, None, mask_img) elif layer_img: output_img.paste(layer_img, None, layer_img) elif color_img: output_img.paste(color_img, None, color_img) elif mask_img: raise Exception('nothing') else: raise Exception('nothing') return output_img
def tiles(layer, x, y, z): if not tileconfig.layers.has_key(layer): return abort(404) coord = ModestMaps.Core.Coordinate(y, x, z) type, bytes = TileStache.getTile(tileconfig.layers[layer], coord, 'png') buf = BytesIO(bytes) return send_file(buf, mimetype=type)
def add_config(self, kernel_id, **kwargs): cache = kwargs.get("cache", self.default_cache) self._configs[kernel_id] = ts.parseConfig({ "cache": cache, "layers": {} })
def tiles(request, layer_name, z, x, y, extension, custom_tile=None): """ Fetch tiles with tilestache. """ metatile = TileStache.Core.Metatile() if custom_tile: config = get_config(custom_tile=custom_tile) else: config = get_config() path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] try: tilestacheLayer = config.layers[layer_name] except: return HttpResponseNotFound() status_code, headers, content = tilestacheLayer.getTileResponse(coord, extension) mimetype = headers.get('Content-Type') if len(content) == 0: status_code = 404 response = HttpResponse(content, content_type=mimetype, status=status_code) response['Access-Control-Allow-Origin'] = '*' return response
def getTile(layer,extension,x,y,z,config): cfg = TileStache.Config.buildConfiguration(config) contenttype, content = TileStache.getTile(cfg.layers[layer], ModestMaps.Core.Coordinate(int(x), int(y), int(z)),extension,ignore_cached=True) handle, filename = mkstemp(prefix='tile-', suffix='.'+extension) os.write(handle, content) os.close(handle) return filename
def wms(layer,x,y,z): if not tileconfig.layers.has_key(layer): return abort(404) coord = ModestMaps.Core.Coordinate(y,x,z) type, bytes = TileStache.getTile(tileconfig.layers[layer], coord, 'png') buf = BytesIO(bytes) return send_file(buf, mimetype=type)
def clean_resource_cache(tile): # get the tile model's bounds datatype_factory = DataTypeFactory() nodegroup = models.NodeGroup.objects.get(pk=tile.nodegroup_id) for node in nodegroup.node_set.all(): datatype = datatype_factory.get_instance(node.datatype) if datatype.should_cache(node) and datatype.should_manage_cache(node): bounds = datatype.get_bounds(tile, node) if bounds is not None: zooms = range(20) config = TileStache.parseConfig( get_tileserver_config(node.nodeid)) layer = config.layers[str(node.nodeid)] mimetype, format = layer.getTypeByExtension('pbf') lon1, lat1, lon2, lat2 = bounds 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) padding = 0 coordinates = generateCoordinates(ul, lr, zooms, padding) for (offset, count, coord) in coordinates: config.cache.remove(layer, coord, format) for key, tile_list in tile.tiles.iteritems(): for child_tile in tile_list: clean_resource_cache(child_tile)
def get_url_tile(config, url, row, col, zoom, ext): ''' ''' layer = config.layers[url] coord = ModestMaps.Core.Coordinate(row, col, zoom) # (1582, 656, 12) mime, body = TileStache.getTile(layer, coord, ext) return (mime, body)
def get(self, request, layer_name, z, x, y, extension): """ Fetch tiles with tilestache. """ # try: print("==GETTING TILES== {0}".format(layer_name)) extension = extension.upper() config = get_tilestache_config() path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] try: tilestache_layer = config.layers[layer_name] except: return Response({'status': 'layer not found'}, status=status.HTTP_404_NOT_FOUND) status_code, headers, content = tilestache_layer.getTileResponse( coord, extension) mimetype = headers.get('Content-Type') if len(content) == 0: status_code = 404 response = HttpResponse( content, **{ 'content_type': mimetype, 'status': status_code }) if hasattr(tilestache_layer, 'allowed origin'): response['Access-Control-Allow-Origin'] = tilestache_layer.get( 'allowed origin') return response
def getTile(layer, extension, x, y, z, cfg): contenttype, content = TileStache.getTile(cfg.layers[layer], ModestMaps.Core.Coordinate( int(x), int(y), int(z)), extension, ignore_cached=True) return content
def handle_request(request): config_dict = get_tileserver_config() layer_models = models.TileserverLayers.objects.all() for layer_model in layer_models: config_dict['layers'][layer_model.name] = { "provider": { "name": "mapnik", "mapfile": layer_model.path } } config = TileStache.Config.buildConfiguration(config_dict) path_info = request.path.replace('/tileserver/', '') query_string = None script_name = None status_code, headers, content = TileStache.requestHandler2( config, path_info, query_string, script_name) response = HttpResponse() response.content = content response.status_code = status_code for header, value in headers.items(): response[header] = value response['Content-length'] = str(len(content)) return response
class TornadoRequestHandler(tornado.web.RequestHandler): """ Create a Tornado HTTP get and post handler. This class is documented as part of Tornado public RequestHandler API: http://www.tornadoweb.org/en/stable/guide/structure.html """ def initialize(self, config=None, autoreload=False): self.config = config self.autoreload = autoreload try: self.tsconfig = TileStache.parseConfig(self.config) except: print "Error loading Tilestache config:" raise def get(self, *args, **kwargs): if self.autoreload: # re-parse the config file on every request try: self.tsconfig = parseConfig(self.config) except Exception, e: raise Core.KnownUnknown( "Error loading Tilestache configuration:\n%s" % str(e)) status_code, headers, content = TileStache.requestHandler2( self.tsconfig, args[0]) # Get the header header = headers.items()[0] # Tornado syntax for passing headers self.set_header(header[0], header[1]) self.write(content)
def getTileUrls(self, coord): """ Return tile URLs that start with file://, by first retrieving them. """ if self.threadsafe or self.lock.acquire(): mime_type, tile_data = TileStache.getTile(self.layer, coord, 'png', self.ignore_cached) handle, filename = mkstemp(prefix='tilestache-compose-', suffix='.png') write(handle, tile_data) close(handle) self.files.append(filename) if not self.threadsafe: # must be locked, right? self.lock.release() if self.verbose: size = len(tile_data) / 1024. printlocked( self.lock, self.layer.name() + '/%(zoom)d/%(column)d/%(row)d.png' % coord.__dict__, '(%dKB)' % size) return ('file://' + abspath(filename), )
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 app(environ, start_response): layer, coord, ext = TileStache._splitPathInfo(environ['PATH_INFO']) if not config.layers.get(layer, False): status = '404 NOT FOUND' data = '' else: try: content_type, data = TileStache.handleRequest(config.layers[layer], coord, ext) status = '200 OK' except Exception, e: status = '500 SERVER ERROR' data = str(e)
def get_tile_config(): import TileStache as tilestache pth = os.path.join(TILE_CONFIG_DIR, 'tiles.cfg') try: cfg = tilestache.parseConfigfile(pth) except (IOError, ValueError): cfg = None return cfg
def addLayer(self, layerDef, coord): layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1] # raise KnownUnknown(layer) if layerDef['wrapper'] == None: layer = json.loads(layer) else: layer = json.loads(layer[(len(layerDef['wrapper']) + 1):-1]) #Strip "Wrapper(...)" gridSize = len(layer['grid']) #init resultGrid based on given layers (if required) if len(self.resultGrid) == 0: for i in xrange(gridSize): self.resultGrid.append([]) for j in xrange(gridSize): self.resultGrid[i].append(-1) keys = layer['keys'] keyRemap = {} for k in keys: if k in self.gridKeys: for ext in xrange(ord('a'), ord('z') + 1): if not k + chr(ext) in self.gridKeys: keyRemap[k] = (k + chr(ext)) break if not k in keyRemap: raise Error("Couldn't remap") addedKeys = [] #FIXME: HashSet<string>? for y in xrange(gridSize): line = layer['grid'][y] for x in xrange(gridSize): idNo = self.decodeId(line[x]) if keys[idNo] == "": continue key = keys[idNo] if keys[idNo] in keyRemap: key = keyRemap[keys[idNo]] if not key in addedKeys: self.gridKeys.append(key) addedKeys.append(key) if layerDef[ 'layer_id'] != None and self.layer_id != None: #Add layer name attribute layer['data'][keys[idNo]][ self.layer_id] = layerDef['layer_id'] self.gridData[key] = layer['data'][keys[idNo]] newId = self.gridKeys.index(key) self.resultGrid[x][y] = newId
def initialize(self, config=None, autoreload=False): self.config = config self.autoreload = autoreload try: self.tsconfig = TileStache.parseConfig(self.config) except: print "Error loading Tilestache config:" raise
def tileMap(request, version, map_id, zoom, x, y): try: if version != "1.0": raise Http404 try: basqui_map = BasquiMap.objects.get(id=map_id) layersMapOptions = LayerMapOptions.objects.filter( basqui_map=basqui_map, visible=True).order_by('-position') except Shapefile.DoesNotExist or Feature.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 if basqui_map.changed: xml_map_config(request, zoom, x, y, basqui_map, layersMapOptions) config = { "cache": { "name": "test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { basqui_map.map_name: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, basqui_map.map_name) }, "projection": "spherical mercator" } } } path = "/%s/%s/%s/%s.png" % (basqui_map.map_name, zoom, x, y) config = TileStache.Config.buildConfiguration(config) type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
def tileMap(request, map_id, zoom, x, y): try: try: basqui_map = BasquiMap.objects.get(id=map_id, created_by=request.user) except Shapefile.DoesNotExist or Feature.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 map_name = "%s_%s" % (basqui_map.name, basqui_map.pk) config = { "cache": { "name": "test", "path": "../tilestache/%s/cache/" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { map_name: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/maps/viewer/%s.xml" % (request.user, map_name) }, "metatile": { "rows": 2, "columns": 2, "buffer": 64 }, "projection": "spherical mercator", } } } path = "/%s/%s/%s/%s.png" % (map_name, zoom, x, y) config = TileStache.Config.buildConfiguration(config) type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, content_type="image/png") except: traceback.print_exc() return HttpResponse("")
def addLayer( self, layerDef, coord ): _, _, layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1] # raise KnownUnknown(layer) if layerDef['wrapper'] == None: layer = json.loads(layer) else: layer = json.loads(layer[(len(layerDef['wrapper'])+1):-1]) #Strip "Wrapper(...)" gridSize = len(layer['grid']) #init resultGrid based on given layers (if required) if len(self.resultGrid) == 0: for i in xrange(gridSize): self.resultGrid.append([]) for j in xrange(gridSize): self.resultGrid[i].append(-1) keys = layer['keys'] keyRemap = {} for k in keys: if k in self.gridKeys: for ext in xrange(ord('a'), ord('z')+1): if not k+chr(ext) in self.gridKeys: keyRemap[k] = (k+chr(ext)) break if not k in keyRemap: raise Error("Couldn't remap") addedKeys = [] #FIXME: HashSet<string>? for y in xrange(gridSize): line = layer['grid'][y] for x in xrange(gridSize): idNo = self.decodeId(line[x]) if keys[idNo] == "": continue key = keys[idNo] if keys[idNo] in keyRemap: key = keyRemap[keys[idNo]] if not key in addedKeys: self.gridKeys.append(key) addedKeys.append(key) if layerDef['layer_id'] != None and self.layer_id != None: #Add layer name attribute layer['data'][keys[idNo]][self.layer_id] = layerDef['layer_id'] self.gridData[key] = layer['data'][keys[idNo]] newId = self.gridKeys.index(key) self.resultGrid[x][y] = newId
def GET(layer, zoom, x, y): ini = time.clock() path_configfile = os.path.join(request.folder, 'static/tilestache.cfg') config2 = ts.parseConfigfile(path_configfile) formato = request.extension token_version = "x234dffx" response.headers["Cache-Control"] = "public, max-age=100" if request.env.http_if_none_match == token_version: raise HTTP(304, "", **response.headers) else: try: layer2 = config2.layers[layer] coord = ts.Coordinate(int(y), int(x), int(zoom)) mime_type, tile_content = ts.getTile(layer2, coord, formato) except: raise HTTP(404) response.headers["Content-Type"] = mime_type response.headers["Etag"] = token_version raise HTTP(200, tile_content, **response.headers) return locals()
def __call__(self, environ, start_response): """ Handle a request, using PATH_INFO and QUERY_STRING from environ. There are six required query string parameters: width, height, xmin, ymin, xmax and ymax. Layer name must be supplied in PATH_INFO. """ if self.autoreload: # re-parse the config file on every request try: self.config = TileStache.parseConfigfile(self.config_path) except Exception, e: raise Core.KnownUnknown("Error loading Tilestache config file:\n%s" % str(e))
def addLayer(self, layerDef, coord): layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1] if layerDef['wrapper'] == None: layer = json.loads(layer) else: # Strip "Wrapper(...)" layer = json.loads(layer[(len(layerDef['wrapper']) + 1):-1]) grid_size = len(layer['grid']) # Init resultGrid based on given layers (if required) if len(self.resultGrid) == 0: for i in range(grid_size): self.resultGrid.append([]) for j in range(grid_size): self.resultGrid[i].append(-1) layer_keys = layer['keys'] for y in range(grid_size): line = layer['grid'][y] for x in range(grid_size): src_id = self.decodeId(line[x]) if layer_keys[src_id] == "": continue src_key = layer_keys[src_id] # Add layer name attribute if layerDef['layer_id'] != None and self.layer_id != None: layer['data'][src_key][ self.layer_id] = layerDef['layer_id'] if self.resultGrid[x][y] == -1: cur_id = self.curId self.curId += 1 cur_key = json.dumps(cur_id) # Set key for current point. self.resultGrid[x][y] = self.encodeId(cur_id) self.gridKeys.insert(cur_id + 1, cur_key) # Initialize data bucket. self.gridData[cur_key] = [] else: cur_id = self.decodeId(self.resultGrid[x][y]) cur_key = json.dumps(cur_id) self.gridData[cur_key].append(layer['data'][src_key])
def application(environ, start_response): config = environ["TILESTACHE_CONFIG"] layer, coord, ext = TileStache.splitPathInfo(environ["PATH_INFO"]) if not config.layers.get(layer, False): print >>environ["wsgi.errors"], "[gunistache] unknown layer: " + layer status = "404 NOT FOUND" data = "" else: try: content_type, data = TileStache.handleRequest(config.layers[layer], coord, ext) status = "200 OK" except Exception, e: print >>environ["wsgi.errors"], "[gunistache] failed to handle request:" + str(e) status = "500 SERVER ERROR" data = str(e)
def addLayer( self, layerDef, coord ): layer = TileStache.getTile(self.layer.config.layers[layerDef['src']], coord, 'JSON')[1] if layerDef['wrapper'] == None: layer = json.loads(layer) else: # Strip "Wrapper(...)" layer = json.loads(layer[(len(layerDef['wrapper'])+1):-1]) grid_size = len(layer['grid']) # Init resultGrid based on given layers (if required) if len(self.resultGrid) == 0: for i in xrange(grid_size): self.resultGrid.append([]) for j in xrange(grid_size): self.resultGrid[i].append(-1) layer_keys = layer['keys'] for y in xrange(grid_size): line = layer['grid'][y] for x in xrange(grid_size): src_id = self.decodeId(line[x]) if layer_keys[src_id] == "": continue src_key = layer_keys[src_id] # Add layer name attribute if layerDef['layer_id'] != None and self.layer_id != None: layer['data'][src_key][self.layer_id] = layerDef['layer_id'] if self.resultGrid[x][y] == -1: cur_id = self.curId self.curId += 1 cur_key = json.dumps(cur_id) # Set key for current point. self.resultGrid[x][y] = self.encodeId(cur_id) self.gridKeys.insert(cur_id + 1, cur_key) # Initialize data bucket. self.gridData[cur_key] = [] else: cur_id = self.decodeId(self.resultGrid[x][y]) cur_key = json.dumps(cur_id) self.gridData[cur_key].append(layer['data'][src_key])
def tilestache_tiles(request, layer_name, z, x, y, extension): """ :param request: :param layer_name: :param z: :param x: :param y: :param extension: :return: Proxy to tilestache {X} - coordinate column. {Y} - coordinate row. {B} - bounding box. {Z} - zoom level. {S} - host. """ config = TileStacheConfig.objects.filter(name='default')[0].config path_info = "%s/%s/%s/%s.%s" % (layer_name, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] mimetype, content = TileStache.getTile(config.layers[layer_name], coord, extension) return HttpResponse(content, mimetype=mimetype)
def tiles(request, service_slug, z, x, y, extension): """ Proxy to tilestache {X} - coordinate column. {Y} - coordinate row. {B} - bounding box. {Z} - zoom level. {S} - host. """ service = TileService.objects.get(slug=service_slug) config = {"cache": {"name": "Test"}, "layers": {}} config["layers"][service_slug] = { "provider": { 'name': 'mapnik', "mapfile": service.mapfile } } config = TileStache.Config.buildConfiguration(config) path_info = "%s/%s/%s/%s.%s" % (service_slug, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] mimetype, content = TileStache.getTile(config.layers[service_slug], coord, extension) return HttpResponse(content, mimetype=mimetype)
def renderTile(self, width, height, srs, coord): image = PIL.Image.new('RGBA', (width, height), (0, 0, 0, 0)) image = self.stack.render(self.layer.config, image, coord) return image layer = self.layer.config.layers['base'] mime, body = TileStache.handleRequest(layer, coord, 'png') img_base = PIL.Image.open(StringIO(body)) layer = self.layer.config.layers['outlines'] mime, body = TileStache.handleRequest(layer, coord, 'png') img_outlines = PIL.Image.open(StringIO(body)) layer = self.layer.config.layers['halos'] mime, body = TileStache.handleRequest(layer, coord, 'png') img_halos = PIL.Image.open(StringIO(body)) img_outlinesmask = PIL.Image.new('RGBA', img_outlines.size, (0, 0, 0, 0)) img_outlinesmask.paste(img_outlines, None, img_halos.convert('L')) layer = self.layer.config.layers['streets'] mime, body = TileStache.handleRequest(layer, coord, 'png') img_streets = PIL.Image.open(StringIO(body)) img = PIL.Image.new('RGBA', (256, 256)) img.paste(img_base, (0, 0), img_base) img.paste(img_outlines, None, img_outlinesmask) img.paste(img_streets, (0, 0), img_streets) return img pass
def tileMap(request, version, map_id, zoom, x, y): try: if version != "1.0": raise Http404 try: basqui_map = BasquiMap.objects.get(id=map_id) layersMapOptions = LayerMapOptions.objects.filter(basqui_map=basqui_map, visible=True).order_by('-position') except Shapefile.DoesNotExist or Feature.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 if basqui_map.changed: xml_map_config(request, zoom, x, y, basqui_map, layersMapOptions) config = { "cache": { "name": "test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable"}, "layers": { basqui_map.map_name: { "provider": {"name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, basqui_map.map_name)}, "projection": "spherical mercator" } } } path = "/%s/%s/%s/%s.png" % (basqui_map.map_name,zoom,x,y) config = TileStache.Config.buildConfiguration(config) type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
def tileMap(request, map_id, zoom, x, y): try: try: basqui_map = BasquiMap.objects.get(id=map_id, created_by=request.user) except Shapefile.DoesNotExist or Feature.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 map_name = "%s_%s" % (basqui_map.name, basqui_map.pk) config = { "cache": { "name": "test", "path": "../tilestache/%s/cache/" % (request.user), "umask": "0000", "dirs": "portable"}, "layers": { map_name: { "provider": {"name": "mapnik", "mapfile": "../tilestache/%s/maps/viewer/%s.xml" % (request.user, map_name)}, "metatile": { "rows": 2, "columns": 2, "buffer": 64 }, "projection": "spherical mercator", } } } path = "/%s/%s/%s/%s.png" % (map_name,zoom,x,y) config = TileStache.Config.buildConfiguration(config) type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, content_type="image/png") except: traceback.print_exc() return HttpResponse("")
def test_tilestache_lib(self): config = eval(open(get_tilestache_file('tilestache.cfg')).read()) config["layers"]["example"]["provider"]["mapfile"] = "style_sheet.xml" # like http://tile.openstreetmap.org/1/0/0.png coord = ModestMaps.Core.Coordinate(0, 0, 0) config = TileStache.Config.buildConfiguration(config) mime_type, image_bytes = TileStache.getTile(config.layers['example'], coord, 'png') self.assertEquals(mime_type, 'image/png') open(actual_image, 'w').write(image_bytes) with open(actual_image) as actual, open(expected_image) as expected: actual_read = actual.read() self.assertEquals(actual_read, expected.read()) img = Image.open(StringIO(actual_read)) self.assertEquals(img.size, (256, 256))
def getTile(layer,extension,x,y,z): coord=ModestMaps.Core.Coordinate(int(x), int(y), int(z)) configFile=open('static/config/tile.cfg') config=json.load(configFile) cfg = TileStache.Config.buildConfiguration(config) contenttype, content = TileStache.getTile(cfg.layers[layer], coord,extension) if not os.path.exists('static/map/'+layer): os.mkdir(r'static/map/'+layer) if not os.path.exists('static/map/'+layer+'/'+z): os.mkdir(r'static/map/'+layer+'/'+z) if not os.path.exists('static/map/'+layer+'/'+z+'/'+y): os.mkdir(r'static/map/'+layer+'/'+z+'/'+y) #if not os.path.exists('static/map/'+layer+'/'+z+'/'+y+'/'+x): # os.mkdir(r'static/map/'+layer+'/'+z+'/'+y+'/'+x) tilepath='static/map/'+layer+'/'+z+'/'+y+'/'+x+'.png' open(tilepath, 'w').write(content) return contenttype, content
def scenario_tile(request, instance): path_info = "/" + instance.uid + "_tiles" + request.GET.get('tile') if not path_info: return HttpResponse("Must supply tile GET paramater", status=400) if not _pathinfo_pat.match(path_info or ''): return HttpResponse('Bad path: "%s"; Expecting something like "/example/0/0/0.png"' % path_info, status=400) thisdir = os.path.dirname(os.path.abspath(__file__)) dirpath = os.path.realpath(os.path.join(thisdir, '..', '..', 'tile_config')) xml_path = instance.mapnik_xml() config_dict = { "layers": { instance.uid + "_tiles": { # "metatile": { # "buffer": 64, # "rows": 4, # "columns": 4 # }, "provider": { "name": "mapnik", "mapfile": xml_path } }, }, "cache": { "host": "localhost", "name": "Redis", "db": settings.APP_REDIS_DB, "port": 6379 }, # "cache": { # "name": "test", # }, "logging": "warning" } config = TileStache.Config.buildConfiguration(config_dict, dirpath) (mimestr, bytestotal) = TileStache.requestHandler( config_hint=config, path_info=path_info, query_string=None) return HttpResponse(bytestotal, content_type=mimestr)
def renderTile(self, width, height, srs, coord): logging.info("[dithering] render tile %s..." % coord) source = self.layer.config.layers[ self.source_layer ] mime, body = TileStache.getTile(source, coord, 'png') if self.skip_on_checksum: hash = md5.new(body) if hash.hexdigest() == self.checksum: logging.info('[dithering] skip check sum matches %s : %s' % (coord, self.checksum)) return Image.new('RGBA', (256, 256)) img = Image.open(StringIO.StringIO(body)) if self.plotter == 'atk': return self.dither_atk(img) return self.dither_python(img)
def getTileUrls(self, coord): """ Return tile URLs that start with file://, by first retrieving them. """ if self.threadsafe or self.lock.acquire(): mime_type, tile_data = TileStache.getTile(self.layer, coord, 'png', self.ignore_cached) handle, filename = mkstemp(prefix='tilestache-compose-', suffix='.png') write(handle, tile_data) close(handle) self.files.append(filename) if not self.threadsafe: # must be locked, right? self.lock.release() if self.verbose: size = len(tile_data) / 1024. printlocked(self.lock, self.layer.name() + '/%(zoom)d/%(column)d/%(row)d.png' % coord.__dict__, '(%dKB)' % size) return ('file://' + abspath(filename), )
def get(self, request, layer_name, z, x, y, extension): """ Fetch tiles with tilestache. """ try: extension = extension.upper() config = get_config().config path_info = "{}/{}/{}/{}.{}".format(layer_name, z, x, y, extension) coord, extension = TileStache.splitPathInfo(path_info)[1:] try: tilestache_layer = config.layers[layer_name] except: return Response({'status': 'layer not found'}, status=status.HTTP_404_NOT_FOUND) status_code, headers, content = tilestache_layer.getTileResponse(coord, extension) mimetype = headers.get('Content-Type') if len(content) == 0: status_code = 404 response = HttpResponse( content, **{ 'content_type': mimetype, 'status': status_code } ) if hasattr(tilestache_layer, 'allowed origin'): response['Access-Control-Allow-Origin'] = tilestache_layer.get('allowed origin') return response except Exception as ex: return Response( { 'status': 'error', 'message': str(ex) }, status=status.HTTP_404_NOT_FOUND )
def renderTile(self, width, height, srs, coord): logging.info("[dithering] render tile %s..." % coord) source = self.layer.config.layers[self.source_layer] mime, body = TileStache.getTile(source, coord, 'png') if self.skip_on_checksum: hash = md5.new(body) if hash.hexdigest() == self.checksum: logging.info('[dithering] skip check sum matches %s : %s' % (coord, self.checksum)) return Image.new('RGBA', (256, 256)) img = Image.open(StringIO.StringIO(body)) if self.plotter == 'atk': return self.dither_atk(img) return self.dither_python(img)
def handle_request(request): path_info = request.path.replace(reverse('tileserver') + '/', '') layer_id = path_info.split('/')[0] config_dict = get_tileserver_config(layer_id, request=request) config = TileStache.Config.buildConfiguration(config_dict) query_string = "" script_name = "" response = HttpResponse() try: status_code, headers, content = TileStache.requestHandler2( config, path_info, query_string, script_name) response.content = content response.status_code = status_code for header, value in headers.items(): response[header] = value response['Content-length'] = str(len(content)) except Exception as e: print 'No tile data', e, response return response
"-v", "--verbose", dest="verbose", help="Enable verbose logging. Default is false.", action="store_true", default=False, ) options, args = parser.parse_args() if options.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) # Some day, Python will have a -I flag... if options.include: for path in options.include.split(":"): logging.debug("include %s to Python's sys.path") sys.path.insert(0, path) logging.info("start server on %s:%s" % (options.host, options.port)) # http://docs.python.org/library/wsgiref.html httpd = make_server(options.host, int(options.port), application) httpd.base_environ["TILESTACHE_CONFIG"] = TileStache.parseConfigfile(options.config) httpd.serve_forever()
import sys import TileStache application = TileStache.WSGITileServer(config='osm-check.cfg', autoreload=True)
import TileStache application = TileStache.WSGITileServer( '/usr/local/app/tilestache/tilestache.cfg')
def render(self, config, input_rgba, coord): """ Render this image layer. Given a configuration object, starting image, and coordinate, return an output image with the contents of this image layer. """ has_layer, has_color, has_mask = False, False, False output_rgba = [chan.copy() for chan in input_rgba] if self.layername: layer = config.layers[self.layername] _, _, body = TileStache.getTile(layer, coord, 'png') layer_img = Image.open(StringIO(body)).convert('RGBA') layer_rgba = _img2rgba(layer_img) has_layer = True if self.maskname: layer = config.layers[self.maskname] _, _, body = TileStache.getTile(layer, coord, 'png') mask_img = Image.open(StringIO(body)).convert('L') mask_chan = _img2arr(mask_img).astype(numpy.float32) / 255. has_mask = True if self.colorname: color = make_color(self.colorname) color_rgba = [numpy.zeros(output_rgba[0].shape, numpy.float32) + band/255.0 for band in color] has_color = True if has_layer: layer_rgba = apply_adjustments(layer_rgba, self.adjustments) if has_layer and has_color and has_mask: raise KnownUnknown("You can't specify src, color and mask together in a Composite Layer: %s, %s, %s" % (repr(self.layername), repr(self.colorname), repr(self.maskname))) elif has_layer and has_color: # color first, then layer output_rgba = blend_images(output_rgba, color_rgba[:3], color_rgba[3], self.opacity, self.blendmode) output_rgba = blend_images(output_rgba, layer_rgba[:3], layer_rgba[3], self.opacity, self.blendmode) elif has_layer and has_mask: # need to combine the masks here layermask_chan = layer_rgba[3] * mask_chan output_rgba = blend_images(output_rgba, layer_rgba[:3], layermask_chan, self.opacity, self.blendmode) elif has_color and has_mask: output_rgba = blend_images(output_rgba, color_rgba[:3], mask_chan, self.opacity, self.blendmode) elif has_layer: output_rgba = blend_images(output_rgba, layer_rgba[:3], layer_rgba[3], self.opacity, self.blendmode) elif has_color: output_rgba = blend_images(output_rgba, color_rgba[:3], color_rgba[3], self.opacity, self.blendmode) elif has_mask: raise KnownUnknown("You have to provide more than just a mask to Composite Layer: %s" % repr(self.maskname)) else: raise KnownUnknown("You have to provide at least some combination of src, color and mask to Composite Layer") return output_rgba
def tiles(request): path_info = request.path_info.replace('/tiles', '') (mimestr, bytestotal) = TileStache.requestHandler(config_hint=settings.TILE_CONFIG, path_info=path_info, query_string=None) return HttpResponse(bytestotal, content_type=mimestr)
def tileLayer(request, version, shapefile_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id, created_by=request.user) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 #create de mapnik.map object map = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over") map.background = mapnik.Color("#f2f3f7") #defining the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) field = "'NOM'" field2 = "'CODE'" query = '(select ' + geometryField + ', attribute_value->' + field +' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(shapefile.id) + ')) as geom' feature = Feature.objects.filter(shapefile__id=shapefile_id).geojson() adapter = DjLayer(feature) lyr = adapter.to_mapnik() lyr.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" m = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over") ## datasource = mapnik.PostGIS(user=dbSettings['USER'], ## password=dbSettings['PASSWORD'], ## dbname=dbSettings['NAME'], ## port=5433, ## table=query, ## srid=3857, ## geometry_field=geometryField, ## simplify_geometries=True, ## geometry_table='"shapefile_feature"') ## featureLayer = mapnik.Layer("featureLayer") ## featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ## featureLayer.datasource = datasource ## featureLayer.styles.append("featureLayerStyle") ## #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in ["LineString", "MultiLineString"]: rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#f7edee"))) rule.symbols.append(mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) ## ## label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black')) ## label.halo_fill = mapnik.Color('white') ## label.halo_radius = 4 ## label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT ## label.allow_overlap = True ## label.avoid_edges = True ## rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) lyr.styles.append('name') ## ## #add new feature to the map m.append_style("name", style) m.layers.append(lyr) ## map.layers.append(featureLayer) #rendering the map tile mapnik.save_map(m, "../tilestache/%s/%s.xml" % (str(request.user), str(shapefile.filename))) config = { "cache": { "name": "Disk", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable"}, "layers": { shapefile.filename: { "provider": {"name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, shapefile.filename)}, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (shapefile.filename,zoom,x,y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
(options, args) = parser.parse_args() if options.include_paths: for p in options.include_paths.split(':'): path.insert(0, p) import TileStache try: if options.config is None: raise TileStache.Core.KnownUnknown('Missing required configuration (--config) parameter.') if options.layer is None: raise TileStache.Core.KnownUnknown('Missing required layer (--layer) parameter.') config = TileStache.parseConfigfile(options.config) if options.layer not in config.layers: raise TileStache.Core.KnownUnknown('"%s" is not a layer I know about. Here are some that I do know about: %s.' % (options.layer, ', '.join(sorted(config.layers.keys())))) provider = Provider(config.layers[options.layer], options.verbose, options.ignore_cached) try: outfile = args[0] except IndexError: raise BadComposure('Error: Missing output file.') if options.center and options.extent: raise BadComposure("Error: bad map coverage, center and extent can't both be set.") elif options.extent and options.dimensions and options.zoom:
import TileStache application = TileStache.WSGITileServer("/data/tilestache.json", autoreload=False)
def tileLayer(request, version, shapefile_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id, created_by=request.user) except Shapefile.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 #create de mapnik.map object map = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) map.background = mapnik.Color("#f2f3f7") #defining the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) field = "'NOM'" field2 = "'CODE'" query = '(select ' + geometryField + ', attribute_value->' + field + ' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' ## datasource = mapnik.SQLite(file='C:\mygeosite\sqlite3\sql3.db', ## table=query, ## srid=3857, ## geometry_field=geometryField) ## datasource = mapnik.PostGIS(user=dbSettings['USER'], ## password=dbSettings['PASSWORD'], ## dbname=dbSettings['NAME'], ## table=query, ## srid=3857, ## geometry_field=geometryField, ## simplify_geometries=True, ## geometry_table='"shapefile_feature"') feature = Feature.objects.filter(shapefile__id=shapefile_id).geojson() geoj = feature.geojson datasource = mapnik.Ogr(layer_by_index=0, string=geoj) ## featureLayer = mapnik.Layer("featureLayer") featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" featureLayer.datasource = datasource featureLayer.styles.append("featureLayerStyle") #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in ["LineString", "MultiLineString"]: rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color("#f7edee"))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) ## label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black')) ## label.halo_fill = mapnik.Color('white') ## label.halo_radius = 4 ## label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT ## label.allow_overlap = True ## label.avoid_edges = True ## rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) #add new feature to the map map.append_style("featureLayerStyle", style) map.layers.append(featureLayer) #rendering the map tile mapnik.save_map( map, "../tilestache/%s/%s.xml" % (str(request.user), str(shapefile.filename))) config = { "cache": { "name": "Test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { shapefile.filename: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, shapefile.filename) }, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (shapefile.filename, zoom, x, y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
def tileMap(request, version, ezmap_id, zoom, x, y): try: if version != "1.0": raise Http404 try: ezmap = EzMap.objects.get(id=ezmap_id) layersMapOptions = LayerMapOptions.objects.filter( ezmap=ezmap, visible=True).order_by('-position') except Shapefile.DoesNotExist or Feature.DoesNotExist: raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 if ezmap.changed: #create de mapnik.map object ezmap.changed = False ezmap.save() map = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) #map.background = mapnik.Color("#ffffff") #defining the feature layer for layer in layersMapOptions.all(): label = LayerLabel.objects.get(layerMapOptions=layer) for layerStyle in layer.styles.all(): shapefile = layer.layer geometryField = utils.calcGeometryField( shapefile.geom_type) query = '(select ' + geometryField + ', attribute_value->\'' + label.field.name + '\' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' ## datasource = mapnik.SQLite(file='C:\mygeosite\sqlite3\sql3.db', ## table=query, ## srid=3857, ## geometry_field=geometryField, ## use_spatial_index=False) datasource = mapnik.PostGIS( user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], table=query, srid=3857, geometry_field=geometryField, geometry_table='"shapefile_feature"') featureLayer = mapnik.Layer( str(shapefile.filename) + str(layerStyle.id)) featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" featureLayer.datasource = datasource featureLayer.styles.append( str(shapefile.filename) + '_Style' + str(layerStyle.id)) #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: s = mapnik.PointSymbolizer( mapnik.PathExpression(str(layerStyle.iconName))) s.allow_overlap = True rule.symbols.append(s) elif shapefile.geom_type in [ "LineString", "MultiLineString" ]: rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: p = mapnik.PolygonSymbolizer( mapnik.Color(str((layerStyle.fillColor)))) p.fill_opacity = layerStyle.fillOpacity rule.symbols.append(p) rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) label = mapnik.TextSymbolizer( mapnik.Expression('[label]'), 'DejaVu Sans Book', label.font_size, mapnik.Color(str(label.font_color))) label.halo_fill = mapnik.Color(str(label.halo_color)) label.halo_radius = int(label.halo_radius) label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT label.allow_overlap = False label.avoid_edges = True rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) #add new feature to the map map.append_style( str(shapefile.filename) + '_Style' + str(layerStyle.id), style) map.layers.append(featureLayer) #saving the map mapnik xml mapnik.save_map( map, "c:\\mygeosite\\tilestache\\%s\\%s.xml" % (str(request.user), str(ezmap.map_name))) config = { "cache": { "name": "test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { ezmap.map_name: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, ezmap.map_name) }, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (ezmap.map_name, zoom, x, y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
if options.include_paths: for p in options.include_paths.split(':'): path.insert(0, p) import TileStache try: if options.config is None: raise TileStache.Core.KnownUnknown( 'Missing required configuration (--config) parameter.') if options.layer is None: raise TileStache.Core.KnownUnknown( 'Missing required layer (--layer) parameter.') config = TileStache.parseConfig(options.config) if options.layer not in config.layers: raise TileStache.Core.KnownUnknown( '"%s" is not a layer I know about. Here are some that I do know about: %s.' % (options.layer, ', '.join(sorted(config.layers.keys())))) provider = Provider(config.layers[options.layer], options.verbose, options.ignore_cached) try: outfile = args[0] except IndexError: raise BadComposure('Error: Missing output file.') if options.center and options.extent:
import sys import TileStache application = TileStache.WSGITileServer(config='infra.cfg', autoreload=True)