def test_setting_alpha(): w, h = 256, 256 im1 = mapnik2.Image(w, h) # white, half transparent im1.background = mapnik2.Color('rgba(255,255,255,.5)') # pure white im2 = mapnik2.Image(w, h) im2.background = mapnik2.Color('rgba(255,255,255,1)') im2.set_alpha(.5) eq_(len(im1.tostring()), len(im2.tostring()))
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 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_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_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 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 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 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 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) 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_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 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_image_to_string(): i = mapnik2.Image(256, 256) i.background = mapnik2.Color('black') s = i.tostring() eq_(s, 256 * 256 * '\x00\x00\x00\xff') s = i.tostring('png')
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 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 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 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 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 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 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_render_image_to_file(): i = mapnik2.Image(256, 256) i.background = mapnik2.Color('black') if mapnik2.has_jpeg(): i.save('test.jpg') i.save('test.png', 'png') if os.path.exists('test.jpg'): os.remove('test.jpg') else: return False if os.path.exists('test.png'): os.remove('test.png') else: return False
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')
def render_tile(self, tile_uri, x, y, z): # Calculate pixel positions of bottom-left & top-right # start=time.time() # p0 = (x * TILESIZE, (y + 1) * TILESIZE) # p1 = ((x + 1) * TILESIZE, y * TILESIZE) # # # 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(mapnik2.Coord(l0[0],l0[1])) # c1 = self.prj.forward(mapnik2.Coord(l1[0],l1[1])) l0y, l0x = num2deg(x, y + 1, z) l1y, l1x = num2deg(x + 1, y, z) # Convert to map projection (e.g. mercator co-ords EPSG:900913) c0 = self.prj.forward(mapnik2.Coord(l0x, l0y)) c1 = self.prj.forward(mapnik2.Coord(l1x, l1y)) # Bounding box for the tile if hasattr(mapnik2, 'mapnik_version') and mapnik2.mapnik_version() >= 800: bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y) else: bbox = mapnik2.Envelope(c0.x, c0.y, c1.x, c1.y) render_size = TILESIZE 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 = mapnik2.Image(render_size, render_size) # print("%f"%(time.time()-start)) # start=time.time() mapnik2.render(self.m, im) # print("%f"%(time.time()-start)) # start=time.time() im.save(tile_uri, 'png256')
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) im.save(str(filename), "png256")