def rendertiles(self, bounds, data, item, label, lat, layer, lon, num_items, projec): z = 1 imgx = 128 * z imgy = 128 * z mapfile = "/map_data/styles/bs_" + layer + ".xml" m = mapnik.Map(imgx, imgy) mapnik.load_map(m, mapfile) # ensure the target map projection is mercator m.srs = projec.params() if hasattr(mapnik, 'Box2d'): bbox = mapnik.Box2d(*bounds) else: bbox = mapnik.Envelope(*bounds) transform = mapnik.ProjTransform(longlat, projec) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) # render the map to an image im = mapnik.Image(imgx, imgy) mapnik.render(m, im) img = im.tostring('png256') data[(item, layer)] = img
def render_legend(mapfile, tile_uri): m = mapnik.Map(1024, 2048) # Load style XML mapnik.load_map(m, mapfile, True) # Obtain <Map> projection prj = mapnik.Projection(m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) tileproj = GoogleProjection(20) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = prj.forward(mapnik.Coord(14.4503,50.0673)) c1 = prj.forward(mapnik.Coord(14.457,50.0678)) # Bounding box for the tile if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800: bbox = mapnik.Box2d(c0.x,c0.y, c1.x,c1.y) else: bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y) render_size_x = 1024 render_size_y = 1500 m.resize(render_size_x, render_size_y) m.zoom_to_box(bbox) m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size_x, render_size_y) mapnik.render(m, im) im.save(tile_uri, 'png256') surface = cairo.SVGSurface('legend.svg', render_size_x, render_size_y) mapnik.render(m, surface) surface.finish()
def render_location(self): # spherical mercator (most common target map projection of osm data imported with osm2pgsql) merc = mapnik.Projection('+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 +no_defs +over') longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') mapfile = "renderer/map_data/styles/bs_complete.xml" bounds = (self.lon-self.size, self.lat-self.size, self.lon+self.size,self.lat+self.size) z = 1 imgx = 224 * z imgy = 224 * z m = mapnik.Map(imgx,imgy) mapnik.load_map(m,mapfile) m.srs = merc.params() if hasattr(mapnik,'Box2d'): bbox = mapnik.Box2d(*bounds) else: bbox = mapnik.Envelope(*bounds) transform = mapnik.ProjTransform(longlat,merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) #render the map to an image im = mapnik.Image(imgx,imgy) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) window_name = "Location" cv2.imshow(window_name, img) cv2.waitKey(0)
def loop(self): self.m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(self.maxZoom+1) while True: #Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists= "" if os.path.isfile(tile_uri): exists= "exists" else: self.render_tile(tile_uri, x, y, z) bytes=os.stat(tile_uri)[6] empty= '' if bytes == 103: empty = " Empty Tile " self.printLock.acquire() print name, ":", z, x, y, exists, empty self.printLock.release() self.q.task_done()
def compare_map(in_map): mapnik2.load_map(map, in_map) (handle, test_map) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map1-') os.close(handle) (handle, test_map2) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map2-') os.close(handle) if os.path.exists(test_map): os.remove(test_map) mapnik2.save_map(map, test_map) new_map = mapnik2.Map(256, 256) mapnik2.load_map(new_map, test_map) open(test_map2, 'w').write(mapnik2.save_map_to_string(new_map)) diff = ' diff %s %s' % (os.path.abspath(test_map), os.path.abspath(test_map2)) try: eq_(open(test_map).read(), open(test_map2).read()) except AssertionError, e: raise AssertionError( 'serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s' % (in_map, diff))
def run(self): self.mapnik_map = mapnik2.Map(self.width, self.height) mapnik2.load_map(self.mapnik_map, self.config, True) self.map_projection = mapnik2.Projection(self.mapnik_map.srs) self.tile_projection = projections.GoogleProjection() while True: tile_parameters = None # Try to fetch a tile from any queue for tile_queue in self.tile_queues: try: tile_parameters = tile_queue.get_nowait() break except Queue.Empty: pass # Couldn't get tile parameters from any queue--all done if not tile_parameters: return # Skip rendering existing tiles if self.skip_existing: filename = tile_parameters[0] if os.path.exists(filename): print 'Skipping %s' % (filename) tile_queue.task_done() continue self.render(*tile_parameters) tile_queue.task_done()
def renderToPdf(envLL, filename, sizex, sizey): """Renders the specified Box2d and zoom level as a PDF""" basefilename = os.path.splitext(filename)[0] mergedpdf = None for mapname in MAPNIK_LAYERS: print 'Rendering', mapname # Render layer PDF. localfilename = basefilename + '_' + mapname + '.pdf'; file = open(localfilename, 'wb') surface = cairo.PDFSurface(file.name, sizex, sizey) envMerc = LLToMerc(envLL) map = mapnik.Map(sizex, sizey) mapnik.load_map(map, mapname + ".xml") map.zoom_to_box(envMerc) mapnik.render(map, surface) surface.finish() file.close() # Merge with master. if not mergedpdf: mergedpdf = PdfFileWriter() localpdf = PdfFileReader(open(localfilename, "rb")) page = localpdf.getPage(0) mergedpdf.addPage(page) else: localpdf = PdfFileReader(open(localfilename, "rb")) page.mergePage(localpdf.getPage(0)) output = open(filename, 'wb') mergedpdf.write(output) output.close()
def loop(self): self.m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = spherical_mercator.SphericalMercator(self.maxZoom + 1) while True: # Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists = "" if os.path.isfile(tile_uri): exists = "exists" else: self.render_tile(tile_uri, x, y, z) bytes = os.stat(tile_uri)[6] empty = '' if bytes == 103: empty = " Empty Tile " self.printLock.acquire() print(name, ":", z, x, y, exists, empty) self.printLock.release() self.q.task_done()
def loadXML(self, xmlfile, strict=False): tmp_map = Map(0, 0) load_map(tmp_map, xmlfile, strict) for lyr in tmp_map.layers: style_count = len(lyr.styles) if style_count == 0: raise ServerConfigurationError( "Cannot register Layer '%s' without a style" % lyr.name) elif style_count == 1: style_obj = tmp_map.find_style(lyr.styles[0]) style_obj = copy_style(style_obj) style_name = lyr.styles[0] if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) self.register_layer(copy_layer(lyr), style_name, extrastyles=(style_name, )) elif style_count > 1: for style_name in lyr.styles: style_obj = tmp_map.find_style(style_name) style_obj = copy_style(style_obj) if style_name not in self.aggregatestyles.keys( ) and style_name not in self.styles.keys(): self.register_style(style_name, style_obj) aggregates = tuple([sty for sty in lyr.styles]) aggregates_name = '%s_aggregates' % lyr.name self.register_aggregate_style(aggregates_name, aggregates) self.register_layer(copy_layer(lyr), aggregates_name, extrastyles=aggregates)
def renderToPdf(envLL, filename, sizex, sizey): """Renders the specified Box2d and zoom level as a PDF""" basefilename = os.path.splitext(filename)[0] mergedpdf = None for mapname in MAPNIK_LAYERS: print 'Rendering', mapname # Render layer PDF. localfilename = basefilename + '_' + mapname + '.pdf' file = open(localfilename, 'wb') surface = cairo.PDFSurface(file.name, sizex, sizey) envMerc = LLToMerc(envLL) map = mapnik.Map(sizex, sizey) mapnik.load_map(map, mapname + ".xml") map.zoom_to_box(envMerc) mapnik.render(map, surface) surface.finish() file.close() # Merge with master. if not mergedpdf: mergedpdf = PdfFileWriter() localpdf = PdfFileReader(open(localfilename, "rb")) page = localpdf.getPage(0) mergedpdf.addPage(page) else: localpdf = PdfFileReader(open(localfilename, "rb")) page.mergePage(localpdf.getPage(0)) output = open(filename, 'wb') mergedpdf.write(output) output.close()
def renderTile(self, width, height, srs, coord): """ """ if self.mapnik is None: self.mapnik = mapnik.Map(0, 0) mapnik.load_map(self.mapnik, str(self.mapfile)) nw = self.layer.projection.coordinateLocation(coord) se = self.layer.projection.coordinateLocation(coord.right().down()) ul = self.mercator.locationProj(nw) lr = self.mercator.locationProj(se) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y)) # create grid as same size as map/image grid = mapnik.Grid(width, height) # render a layer to that grid array mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields) # then encode the grid array as utf, resample to 1/scale the size, and dump features grid_utf = grid.encode("utf", resolution=self.scale, features=True) if self.wrapper is None: return SaveableResponse(json.dumps(grid_utf)) else: return SaveableResponse(self.wrapper + "(" + json.dumps(grid_utf) + ")")
def run(self): self.mapnik_map = mapnik2.Map(self.width, self.height) mapnik2.load_map(self.mapnik_map, self.config, True) self.map_projection = mapnik2.Projection(self.mapnik_map.srs) self.tile_projection = projections.GoogleProjection() while True: tile_parameters = None # Try to fetch a tile from any queue for tile_queue in self.tile_queues: try: tile_parameters = tile_queue.get_nowait() break except Queue.Empty: pass # Couldn't get tile parameters from any queue--all done if not tile_parameters: return # Skip rendering existing tiles if self.skip_existing: filename = tile_parameters[0] if os.path.exists(filename): print 'Skipping %s' % (filename) tile_queue.task_done() continue self.render(*tile_parameters) tile_queue.task_done()
def renderTile(self, width, height, srs, coord): """ """ if self.mapnik is None: self.mapnik = mapnik.Map(0, 0) mapnik.load_map(self.mapnik, str(self.mapfile)) # buffer as fraction of tile size buffer = float(self.buffer) / 256 nw = self.layer.projection.coordinateLocation(coord.left(buffer).up(buffer)) se = self.layer.projection.coordinateLocation(coord.right(1 + buffer).down(1 + buffer)) ul = self.mercator.locationProj(nw) lr = self.mercator.locationProj(se) self.mapnik.width = width + 2 * self.buffer self.mapnik.height = height + 2 * self.buffer self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y)) # create grid as same size as map/image grid = mapnik.Grid(width + 2 * self.buffer, height + 2 * self.buffer) # render a layer to that grid array mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields) # extract a gridview excluding the buffer grid_view = grid.view(self.buffer, self.buffer, width, height) # then encode the grid array as utf, resample to 1/scale the size, and dump features grid_utf = grid_view.encode('utf', resolution=self.scale, add_features=True) if self.wrapper is None: return SaveableResponse(json.dumps(grid_utf)) else: return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) + ')')
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): """ """ if self.mapnik is None: self.mapnik = mapnik.Map(0, 0) if exists(self.mapfile): mapnik.load_map(self.mapnik, str(self.mapfile)) else: handle, filename = mkstemp() os.write(handle, urlopen(self.mapfile).read()) os.close(handle) mapnik.load_map(self.mapnik, filename) os.unlink(filename) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(mapnik.Envelope(xmin, ymin, xmax, ymax)) img = mapnik.Image(width, height) mapnik.render(self.mapnik, img) img = Image.fromstring('RGBA', (width, height), img.tostring()) return img
def loop(self, nb): self.m = mapnik.Map(TILES_SIZE, TILES_SIZE) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(self.maxZoom + 1) while True: #Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists = "" if os.path.isfile(tile_uri + '.' + FILE_EXTENSION): exists = "exists" else: self.render_tile(tile_uri, x, y, z) self.printLock.acquire() print name, ":", z, x, y, exists self.printLock.release() self.q.task_done()
def test_hit_grid(): import os from itertools import groupby def rle_encode(l): """ encode a list of strings with run-length compression """ return ["%d:%s" % (len(list(group)), name) for name, group in groupby(l)] m = mapnik2.Map(256,256); mapnik2.load_map(m,'../data/good_maps/agg_poly_gamma_map.xml'); m.zoom_all() join_field = 'NAME' fg = [] # feature grid for y in range(0, 256, 4): for x in range(0, 256, 4): featureset = m.query_map_point(0,x,y) added = False for feature in featureset.features: fg.append(feature[join_field]) added = True if not added: fg.append('') hit_list = '|'.join(rle_encode(fg)) eq_(hit_list[:16],'730:|2:Greenland') eq_(hit_list[-12:],'1:Chile|812:')
def serialize(xml, options): try: import mapnik2 as mapnik except: try: import mapnik except: sys.exit( color_text( 1, 'Error: saving xml requires Mapnik python bindings to be installed' )) m = mapnik.Map(1, 1) if options.from_string: mapnik.load_map_from_string(m, xml, True) else: mapnik.load_map(m, xml, True) if options.output: mapnik.save_map(m, options.output) else: if hasattr(mapnik, 'mapnik_version') and mapnik.mapnik_version() >= 700: print mapnik.save_map_to_string(m) else: sys.exit( color_text( 1, 'Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file' ))
def serialize(xml, options): try: try: import mapnik2 as mapnik except ImportError: import mapnik except ImportError: sys.exit(color_text(1, "Error: saving xml requires Mapnik python bindings to be installed")) m = mapnik.Map(1, 1) if options.from_string: mapnik.load_map_from_string(m, xml, True) else: mapnik.load_map(m, xml, True) if options.output: mapnik.save_map(m, options.output) else: if hasattr(mapnik, "mapnik_version") and mapnik.mapnik_version() >= 700: print mapnik.save_map_to_string(m) else: sys.exit( color_text( 1, "Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file", ) )
def renderTile(self, width, height, srs, coord): """ """ if self.mapnik is None: self.mapnik = mapnik.Map(0, 0) mapnik.load_map(self.mapnik, str(self.mapfile)) nw = self.layer.projection.coordinateLocation(coord) se = self.layer.projection.coordinateLocation(coord.right().down()) ul = self.mercator.locationProj(nw) lr = self.mercator.locationProj(se) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y)) # create grid as same size as map/image grid = mapnik.Grid(width, height) # render a layer to that grid array mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields) # then encode the grid array as utf, resample to 1/scale the size, and dump features grid_utf = grid.encode('utf', resolution=self.scale, features=True) if self.wrapper is None: return SaveableResponse(json.dumps(grid_utf)) else: return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) + ')')
def loop(self, nb): self.m = mapnik.Map(TILES_SIZE, TILES_SIZE) # Load style XML mapnik.load_map(self.m, self.mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(self.maxZoom + 1) while True: #Fetch a tile from the queue and render it r = self.q.get() if (r == None): self.q.task_done() break else: (name, tile_uri, x, y, z) = r exists = "" if os.path.isfile(tile_uri + '.' + FILE_EXTENSION): exists = "exists" else: self.render_tile(tile_uri, x, y, z) self.printLock.acquire() print name, ":", z, x, y, exists self.printLock.release() self.q.task_done()
def drawTile_bbox(self,bbox,imgx,imgy,fname): """Call Mapnik to draw a map image for data in bounding box bbox. The image size is imgx by imgy pixels, and the output filename is fname. 29sep2009 GJ ORIGINAL VERSION, based on generate_image.py 06jan2010 GJ Renamed to drawTile_bbox from drawTile """ mapfile = str(self.preferences_list['mapfile']) map_uri = str(fname) print ("mapfile=%s" % mapfile) # png image m = mapnik.Map(imgx,imgy) mapnik.load_map(m,mapfile) m.zoom_to_box(bbox) im = mapnik.Image(imgx,imgy) if HAS_MAPNIK2: # We apply the scale factor to the map print 'using scale factors from mapnik2' scale_factor = float( self.preferences_list['dpi'] ) / 72 print "Scale factor is: ", scale_factor, "=================" mapnik.render(m, im, scale_factor) else: print 'NOT using scale_factors' mapnik.render(m, im) view = im.view(0,0,imgx,imgy) # x,y,width,height view.save(map_uri,'png')
def test_hit_grid(): import os from itertools import groupby def rle_encode(l): """ encode a list of strings with run-length compression """ return [ "%d:%s" % (len(list(group)), name) for name, group in groupby(l) ] m = mapnik2.Map(256, 256) mapnik2.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml') m.zoom_all() join_field = 'NAME' fg = [] # feature grid for y in range(0, 256, 4): for x in range(0, 256, 4): featureset = m.query_map_point(0, x, y) added = False for feature in featureset.features: fg.append(feature[join_field]) added = True if not added: fg.append('') hit_list = '|'.join(rle_encode(fg)) eq_(hit_list[:16], '730:|2:Greenland') eq_(hit_list[-12:], '1:Chile|812:')
def __init__( self, tilegrid, mapfile, data_buffer=128, image_buffer=0, output_format='png256', resolution=2, layers_fields={}, drop_empty_utfgrid=False, proj4_literal=None, **kwargs): """ Constructs a MapnikTileStore :param tilegrid: the tilegrid. :param mapfile: the file used to render the tiles. :param buffer_size: the image buffer size default is 128. :param output_format: the output format, possible values 'jpeg', 'png', 'png256', 'grid', default is 'png256' :param layers: the layers and fields used in the grid generation, example: { 'my_layer': ['my_first_field', 'my_segonf_field']}, default is {}. :param **kwargs: for extended class. """ TileStore.__init__(self, **kwargs) self.tilegrid = tilegrid self.buffer = image_buffer self.output_format = output_format self.resolution = resolution self.layers_fields = layers_fields self.drop_empty_utfgrid = drop_empty_utfgrid self.mapnik = mapnik.Map(tilegrid.tile_size, tilegrid.tile_size) mapnik.load_map(self.mapnik, mapfile, True) self.mapnik.buffer_size = data_buffer if proj4_literal is not None: self.mapnik.srs = proj4_literal
def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom): """ """ if self.mapnik is None: self.mapnik = mapnik.Map(0, 0) if exists(self.mapfile): mapnik.load_map(self.mapnik, str(self.mapfile)) else: handle, filename = mkstemp() os.write(handle, urlopen(self.mapfile).read()) os.close(handle) mapnik.load_map(self.mapnik, filename) os.unlink(filename) self.mapnik.width = width self.mapnik.height = height self.mapnik.zoom_to_box(mapnik.Envelope(xmin, ymin, xmax, ymax)) img = mapnik.Image(width, height) mapnik.render(self.mapnik, img) img = Image.fromstring("RGBA", (width, height), img.tostring()) return img
def render_location_with_variants(self, variants): # target projection #merc = mapnik.Projection('+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 +no_defs +over') data = [] for item in range(0,variants): if item == 0: teta = 0 zoom = 20 shift_lat = 0 shift_lon = 0 else: shift_lat = 0.1*self.size*(random.random()-random.random()) shift_lon = 0.1*self.size*(random.random()-random.random()) teta = 45 * (random.random()-random.random()) zoom = random.randint(17,21) layer = "complete" projec = mapnik.Projection('+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0='+str(teta)) # WGS lat/long source projection of centre longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapfile = "renderer/map_data/styles/bs_" + layer + ".xml" mapnik.load_map(m, mapfile) # ensure the target map projection is mercator m.srs = projec.params() # transform the centre point into the target coord sys centre = mapnik.Coord(self.lon+shift_lon, self.lat+shift_lat) transform = mapnik.ProjTransform(longlat, projec) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width,self.height) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) data.append(img) data = np.stack(data) return data
def init_zoomlevel(self, z): self.currentz = z self.tilesize = getTileSize(NTILES[z], True) self.maps = {} for mapName in MAPNIK_LAYERS: console.debugMessage('Loading mapnik.Map: ' + mapName) self.maps[mapName] = mapnik.Map(self.tilesize, self.tilesize) mapnik.load_map(self.maps[mapName], mapName + ".xml")
def compile(self, url, compile_callback): """ retrieve and compile a mapnik xml file. only called when the map is not already in static cache. calls compile_callback when """ self.mapnik_maps[url] = mapnik.Map(self.tilesize, self.tilesize) open("%s_compiled.xml" % self.filecache(url), 'w').write( cascadenik.compile(self.filecache(url), urlcache=True)) mapnik.load_map(self.mapnik_maps[url], "%s_compiled.xml" % self.filecache(url)) compile_callback(self.mapnik_maps[url])
def init_zoomlevel(self, z): self.currentz = z self.tilesize = getTileSize(NTILES[z], True) self.maps = {} for mapName in MAPNIK_LAYERS: console.debugMessage('Loading mapnik.Map: ' + mapName) self.maps[mapName] = mapnik.Map(self.tilesize, self.tilesize) mapnik.load_map(self.maps[mapName], mapName + ".xml")
def test_load_save_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/raster_symbolizer.xml" mapnik2.load_map(map, in_map) out_map = mapnik2.save_map_to_string(map) assert 'RasterSymbolizer' in out_map assert 'RasterColorizer' in out_map assert 'stop' in out_map
def test_load_save_map(): map = mapnik2.Map(256, 256) in_map = "../data/good_maps/raster_symbolizer.xml" mapnik2.load_map(map, in_map) out_map = mapnik2.save_map_to_string(map) assert 'RasterSymbolizer' in out_map assert 'RasterColorizer' in out_map assert 'ColorBand' in out_map
def __init__(self, tile_dir, mapfile, q, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) # Load style XML mapnik.load_map(self.m, mapfile, False) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(maxZoom+1)
def test_gen_map(): mapxmlfile = '../data/good_maps/raster_colorizer.xml' mapxmloutputfile = 'raster_colorizer_test_save.xml' outputfile = 'raster_colorizer_test.png' m = mapnik2.Map(800, 600) mapnik2.load_map(m, mapxmlfile) mapnik2.save_map(m, mapxmloutputfile) m.zoom_all() mapnik2.render_to_file(m, outputfile)
def test_gen_map(): mapxmlfile = '../data/good_maps/raster_colorizer.xml' mapxmloutputfile = 'raster_colorizer_test_save.xml' outputfile = 'raster_colorizer_test.png' m = mapnik2.Map(800, 600) mapnik2.load_map(m, mapxmlfile) mapnik2.save_map(m, mapxmloutputfile) m.zoom_all() mapnik2.render_to_file(m, outputfile)
def assert_loads_successfully(file): m = mapnik2.Map(512, 512) strict = True mapnik2.load_map(m, file, strict) # libxml2 is not smart about paths, and clips the last directory off # of a path if it does not end in a trailing slash base_path = os.path.dirname(file) + '/' mapnik2.load_map_from_string(m, open(file, 'rb').read(), strict, base_path)
def assert_loads_successfully(file): m = mapnik2.Map(512, 512) strict = True mapnik2.load_map(m, file, strict) # libxml2 is not smart about paths, and clips the last directory off # of a path if it does not end in a trailing slash base_path = os.path.dirname(file) + '/' mapnik2.load_map_from_string(m,open(file,'rb').read(),strict,base_path)
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) self.printLock = printLock # Load style XML mapnik.load_map(self.m, mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(maxZoom+1)
def run(image, stylesheet): #stylesheet = 'world_style.xml' #image = 'world_style.png' imgx = 600 imgy = 300 m = mapnik.Map(imgx, imgy) mapnik.load_map(m, stylesheet) m.zoom_all() mapnik.render_to_file(m, image) #print "rendered image to '%s'" % image return image
def run(image, stylesheet): #stylesheet = 'world_style.xml' #image = 'world_style.png' imgx = 600 imgy = 300 m = mapnik.Map(imgx, imgy) mapnik.load_map(m, stylesheet) m.zoom_all() mapnik.render_to_file(m, image) #print "rendered image to '%s'" % image return image
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) self.printLock = printLock # Load style XML mapnik.load_map(self.m, mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = spherical_mercator.SphericalMercator(maxZoom + 1)
def add_region(self,name,mapfile,wkt_mask_file): # ignore attempts to add regions when no mask has been # specified with a warning. if self.mask_map is not None: try: m = Map(0,0) load_map(m, mapfile) mask = Mask(wkt_mask_file) self.regions.append((name,m,mask)) except Exception as ex: mq_logging.error("Exception caught adding region (%s)" % str(ex)) else: mq_logging.warning("Cannot add mask (%s) because no mask_style was configured." % name)
def test_load_save_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/raster_symbolizer.xml" try: mapnik2.load_map(map, in_map) out_map = mapnik2.save_map_to_string(map) assert 'RasterSymbolizer' in out_map assert 'RasterColorizer' in out_map assert 'stop' in out_map except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(str(e))
def get_paired_images(w, h, mapfile): tmp_map = 'tmp_map.xml' m = mapnik2.Map(w, h) mapnik2.load_map(m, mapfile) i = mapnik2.Image(w, h) m.zoom_all() mapnik2.render(m, i) mapnik2.save_map(m, tmp_map) m2 = mapnik2.Map(w, h) mapnik2.load_map(m2, tmp_map) i2 = mapnik2.Image(w, h) m2.zoom_all() mapnik2.render(m2, i2) os.remove(tmp_map) return i, i2
def load_map(self): start = time.perf_counter() self.m = mapnik.Map(0, 0) # Load style XML if not self.opts.dry_run: mapnik.load_map(self.m, self.opts.mapfile, self.opts.mapnik_strict) end = time.perf_counter() info('[%s] Map loading took %.6fs', self.name, end - start) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = map_utils.GoogleProjection(opts.max_zoom + 1)
def get_paired_images(w,h,mapfile): tmp_map = 'tmp_map.xml' m = mapnik2.Map(w,h) mapnik2.load_map(m,mapfile) i = mapnik2.Image(w,h) m.zoom_all() mapnik2.render(m,i) mapnik2.save_map(m,tmp_map) m2 = mapnik2.Map(w,h) mapnik2.load_map(m2,tmp_map) i2 = mapnik2.Image(w,h) m2.zoom_all() mapnik2.render(m2,i2) os.remove(tmp_map) return i,i2
def __init__(self): self.MR['rpc_renderArea'] = {'minlat': [float, "Minimal latitude of map."], 'minlon': [float, "Minimal longitude of map."], 'maxlat': [float, "Maximal latitude of map."], 'maxlon': [float, "Maximal longitude of map."], } self.MR['rpc_renderCoord'] = {'lat': [float, "Minimal latitude of map."], 'lon': [float, "Minimal longitude of map."], 'zoom': [float, "Maximal longitude of map."], } self.rendermap = mapnik.Map(self.mapsize[0], self.mapsize[1]) mapnik.load_map(self.rendermap, self.mapfile) super(MapRenderer, self).__init__()
def __init__(self, d, m): QObject.__init__(self) self.map_file = m self.tile_dir = d if not self.tile_dir.endswith('/'): self.tile_dir = self.tile_dir + '/' if not os.path.isdir(self.tile_dir): os.makedirs(self.tile_dir) self.m = mapnik2.Map(TILESIZE, TILESIZE) mapnik2.load_map(self.m, self.map_file, True) self.prj = mapnik2.Projection(self.m.srs) self.tileproj = GoogleProjection(MAX_ZOOM + 1) self.render_thread = RenderThread(self.m, self.prj, self.tileproj)
def assert_loads_successfully(file): m = mapnik2.Map(512, 512) try: strict = True mapnik2.load_map(m, file, strict) # libxml2 is not smart about paths, and clips the last directory off # of a path if it does not end in a trailing slash base_path = os.path.dirname(file) + '/' mapnik2.load_map_from_string(m,open(file,'rb').read(),strict,base_path) except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(e)
def __init__(self, path_to_mapfile): self.max_zoom = 22 self.image_size = 256 self.mapnik = mapnik.Map(self.image_size, self.image_size) self.mapnik.srs = MERC_PROJ4 self.mercator = SphericalMercator(levels=self.max_zoom+1,size=self.image_size) mapnik.load_map(self.mapnik, path_to_mapfile) if not is_merc(self.mapnik.srs): self.mapnik_map.srs = MERC_PROJ4 # NOTE: Add better logging print 'Forcing Merc Projection.' self.mapnik_map.zoom_all() self.envelope = self._mapnik_map.envelope()
def load_map(self): start = time.perf_counter() self.m = mapnik.Map(self.image_size, self.image_size) # Load style XML if not self.opts.dry_run: mapnik.load_map(self.m, self.opts.mapfile, self.opts.strict) end = time.perf_counter() info('[%s] Map loading took %.6fs', self.pid, end - start) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = map_utils.GoogleProjection(opts.max_zoom + 1)
def _lazy_init_map(self): if self.m is None: #start = time.perf_counter() self.m = mapnik.Map(self.map_width, self.map_height) #print ("Mapnik took %r s" % (time.perf_counter()-start,)) #start = time.perf_counter() if self.mapfile is None: self.m.background = mapnik.Color('rgb(0,0,0,0)') #transparent else: mapnik.load_map(self.m, self.mapfile) #print ("loadint took %r s" % (time.perf_counter()-start,)) # Create a symbolizer to draw the points #if "openstreetmap-carto" in mapfile: self.draw_gpx_track(self.gpx_file, self.gpx_style)
def test_gen_map(): mapxmlfile = '../data/good_maps/raster_colorizer.xml' mapxmloutputfile = 'raster_colorizer_test_save.xml' outputfile = 'raster_colorizer_test.png' m = mapnik2.Map(800, 600) try: mapnik2.load_map(m, mapxmlfile) mapnik2.save_map(m, mapxmloutputfile) m.zoom_all() mapnik2.render_to_file(m, outputfile) except RuntimeError,e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(str(e))
def run(self): self.mapnik_map = mapnik2.Map(self.width, self.height) mapnik2.load_map(self.mapnik_map, self.config, True) self.map_projection = mapnik2.Projection(self.mapnik_map.srs) self.tile_projection = GoogleProjection() while True: try: tile_parameters = self.tile_queue.get_nowait() except Queue.Empty: break self.render_tile(*tile_parameters) self.tile_queue.task_done()
def __init__(self, tile_dir, mapfile, q, printLock, maxZoom): self.tile_dir = tile_dir self.q = q self.m = mapnik.Map(256, 256) self.printLock = printLock # Load style XML mapnik.load_map(self.m, mapfile, True) # Obtain <Map> projection self.prj = mapnik.Projection(self.m.srs) # Projects between tile pixel co-ordinates and LatLong (EPSG:4326) self.tileproj = GoogleProjection(maxZoom + 1) # For testing if tiles are blank blankTile = mapnik.Image(256, 256) blankTile.background = mapnik.Color("rgba(0,0,0,0)") self.blankTileStr = blankTile.tostring("png")
def _pycairo_surface(type,sym): if mapnik2.has_pycairo(): import cairo test_cairo_file = 'test.%s' % type m = mapnik2.Map(256,256) mapnik2.load_map(m,'../data/good_maps/%s_symbolizer.xml' % sym) surface = getattr(cairo,'%sSurface' % type.upper())(test_cairo_file, m.width,m.height) mapnik2.render(m, surface) surface.finish() if os.path.exists(test_cairo_file): os.remove(test_cairo_file) return True else: # Fail, the file wasn't written return False
def _pycairo_surface(type, sym): if mapnik2.has_pycairo(): import cairo test_cairo_file = 'test.%s' % type m = mapnik2.Map(256, 256) mapnik2.load_map(m, '../data/good_maps/%s_symbolizer.xml' % sym) surface = getattr(cairo, '%sSurface' % type.upper())(test_cairo_file, m.width, m.height) mapnik2.render(m, surface) surface.finish() if os.path.exists(test_cairo_file): os.remove(test_cairo_file) return True else: # Fail, the file wasn't written return False
def __init__(self): self.MR['rpc_renderArea'] = { 'minlat': [float, "Minimal latitude of map."], 'minlon': [float, "Minimal longitude of map."], 'maxlat': [float, "Maximal latitude of map."], 'maxlon': [float, "Maximal longitude of map."], } self.MR['rpc_renderCoord'] = { 'lat': [float, "Minimal latitude of map."], 'lon': [float, "Minimal longitude of map."], 'zoom': [float, "Maximal longitude of map."], } self.rendermap = mapnik.Map(self.mapsize[0], self.mapsize[1]) mapnik.load_map(self.rendermap, self.mapfile) super(MapRenderer, self).__init__()
def test_load_save_load_map(): map = mapnik2.Map(256, 256) in_map = "../data/good_maps/glyph_symbolizer.xml" mapnik2.load_map(map, in_map) style = map.find_style('arrows') sym = style.rules[0].symbols[0] assert isinstance(sym, mapnik2.GlyphSymbolizer) assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH out_map = mapnik2.save_map_to_string(map).decode('utf8') map = mapnik2.Map(256, 256) mapnik2.load_map_from_string(map, out_map.encode('utf8')) assert 'GlyphSymbolizer' in out_map assert 'RasterColorizer' in out_map # make sure non-ascii characters are well supported since most interesting # glyphs for symbology are usually in that range assert u'í' in out_map, out_map
def render_location_with_zoom(self, zoom): # target projection merc = mapnik.Projection('+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 +no_defs +over') # WGS lat/long source projection of centrel longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapnik.load_map(m, self.mapfile) # ensure the target map projection is mercator m.srs = merc.params() # transform the centre point into the target coord sys centre = mapnik.Coord(self.lon, self.lat) transform = mapnik.ProjTransform(longlat, merc) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d(minx, merc_centre.y-10, maxx, merc_centre.y+10) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width,self.height) mapnik.render(m, im) img = im.tostring('png256') img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1) img =np.asarray(img) window_name = "Location" cv2.imshow(window_name, img) cv2.waitKey(1)
def rendertiles(self, cpoint, data, item, label, lat, layer, lon, num_items, projec, zoom): # target projection #merc = mapnik.Projection('+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 +no_defs +over') merc = projec # WGS lat/long source projection of centre longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # make a new Map object for the given mapfile m = mapnik.Map(self.width, self.height) mapfile = "/map_data/styles/bs_" + layer + ".xml" mapnik.load_map(m, mapfile) # ensure the target map projection is mercator m.srs = merc.params() # transform the centre point into the target coord sys centre = mapnik.Coord(cpoint[0], cpoint[1]) transform = mapnik.ProjTransform(longlat, merc) merc_centre = transform.forward(centre) # 360/(2**zoom) degrees = 256 px # so in merc 1px = (20037508.34*2) / (256 * 2**zoom) # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units dx = ((20037508.34 * 2 * (self.width / 2))) / (256 * (2**(zoom))) minx = merc_centre.x - dx maxx = merc_centre.x + dx # grow the height bbox, as we only accurately set the width bbox m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT bounds = mapnik.Box2d( minx, merc_centre.y - 10, maxx, merc_centre.y + 10 ) # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT m.zoom_to_box(bounds) # render the map image to a file # mapnik.render_to_file(m, output) #render the map to an image im = mapnik.Image(self.width, self.height) mapnik.render(m, im) img = im.tostring('png256') data[(item, layer)] = img