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 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 render_dynamic(self, painter): if self.mapnik_map: w = painter.device().width() h = painter.device().height() # using canvas dims leads to shift in QGIS < 1.3... #w = self.canvas.width() #h = self.canvas.height() try: self.mapnik_map.resize(w, h) except: self.mapnik_map.width = w self.mapnik_map.height = h if self.qCanvas: can = self.qCanvas else: can = self.canvas try: e = can.extent() except: can = self.canvas e = can.extent() bbox = mapnik.Envelope(e.xMinimum(), e.yMinimum(), e.xMaximum(), e.yMaximum()) self.mapnik_map.zoom_to_box(bbox) im = mapnik.Image(w, h) mapnik.render(self.mapnik_map, im) if os.name == 'nt': qim = QImage() qim.loadFromData(QByteArray(im.tostring('png'))) painter.drawImage(0, 0, qim) else: qim = QImage(im.tostring(), w, h, QImage.Format_ARGB32) painter.drawImage(0, 0, qim.rgbSwapped()) can.refresh()
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 render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z) l1 = self.tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1])) # 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 = 256 self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) if (self.m.buffer_size < 128): self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri, 'png256')
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(self, filename, tile_x, tile_y, zoom): """ Render a single tile to a given filename. """ print 'Rendering %s' % (filename) # Calculate pixel positions of bottom-left & top-right half_width = self.width / 2 half_height = self.height / 2 px0 = (tile_x * self.width, (tile_y + 1) * self.height) px1 = ((tile_x + 1) * self.width, tile_y * self.height) # Convert tile coords to LatLng ll0 = self.tile_projection.fromPixelToLL(px0, zoom) ll1 = self.tile_projection.fromPixelToLL(px1, zoom) # Convert LatLng to map coords c0 = self.map_projection.forward(mapnik2.Coord(ll0[0], ll0[1])) c1 = self.map_projection.forward(mapnik2.Coord(ll1[0], ll1[1])) # Create bounding box for the render bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y) self.mapnik_map.zoom_to_box(bbox) self.mapnik_map.buffer_size = self.buffer_size # Render image with default renderer image = mapnik2.Image(self.width, self.height) mapnik2.render(self.mapnik_map, image) image.save(filename, self.filetype)
def get_one(self, tile): bbox = self.tilegrid.extent(tile.tilecoord, self.buffer) bbox2d = mapnik.Box2d(bbox[0], bbox[1], bbox[2], bbox[3]) size = tile.tilecoord.n * self.tilegrid.tile_size + 2 * self.buffer self.mapnik.resize(size, size) self.mapnik.zoom_to_box(bbox2d) if self.output_format == 'grid': grid = mapnik.Grid(self.tilegrid.tile_size, self.tilegrid.tile_size) for n, l in enumerate(self.mapnik.layers): if l.name in self.layers_fields: mapnik.render_layer(self.mapnik, grid, layer=n, fields=self.layers_fields[l.name]) encode = grid.encode('utf', resolution=self.resolution) if self.drop_empty_utfgrid and len(encode['data'].keys()) == 0: return None tile.data = dumps(encode) else: # Render image with default Agg renderer im = mapnik.Image(size, size) mapnik.render(self.mapnik, im) tile.data = im.tostring(self.output_format) return tile
def test_raster_warping_does_not_overclip_source(): lyrSrs = "+init=epsg:32630" mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik2.Layer('dataraster', lyrSrs) if 'gdal' in mapnik2.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik2.Gdal( file = '../data/raster/dataraster.tif', band = 1, ) sym = mapnik2.RasterSymbolizer() sym.colorizer = mapnik2.RasterColorizer(mapnik2.COLORIZER_DISCRETE, mapnik2.Color(255,255,0)) rule = mapnik2.Rule() rule.symbols.append(sym) style = mapnik2.Style() style.rules.append(rule) _map = mapnik2.Map(256,256, mapSrs) _map.background=mapnik2.Color('white') _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(mapnik2.Box2d(3,42,4,43)) im = mapnik2.Image(_map.width,_map.height) mapnik2.render(_map, im) # save a png somewhere so we can see it save_data('test_raster_warping_does_not_overclip_source.png', im.tostring('png')) assert im.view(0,200,1,1).tostring()=='\xff\xff\x00\xff'
def process(self, tile): #from lat,lng bbox to mapnik bbox p0 = self.map_proj.forward(Coord(tile.bbox[0][1],tile.bbox[0][0])) p1 = self.map_proj.forward(Coord(tile.bbox[1][1],tile.bbox[1][0])) bbox = Box2d(p0,p1) image = Image(tile.size[0],tile.size[1]) features = None result = self._check_region(bbox) if result is not None: if result[0]: result[1].resize(image.width(),image.height()) result[1].zoom_to_box(bbox) self.adjust_language(result(1), tile.lang) render(result[1],image) features = self.save_rendered_metadata(result[1], tile.size, tile.dimensions) else : mq_logging.info("COMPOSITE MAP: %s" % result[2]) default_image = Image(tile.size[0],tile.size[1]) # mask style self.mask_map.resize(image.width(),image.height()) self.mask_map.zoom_to_box(bbox) self.adjust_language(self.mask_map, tile.lang) render(self.mask_map,image) # default style self.default_map.resize(default_image.width(),default_image.height()) self.default_map.zoom_to_box(bbox) self.adjust_language(self.default_map, tile.lang) render(self.default_map,default_image) features = self.save_rendered_metadata(self.default_map, tile.size, tile.dimensions) # composite DST_OUT default_image.composite(image,CompositeOp.dst_out) # current style result[1].resize(image.width(),image.height()) result[1].zoom_to_box(bbox) image.set_alpha(0) self.adjust_language(result[1], tile.lang) render(result[1],image) if features is not None: features.features.extend(self.save_rendered_metadata(result[1], tile.size, tile.dimensions).features) else: features = self.save_rendered_metadata(result[1], tile.size, tile.dimensions) # blend image.blend(0,0,default_image,1.0) else : # use default style self.default_map.resize(image.width(),image.height()) self.default_map.zoom_to_box(bbox) self.adjust_language(self.default_map, tile.lang) render(self.default_map,image) features = self.save_rendered_metadata(self.default_map, tile.size, tile.dimensions) #convert to PIL image image = PIL.Image.frombuffer('RGBA', (image.width(), image.height()), image.tostring(), 'raw', 'RGBA', 0, 3) return RenderResult.from_image(tile, image, features)
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 render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z); l1 = self.tileproj.fromPixelToLL(p1, z); # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0],l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0],l1[1])) # 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 = 256 self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) if(self.m.buffer_size < 128): self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri, 'png256')
def render_dynamic(self, painter): if self.mapnik_map: w = painter.device().width() h = painter.device().height() # using canvas dims leads to shift in QGIS < 1.3... #w = self.canvas.width() #h = self.canvas.height() try: self.mapnik_map.resize(w,h) except: self.mapnik_map.width = w self.mapnik_map.height = h if self.qCanvas: can = self.qCanvas else: can = self.canvas try: e = can.extent() except: can = self.canvas e = can.extent() bbox = mapnik.Envelope(e.xMinimum(),e.yMinimum(), e.xMaximum(),e.yMaximum()) self.mapnik_map.zoom_to_box(bbox) im = mapnik.Image(w,h) mapnik.render(self.mapnik_map,im) if os.name == 'nt': qim = QImage() qim.loadFromData(QByteArray(im.tostring('png'))) painter.drawImage(0,0,qim) else: qim = QImage(im.tostring(),w,h,QImage.Format_ARGB32) painter.drawImage(0,0,qim.rgbSwapped()) can.refresh()
def rpc_renderArea(self, minlat, minlon, maxlat, maxlon): """ Renders a map for the given coordin """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' 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') # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection( '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') im = mapnik.Image(self.mapsize) m = self.rendermap m.srs = merc.params() bbox = mapnik.Box2d(minlat, minlon, maxlat, maxlon) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map)
def index(self): x = cherrypy.request.headers['x'] y = cherrypy.request.headers['y'] z = cherrypy.request.headers['z'] img = mapnik.Image() img.background = self._mapnik_map.background if not x or not y or not z: error_msg = "Failed request:\n\tx: %s\n\ty: %s\n\tz: %s\n" % (x, y, z) cherrypy.reponse.headers["Status"] = "400" return error_msg else: # NOTE: Process request correctly x = int(x) y = int(y) z = int(z) envelope = self.merc.xyz_to_envelope(x,y,zoom) if self.envelope.intersects(envelope): self._mapnik_map.zoom_to_box(envelope) self._mapnik_map.buffer_size = self.buffer_size mapnik.render(self._mapnik_map, img) cherrypy.reponse.headers["Status"] = "200" return img.tostring('png256')
def rpc_renderArea(self, minlat, minlon, maxlat, maxlon): """ Renders a map for the given coordin """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' 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') # long/lat in degrees, aka ESPG:4326 and "WGS 84" longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') # can also be constructed as: #longlat = mapnik.Projection('+init=epsg:4326') im = mapnik.Image(self.mapsize) m = self.rendermap m.srs = merc.params() bbox = mapnik.Box2d(minlat, minlon, maxlat, maxlon) transform = mapnik.ProjTransform(longlat, merc) merc_bbox = transform.forward(bbox) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map)
def get_one(self, tile): bbox = self.tilegrid.extent(tile.tilecoord, self.buffer) bbox2d = mapnik.Box2d(bbox[0], bbox[1], bbox[2], bbox[3]) size = tile.tilecoord.n * self.tilegrid.tile_size + 2 * self.buffer self.mapnik.resize(size, size) self.mapnik.zoom_to_box(bbox2d) if self.output_format == "grid": grid = mapnik.Grid(self.tilegrid.tile_size, self.tilegrid.tile_size) for n, l in enumerate(self.mapnik.layers): if l.name in self.layers_fields: mapnik.render_layer(self.mapnik, grid, layer=n, fields=self.layers_fields[l.name]) encode = grid.encode("utf", resolution=self.resolution) if self.drop_empty_utfgrid and len(encode["data"].keys()) == 0: return None tile.data = dumps(encode) else: # Render image with default Agg renderer im = mapnik.Image(size, size) mapnik.render(self.mapnik, im) tile.data = im.tostring(self.output_format) return tile
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_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z) l1 = self.tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1])) # 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 = 256 self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) # Ensure the tile isn't blank before saving if not im.tostring("png") == self.blankTileStr: im.save(tile_uri, "png256") # Return True if the tile was saved return True else: return False
def test_raster_warping(): lyrSrs = "+init=epsg:32630" mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik2.Layer('dataraster', lyrSrs) if 'gdal' in mapnik2.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik2.Gdal( file = '../data/raster/dataraster.tif', band = 1, ) sym = mapnik2.RasterSymbolizer() sym.colorizer = mapnik2.RasterColorizer(mapnik2.COLORIZER_DISCRETE, mapnik2.Color(255,255,0)) rule = mapnik2.Rule() rule.symbols.append(sym) style = mapnik2.Style() style.rules.append(rule) _map = mapnik2.Map(256,256, mapSrs) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) prj_trans = mapnik2.ProjTransform(mapnik2.Projection(mapSrs), mapnik2.Projection(lyrSrs)) _map.zoom_to_box(prj_trans.backward(lyr.envelope())) im = mapnik2.Image(_map.width,_map.height) mapnik2.render(_map, im) # save a png somewhere so we can see it save_data('test_raster_warping.png', im.tostring('png')) imdata = im.tostring() assert contains_word('\xff\xff\x00\xff', imdata)
def render_tile(self, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * TILE_SIZE, (y + 1) * TILE_SIZE) p1 = ((x + 1) * TILE_SIZE, y * TILE_SIZE) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z) l1 = self.tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1])) # 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 = TILE_SIZE self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) self.writer.write(x, y, z, im)
def get(self): mapfile = os.path.join(DATA_PATH, 'hazard', 'flood.shp') #mapfile = os.path.join(DATA_PATH, 'impact', 'impact.json') filename = os.path.join(DATA_PATH, 'pdf', 'report_map.pdf') filename2 = os.path.join(DATA_PATH, 'pdf', 'report_map.png') map = mapnik2.Map(600, 400) map.background = mapnik2.Color('steelblue') s = mapnik2.Style() r = mapnik2.Rule() polygon_symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color('#f2eff9')) r.symbols.append(polygon_symbolizer) line_symbolizer = mapnik2.LineSymbolizer(mapnik2.Color('rgb(50%,50%,50%)'),0.1) r.symbols.append(line_symbolizer) s.rules.append(r) map.append_style('My Style',s) ds = mapnik2.Shapefile(file=mapfile) layer = mapnik2.Layer('world') layer.datasource = ds layer.styles.append('My Style') map.layers.append(layer) map.zoom_all() mapnik2.render_to_file(map, filename2, 'png') #bbox = mapnik.Envelope(-180.0,-90.0,180.0,90.0) #map.zoom_to_box(bbox) surface = cairo.PDFSurface(filename, map.width, map.height) mapnik2.render(map, surface) surface.finish() with open(filename) as data: pdf = data.read() data.close() self.set_header("Content-Type", "application/pdf") self.write(pdf)
def render(self, filename, tile_x, tile_y, zoom): """ Render a single tile to a given filename. """ print 'Rendering %s' % (filename) # Calculate pixel positions of bottom-left & top-right half_width = self.width / 2 half_height = self.height / 2 px0 = (tile_x * self.width, (tile_y + 1) * self.height) px1 = ((tile_x + 1) * self.width, tile_y * self.height) # Convert tile coords to LatLng ll0 = self.tile_projection.fromPixelToLL(px0, zoom); ll1 = self.tile_projection.fromPixelToLL(px1, zoom); # Convert LatLng to map coords c0 = self.map_projection.forward(mapnik2.Coord(ll0[0], ll0[1])) c1 = self.map_projection.forward(mapnik2.Coord(ll1[0], ll1[1])) # Create bounding box for the render bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y) self.mapnik_map.zoom_to_box(bbox) self.mapnik_map.buffer_size = self.buffer_size # Render image with default renderer image = mapnik2.Image(self.width, self.height) mapnik2.render(self.mapnik_map, image) image.save(filename, self.filetype)
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 generate_map_tile(self, m, filename, z, x, y): # Code taken from OSM generate_tiles.py proj = GoogleProjection() mprj = mapnik.Projection(m.srs) p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) l0 = proj.fromPixelToLL(p0, z); l1 = proj.fromPixelToLL(p1, z); c0 = mprj.forward(mapnik.Coord(l0[0], l0[1])) c1 = mprj.forward(mapnik.Coord(l1[0], l1[1])) 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) m.resize(256, 256) m.zoom_to_box(bbox) im = mapnik.Image(256, 256) mapnik.render(m, im) # See https://github.com/mapnik/mapnik/wiki/OutputFormats for output # formats and special parameters. The default here is 32 bit PNG with 8 # bit per component and alpha channel. if mapnik_version == 2: im.save(str(filename), "png32") else: im.save(str(filename), "png")
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 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 draw(self): zoom = self.style.get('zoom') # save context self.ctx.save() self.ctx.scale(zoom, zoom) mapnik2.render(self.m, self.ctx) # restore saved context self.ctx.restore()
def test_simplest_render(): m = mapnik2.Map(256, 256) i = mapnik2.Image(m.width, m.height) mapnik2.render(m, i) s = i.tostring() eq_(s, 256 * 256 * '\x00\x00\x00\x00')
def test_render_points(): # Test for effectivenes of ticket #402 (borderline points get lost on reprojection) raise Todo("See: http://trac.mapnik2.org/ticket/402") if not mapnik2.has_pycairo(): return # create and populate point datasource (WGS84 lat-lon coordinates) places_ds = mapnik2.PointDatasource() places_ds.add_point(142.48, -38.38, "Name", "Westernmost Point") # westernmost places_ds.add_point(143.10, -38.60, "Name", "Southernmost Point") # southernmost # create layer/rule/style s = mapnik2.Style() r = mapnik2.Rule() symb = mapnik2.PointSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik2.Layer("Places", "+proj=latlon +datum=WGS84") lyr.datasource = places_ds lyr.styles.append("places_labels") # latlon bounding box corners ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) # render for different projections projs = { "latlon": "+proj=latlon +datum=WGS84", "merc": "+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs", "google": "+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m", "utm": "+proj=utm +zone=54 +datum=WGS84", } from cairo import SVGSurface for projdescr in projs.iterkeys(): m = mapnik2.Map(1000, 500, projs[projdescr]) m.append_style("places_labels", s) m.layers.append(lyr) p = mapnik2.Projection(projs[projdescr]) m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat))) # Render to SVG so that it can be checked how many points are there with string comparison import StringIO svg_memory_file = StringIO.StringIO() surface = SVGSurface(svg_memory_file, m.width, m.height) mapnik2.render(m, surface) surface.flush() surface.finish() svg = svg_memory_file.getvalue() svg_memory_file.close() num_points_present = len(places_ds.all_features()) num_points_rendered = svg.count("<image ") eq_( num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr), )
def updateMap(self): self.timer.stop() self.total_scale = 1.0 self.scale = False im = mapnik.Image(self.map.width, self.map.height) mapnik.render(self.map, im) #self.qim = QImage(im.tostring(), self.map.width, self.map.height, QImage.Format_ARGB32).rgbSwapped() self.pixmap = QPixmap.fromImage(QImage.loadFromData(QByteArray(im.tostring('png')))) self.update()
def test_multi_tile_policy(): srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik2.Layer('raster') if 'raster' in mapnik2.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik2.Raster( file = '../data/raster_tiles/${x}/${y}.tif', lox = -180, loy = -90, hix = 180, hiy = 90, multi = 1, tile_size = 256, x_width = 2, y_width = 2 ) lyr.srs = srs _map = mapnik2.Map(256, 256, srs) style = mapnik2.Style() rule = mapnik2.Rule() sym = mapnik2.RasterSymbolizer() rule.symbols.append(sym) style.rules.append(rule) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(lyr.envelope()) im = mapnik2.Image(_map.width, _map.height) mapnik2.render(_map, im) save_data('test_multi_tile_policy.png', im.tostring('png')) # test green chunk eq_(im.view(0,64,1,1).tostring(), '\x00\xff\x00\xff') eq_(im.view(127,64,1,1).tostring(), '\x00\xff\x00\xff') eq_(im.view(0,127,1,1).tostring(), '\x00\xff\x00\xff') eq_(im.view(127,127,1,1).tostring(), '\x00\xff\x00\xff') # test blue chunk eq_(im.view(128,64,1,1).tostring(), '\x00\x00\xff\xff') eq_(im.view(255,64,1,1).tostring(), '\x00\x00\xff\xff') eq_(im.view(128,127,1,1).tostring(), '\x00\x00\xff\xff') eq_(im.view(255,127,1,1).tostring(), '\x00\x00\xff\xff') # test red chunk eq_(im.view(0,128,1,1).tostring(), '\xff\x00\x00\xff') eq_(im.view(127,128,1,1).tostring(), '\xff\x00\x00\xff') eq_(im.view(0,191,1,1).tostring(), '\xff\x00\x00\xff') eq_(im.view(127,191,1,1).tostring(), '\xff\x00\x00\xff') # test magenta chunk eq_(im.view(128,128,1,1).tostring(), '\xff\x00\xff\xff') eq_(im.view(255,128,1,1).tostring(), '\xff\x00\xff\xff') eq_(im.view(128,191,1,1).tostring(), '\xff\x00\xff\xff') eq_(im.view(255,191,1,1).tostring(), '\xff\x00\xff\xff')
def test_render_points(): # Test for effectivenes of ticket #402 (borderline points get lost on reprojection) raise Todo("See: http://trac.mapnik2.org/ticket/402") if not mapnik2.has_pycairo(): return # create and populate point datasource (WGS84 lat-lon coordinates) places_ds = mapnik2.PointDatasource() places_ds.add_point(142.48, -38.38, 'Name', 'Westernmost Point') # westernmost places_ds.add_point(143.10, -38.60, 'Name', 'Southernmost Point') # southernmost # create layer/rule/style s = mapnik2.Style() r = mapnik2.Rule() symb = mapnik2.PointSymbolizer() symb.allow_overlap = True r.symbols.append(symb) s.rules.append(r) lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84') lyr.datasource = places_ds lyr.styles.append('places_labels') # latlon bounding box corners ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) # render for different projections projs = { 'latlon': '+proj=latlon +datum=WGS84', 'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs', 'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m', 'utm': '+proj=utm +zone=54 +datum=WGS84' } from cairo import SVGSurface for projdescr in projs.iterkeys(): m = mapnik2.Map(1000, 500, projs[projdescr]) m.append_style('places_labels', s) m.layers.append(lyr) p = mapnik2.Projection(projs[projdescr]) m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat))) # Render to SVG so that it can be checked how many points are there with string comparison import StringIO svg_memory_file = StringIO.StringIO() surface = SVGSurface(svg_memory_file, m.width, m.height) mapnik2.render(m, surface) surface.flush() surface.finish() svg = svg_memory_file.getvalue() svg_memory_file.close() num_points_present = len(places_ds.all_features()) num_points_rendered = svg.count('<image ') eq_( num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr))
def updateMap(self): self.timer.stop() self.total_scale = 1.0 self.scale = False im = mapnik.Image(self.map.width, self.map.height) mapnik.render(self.map, im) #self.qim = QImage(im.tostring(), self.map.width, self.map.height, QImage.Format_ARGB32).rgbSwapped() self.pixmap = QPixmap.fromImage( QImage.loadFromData(QByteArray(im.tostring('png')))) self.update()
def test_renders_with_agg(): sym = mapnik2.GlyphSymbolizer("DejaVu Sans Condensed", mapnik2.Expression("'í'")) sym.allow_overlap = True sym.angle = mapnik2.Expression("[azimuth]+90") #+90 so the top of the glyph points upwards sym.size = mapnik2.Expression("[value]") sym.color = mapnik2.Expression("'#ff0000'") _map = create_map_and_append_symbolyzer(sym) im = mapnik2.Image(_map.width,_map.height) mapnik2.render(_map, im) save_data('agg_glyph_symbolizer.png', im.tostring('png')) assert contains_word('\xff\x00\x00\xff', im.tostring())
def test_renders_with_agg(): sym = mapnik2.GlyphSymbolizer("DejaVu Sans Condensed", mapnik2.Expression("'í'")) sym.allow_overlap = True sym.angle = mapnik2.Expression( "[azimuth]+90") #+90 so the top of the glyph points upwards sym.size = mapnik2.Expression("[value]") sym.color = mapnik2.Expression("'#ff0000'") _map = create_map_and_append_symbolyzer(sym) im = mapnik2.Image(_map.width, _map.height) mapnik2.render(_map, im) save_data('agg_glyph_symbolizer.png', im.tostring('png')) assert contains_word('\xff\x00\x00\xff', im.tostring())
def async_get(self, mapnik_map): envelope = self.application._merc.xyz_to_envelope(self.x, self.y, self.z, self.tms_style) mapnik_map.zoom_to_box(envelope) mapnik_map.buffer_size = options.buffer_size try: if options.tile_cache: mapnik_map.set_metawriter_property('tile_dir', self.application._tile_cache.local_dir(self.mapfile, '')) mapnik_map.set_metawriter_property('z', str(self.z)) mapnik_map.set_metawriter_property('x', str(self.x)) mapnik_map.set_metawriter_property('y', str(self.y)) url = "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype) self.application._tile_cache.prepare_dir(self.mapfile, url) mapnik.render_to_file(mapnik_map, self.application._tile_cache.local_url(self.mapfile, url)) if self.application._tile_cache.contains(self.mapfile, "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype)): self.set_header('Content-Type', 'image/png') self.write(self.application._tile_cache.get(self.mapfile, "%d/%d/%d.%s" % (self.z, self.x, self.y, self.filetype))) if self.application._tile_cache.contains(self.mapfile, "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json')): code_string = self.fString(self.mapfile, self.z, self.x, self.y) jsonp_str = "%s(%s)" % (code_string, json_encode({ 'features': json_decode(str(self.application._tile_cache.get(self.mapfile, "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json')))), 'code_string': code_string})) self.application._tile_cache.set(self.mapfile, "%d/%d/%d.%s" % (self.z, self.x, self.y, 'json'), jsonp_str) self.finish() return else: im = mapnik.Image(options.tilesize, options.tilesize) mapnik.render(mapnik_map, im) self.set_header('Content-Type', 'image/png') im_data = im.tostring('png') self.write(im_data) self.finish() return except RuntimeError: logging.error('Map for %s failed to render, cache reset', self.mapfile) self.application._map_cache.remove(self.mapfile) # Retry exactly once to re-render this tile. if not hasattr(self, 'retry'): self.retry = True self.get(self.mapfile, 'tms', self.z, self.x, self.y, self.filetype)
def renderLayer(name, z, x, y, ntiles, map, suffix = 'png', useCairo = False): """Renders the specified map tile (layer) as a mapnik.Image.""" console.debugMessage(' Rendering layer: ' + name) env = getMercTileEnv(z, x, y, ntiles, True) tilesize = getTileSize(ntiles, True) map.zoom_to_box(env) if useCairo and USE_CAIRO: assert mapnik.has_cairo() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, tilesize, tilesize) mapnik.render(map, surface) image = mapnik.Image.from_cairo(surface) else: image = mapnik.Image(tilesize, tilesize) mapnik.render(map, image) return image
def renderLayer(name, z, x, y, ntiles, map, suffix='png', useCairo=False): """Renders the specified map tile (layer) as a mapnik.Image.""" console.debugMessage(' Rendering layer: ' + name) env = getMercTileEnv(z, x, y, ntiles, True) tilesize = getTileSize(ntiles, True) map.zoom_to_box(env) if useCairo and USE_CAIRO: assert mapnik.has_cairo() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, tilesize, tilesize) mapnik.render(map, surface) image = mapnik.Image.from_cairo(surface) else: image = mapnik.Image(tilesize, tilesize) mapnik.render(map, image) return image
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 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 _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 _render_map(self, page, bbox): self._m.zoom_to_box(bbox) mapnik.render(self._m,self._im,self.area.scale) imagefile=tempfile.NamedTemporaryFile(suffix='.png',delete=True) self._im.save(imagefile.name) # Set up the cairo ImageSurface imgsurface = cairo.ImageSurface.create_from_png(imagefile) self._ctx.save() self.area.sheet.draw_inset(self._ctx,page) self._ctx.clip() self._ctx.scale(POINTS_PER_INCH/self.area.dpi,POINTS_PER_INCH/self.area.dpi) self._ctx.set_source_surface(imgsurface) self._ctx.paint() self._ctx.restore()
def rpc_renderCoordOld(self, lat, lon, zoom): """ Renders a map for the given coordinates. """ Map = None LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp' im = mapnik.Image(self.mapsize[0], self.mapsize[1]) m = mapnik.Map(self.mapsize[0], self.mapsize[1]) m.background = mapnik.Color(self.backgroundColor) s = mapnik.Style() r = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer( mapnik.Color(self.foregroundColor)) r.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer( mapnik.Color('rgb(50%,50%,50%)'), 0.1) r.symbols.append(line_symbolizer) s.rules.append(r) m.append_style('My Style', s) ds = mapnik.Shapefile(file=LandmassShapefile) layer = mapnik.Layer('world') layer.datasource = ds layer.styles.append('My Style') m.layers.append(layer) center = mapnik.Coord(lat, lon) transform = mapnik.ProjTransform(self.longlat, self.merc) merc_center = transform.forward(center) dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom))) minx = merc_center.x - dx maxx = merc_center.x + dx m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx, merc_center.y + 1) m.zoom_to_box(merc_bbox) mapnik.render(m, im) Map = im.tostring('png') return (True, Map)
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 render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z) l1 = self.tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1])) # 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 = 256 self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri, 'png256') grid_uri = tile_uri.replace('.png', '.grid.json') # new mapnik.Grid api, works like mapnik.Image # with the exception that you can only render one # layer to it with the mapnik.render_layer function # create grid as same size as map/image grid = mapnik.Grid(render_size, render_size) # render a layer to that grid array mapnik.render_layer(self.m, grid, layer=0, fields=['POP2005', 'NAME']) # then encode the grid array as utf, resample to 1/4 the size, and dump features grid_utf = grid.encode('utf', resolution=4, add_features=True) # below is the old grid api - will be removed soon, don't use #grid_utf = mapnik.render_grid(self.m,0,key='__id__',resolution=4,fields=['POP2005','NAME']) # client code uses jsonp, so fake by wrapping in grid() callback open(grid_uri, 'wb').write('grid(' + json.dumps(grid_utf) + ')')
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 test_dataraster_coloring(): srs = '+init=epsg:32630' lyr = mapnik2.Layer('dataraster') lyr.datasource = mapnik2.Gdal( file='../data/raster/dataraster.tif', band=1, ) lyr.srs = srs _map = mapnik2.Map(256, 256, srs) style = mapnik2.Style() rule = mapnik2.Rule() sym = mapnik2.RasterSymbolizer() # Assigning a colorizer to the RasterSymbolizer tells the later # that it should use it to colorize the raw data raster sym.colorizer = mapnik2.RasterColorizer(mapnik2.COLORIZER_DISCRETE, mapnik2.Color("transparent")) for value, color in [ (0, "#0044cc"), (10, "#00cc00"), (20, "#ffff00"), (30, "#ff7f00"), (40, "#ff0000"), (50, "#ff007f"), (60, "#ff00ff"), (70, "#cc00cc"), (80, "#990099"), (90, "#660066"), (200, "transparent"), ]: sym.colorizer.add_stop(value, mapnik2.Color(color)) rule.symbols.append(sym) style.rules.append(rule) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(lyr.envelope()) im = mapnik2.Image(_map.width, _map.height) mapnik2.render(_map, im) # save a png somewhere so we can see it save_data('test_dataraster_coloring.png', im.tostring('png')) imdata = im.tostring() # we have some values in the [20,30) interval so check that they're colored assert contains_word('\xff\xff\x00\xff', imdata)
def test_dataraster_coloring(): srs = '+init=epsg:32630' lyr = mapnik2.Layer('dataraster') if 'gdal' in mapnik2.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik2.Gdal( file = '../data/raster/dataraster.tif', band = 1, ) lyr.srs = srs _map = mapnik2.Map(256,256, srs) style = mapnik2.Style() rule = mapnik2.Rule() sym = mapnik2.RasterSymbolizer() # Assigning a colorizer to the RasterSymbolizer tells the later # that it should use it to colorize the raw data raster sym.colorizer = mapnik2.RasterColorizer(mapnik2.COLORIZER_DISCRETE, mapnik2.Color("transparent")) for value, color in [ ( 0, "#0044cc"), ( 10, "#00cc00"), ( 20, "#ffff00"), ( 30, "#ff7f00"), ( 40, "#ff0000"), ( 50, "#ff007f"), ( 60, "#ff00ff"), ( 70, "#cc00cc"), ( 80, "#990099"), ( 90, "#660066"), ( 200, "transparent"), ]: sym.colorizer.add_stop(value, mapnik2.Color(color)) rule.symbols.append(sym) style.rules.append(rule) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(lyr.envelope()) im = mapnik2.Image(_map.width,_map.height) mapnik2.render(_map, im) # save a png somewhere so we can see it save_data('test_dataraster_coloring.png', im.tostring('png')) imdata = im.tostring() # we have some values in the [20,30) interval so check that they're colored assert contains_word('\xff\xff\x00\xff', imdata)
def render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * 256, (y + 1) * 256) p1 = ((x + 1) * 256, y * 256) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z); l1 = self.tileproj.fromPixelToLL(p1, z); # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0],l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0],l1[1])) # 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 = 256 self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri, 'png256') grid_uri = tile_uri.replace('.png','.grid.json') # new mapnik.Grid api, works like mapnik.Image # with the exception that you can only render one # layer to it with the mapnik.render_layer function # create grid as same size as map/image grid = mapnik.Grid(render_size, render_size) # render a layer to that grid array mapnik.render_layer(self.m,grid,layer=0,fields=['POP2005','NAME']) # then encode the grid array as utf, resample to 1/4 the size, and dump features grid_utf = grid.encode('utf',resolution=4,add_features=True) # below is the old grid api - will be removed soon, don't use #grid_utf = mapnik.render_grid(self.m,0,key='__id__',resolution=4,fields=['POP2005','NAME']) # client code uses jsonp, so fake by wrapping in grid() callback open(grid_uri,'wb').write('grid(' + json.dumps(grid_utf) + ')')
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
def test_renders_with_cairo(): if not mapnik2.has_pycairo(): return sym = mapnik2.GlyphSymbolizer("DejaVu Sans Condensed", mapnik2.Expression("'í'")) sym.allow_overlap = True sym.angle = mapnik2.Expression( "[azimuth]+90") #+90 so the top of the glyph points upwards sym.size = mapnik2.Expression("[value]") sym.color = mapnik2.Expression("'#ff0000'") _map = create_map_and_append_symbolyzer(sym) from cStringIO import StringIO import cairo surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 256, 256) mapnik2.render(_map, surface) im = mapnik2.Image.from_cairo(surface) save_data('cairo_glyph_symbolizer.png', im.tostring('png')) assert contains_word('\xff\x00\x00\xff', im.tostring())
def render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right p0 = (x * TILES_SIZE, (y + 1) * TILES_SIZE) p1 = ((x + 1) * TILES_SIZE, y * TILES_SIZE) # Convert to LatLong (EPSG:4326) l0 = self.tileproj.fromPixelToLL(p0, z) l1 = self.tileproj.fromPixelToLL(p1, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1])) c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1])) # 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 = TILES_SIZE self.m.resize(render_size, render_size) self.m.zoom_to_box(bbox) self.m.buffer_size = 128 if FORMAT == 'grid': grid = mapnik.Grid(render_size, render_size) # mapnik.render_layer(self.m, grid, layer=64, fields=['name']) for n, l in enumerate(self.m.layers): if l.name != 'admin-012345678': if 'name' in l.datasource.fields(): mapnik.render_layer(self.m, grid, layer=n, fields=['name']) utfgrid = grid.encode('utf', resolution=4) f = open(tile_uri + '.' + FILE_EXTENSION, 'w') f.write(json.dumps(utfgrid)) f.close() else: # Render image with default Agg renderer im = mapnik.Image(render_size, render_size) mapnik.render(self.m, im) im.save(tile_uri + '.' + FILE_EXTENSION, FORMAT)
def complexRun(image, stylesheet, extent, size): mapfile = stylesheet map_uri = image imgx = size[0] imgy = size[1] m = mapnik.Map(imgx, imgy) mapnik.load_map(m, mapfile) if hasattr(mapnik, 'mapnik_version') and mapnik.mapnik_version() >= 800: bbox = mapnik.Box2d(extent[0], extent[2], extent[1], extent[3]) else: bbox = mapnik.Envelope(extent[0], extent[2], extent[1], extent[3]) m.zoom_to_box(bbox) im = mapnik.Image(imgx, imgy) mapnik.render(m, im) view = im.view(0, 0, imgx, imgy) # x,y,width,height view.save(map_uri, 'png')
def rpc_renderCoord(self, lat, lon, zoom): im = mapnik.Image(self.mapsize[0], self.mapsize[1]) center = mapnik.Coord(lat, lon) transform = mapnik.ProjTransform(self.longlat, self.merc) merc_center = transform.forward(center) dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom))) minx = merc_center.x - dx maxx = merc_center.x + dx self.rendermap.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx, merc_center.y + 1) self.rendermap.zoom_to_box(merc_bbox) mapnik.render(self.rendermap, im) Map = im.tostring('png') return (True, Map)
def renderLayer(name, z, x, y, ntiles, map, suffix='png'): """Renders the specified map tile (layer) as a mapnik.Image.""" if name in CACHE_LAYERS and cachedMetaTileExists(name, z, x, y, 'png'): console.debugMessage(' Using cached: ' + name) return mapnik.Image.open(getCachedMetaTilePath(name, z, x, y, 'png')) console.debugMessage(' Rendering layer: ' + name) env = getMercTileEnv(z, x, y, ntiles, True) tilesize = getTileSize(ntiles, True) map.zoom_to_box(env) if USE_CAIRO and name in CAIRO_LAYERS: assert mapnik.has_cairo() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, tilesize, tilesize) mapnik.render(map, surface) image = mapnik.Image.from_cairo(surface) else: image = mapnik.Image(tilesize, tilesize) mapnik.render(map, image) if name in CACHE_LAYERS: ensureDirExists(getCachedMetaTileDir(name, z, x)) image.save(getCachedMetaTilePath(name, z, x, y, 'png')) return image
def renderToPng(envLL, filename, sizex, sizey, base='hypsorelief'): """Renders the specified Box2d and zoom level as a PNG""" layers = [base, 'areas', 'ocean', 'contours', 'features'] if base == 'landcoverrelief': layers.remove('areas') images = {} for mapname in layers: console.debugMessage(' Rendering layer: ' + mapname) map = mapnik.Map(sizex, sizey) mapnik.load_map(map, mapname + ".xml") map.zoom_to_box(LLToMerc(envLL)) if USE_CAIRO and mapname in ['ocean', 'contours', 'features']: assert mapnik.has_cairo() surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, sizex, sizey) mapnik.render(map, surface) images[mapname] = mapnik.Image.from_cairo(surface) else: images[mapname] = mapnik.Image(sizex, sizey) mapnik.render(map, images[mapname]) image = getComposite([images[m] for m in layers]) image.save(filename, 'png')