def test_dataraster_query_point(): srs = '+init=epsg:32630' lyr = mapnik.Layer('dataraster') if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file = '../data/raster/dataraster.tif', band = 1, ) lyr.srs = srs _map = mapnik.Map(256,256, srs) _map.layers.append(lyr) x, y = 556113.0,4381428.0 # center of extent of raster _map.zoom_all() features = _map.query_point(0,x,y).features assert len(features) == 1 feat = features[0] center = feat.envelope().center() assert center.x==x and center.y==y, center value = feat['value'] assert value == 18.0, value # point inside map extent but outside raster extent current_box = _map.envelope() current_box.expand_to_include(-427417,4477517) _map.zoom_to_box(current_box) features = _map.query_point(0,-427417,4477517).features assert len(features) == 0 # point inside raster extent with nodata features = _map.query_point(0,126850,4596050).features assert len(features) == 0
def test_dataraster_query_point(): srs = '+init=epsg:32630' lyr = mapnik.Layer('dataraster') if 'gdal' in mapnik.DatasourceCache.instance().plugin_names(): lyr.datasource = mapnik.Gdal( file='../data/raster/dataraster.tif', band=1, ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) _map.layers.append(lyr) # point inside raster extent with valid data x, y = 427417, 4477517 features = _map.query_point(0, x, y).features assert len(features) == 1 feat = features[0] center = feat.envelope().center() assert center.x == x and center.y == y, center value = feat['value'] assert value == 21.0, value # point outside raster extent features = _map.query_point(0, -427417, 4477517).features assert len(features) == 0 # point inside raster extent with nodata features = _map.query_point(0, 126850, 4596050).features assert len(features) == 0
def __init__(self): BaseWMSFactory.__init__(self) for data in datas: name = data['name'] title = data['long_name'] data = base_path+"/ecohealth/"+name+'.asc' layer = mapnik.Layer(name,"+init=epsg:4326") layer.datasource = mapnik.Gdal(file=str(data),band=1) layer.title = title layer.queryable = True layer.wms_srs = None style = mapnik.Style() rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent")) scale = getEcohealthScale(name) for color in scale: sym.colorizer.add_stop(color['stop'], mapnik.Color(*color['color'])) rule.symbols.append(sym) style.rules.append(rule) self.register_style(name,style) self.register_layer(layer, name, (name,)) self.finalize()
def get_raster_map(): m = mapnik.Map(map_width, map_height) m.background = mapnik.Color('black') m.srs = map_srs s = mapnik.Style() r = mapnik.Rule() raster_symbolizer = mapnik.RasterSymbolizer() raster_symbolizer.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent")) raster_symbolizer.colorizer.add_stop(0.0, mapnik.COLORIZER_LINEAR, mapnik.Color("black")) raster_symbolizer.colorizer.add_stop(1.0, mapnik.COLORIZER_LINEAR, mapnik.Color("white")) r.symbols.append(raster_symbolizer) s.rules.append(r) m.append_style('raster_style', s) lyr = mapnik.Layer('urban') lyr.datasource = mapnik.Gdal(base='./ne_110m_admin_0_countries', file='urban19901.tif', band=1) lyr.styles.append('raster_style') m.layers.append(lyr) return m
def _addStyleToMap(self, m, layerSrs, colorizer=None, band=-1, extent=None, composite=None, nodata=None): """ Add a mapik raster symbolizer to a map. :param m: mapnik map. :param layerSrs: the layer projection :param colorizer: a mapnik colorizer. :param band: an integer band number. -1 for default. :param extent: the extent to use for the mapnik layer. :param composite: the composite operation to use. This is one of mapnik.CompositeOp.xxx, typically lighten or multiply. :param nodata: the value to use for missing data or None to use all data. """ styleName = 'Raster Style' if band != -1: styleName += ' ' + str(band) rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() if colorizer is not None: sym.colorizer = colorizer rule.symbols.append(sym) style = mapnik.Style() style.rules.append(rule) if composite is not None: style.comp_op = composite m.append_style(styleName, style) lyr = mapnik.Layer('layer') lyr.srs = layerSrs lyr.datasource = mapnik.Gdal( base=None, file=self._path, band=band, extent=extent, nodata=nodata) lyr.styles.append(styleName) m.layers.append(lyr)
def test_raster_warping_does_not_overclip_source(): lyrSrs = "+init=epsg:32630" mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik.Layer('dataraster', lyrSrs) if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file='../data/raster/dataraster.tif', band=1, ) sym = mapnik.RasterSymbolizer() sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(255, 255, 0)) rule = mapnik.Rule() rule.symbols.append(sym) style = mapnik.Style() style.rules.append(rule) _map = mapnik.Map(256, 256, mapSrs) _map.background = mapnik.Color('white') _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(mapnik.Box2d(3, 42, 4, 43)) im = mapnik.Image(_map.width, _map.height) mapnik.render(_map, im) assert im.view(0, 200, 1, 1).tostring() == '\xff\xff\x00\xff'
def test_raster_warping(): lyrSrs = "+init=epsg:32630" mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik.Layer('dataraster', lyrSrs) if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file='../data/raster/dataraster.tif', band=1, ) sym = mapnik.RasterSymbolizer() sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(255, 255, 0)) rule = mapnik.Rule() rule.symbols.append(sym) style = mapnik.Style() style.rules.append(rule) _map = mapnik.Map(256, 256, mapSrs) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) map_proj = mapnik.Projection(mapSrs) layer_proj = mapnik.Projection(lyrSrs) prj_trans = mapnik.ProjTransform(map_proj, layer_proj) _map.zoom_to_box(prj_trans.backward(lyr.envelope())) im = mapnik.Image(_map.width, _map.height) mapnik.render(_map, im) imdata = im.tostring() assert contains_word('\xff\xff\x00\xff', imdata)
def test_raster_with_alpha_blends_correctly_with_background(): WIDTH = 500 HEIGHT = 500 map = mapnik.Map(WIDTH, HEIGHT) WHITE = mapnik.Color(255, 255, 255) map.background = WHITE style = mapnik.Style() rule = mapnik.Rule() symbolizer = mapnik.RasterSymbolizer() symbolizer.scaling = mapnik.scaling_method.BILINEAR rule.symbols.append(symbolizer) style.rules.append(rule) map.append_style('raster_style', style) map_layer = mapnik.Layer('test_layer') filepath = '../data/raster/white-alpha.png' if 'gdal' in mapnik.DatasourceCache.plugin_names(): map_layer.datasource = mapnik.Gdal(file=filepath) map_layer.styles.append('raster_style') map.layers.append(map_layer) map.zoom_all() mim = mapnik.Image(WIDTH, HEIGHT) mapnik.render(map, mim) imdata = mim.tostring() # All white is expected eq_(get_unique_colors(mim),['rgba(254,254,254,255)'])
def test_raster_warping_does_not_overclip_source(): lyrSrs = "+init=epsg:32630" mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' lyr = mapnik.Layer('dataraster', lyrSrs) if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file = '../data/raster/dataraster.tif', band = 1, ) sym = mapnik.RasterSymbolizer() sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(255,255,0)) rule = mapnik.Rule() rule.symbols.append(sym) style = mapnik.Style() style.rules.append(rule) _map = mapnik.Map(256,256, mapSrs) _map.background=mapnik.Color('white') _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(mapnik.Box2d(3,42,4,43)) im = mapnik.Image(_map.width,_map.height) mapnik.render(_map, im) expected_file = './images/support/raster_warping_does_not_overclip_source.png' actual_file = '/tmp/' + os.path.basename(expected_file) im.save(actual_file,'png32') if not os.path.exists(expected_file) or os.environ.get('UPDATE'): im.save(expected_file,'png32') actual = mapnik.Image.open(actual_file) expected = mapnik.Image.open(expected_file) eq_(actual.tostring('png32'),expected.tostring('png32'), 'failed comparing actual (%s) and expected (%s)' % (actual_file,expected_file))
def test_vrt_referring_to_missing_files(): srs = '+init=epsg:32630' if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr = mapnik.Layer('dataraster') lyr.datasource = mapnik.Gdal( file='../data/raster/missing_raster.vrt', band=1, ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) _map.layers.append(lyr) # center of extent of raster x, y = 556113.0, 4381428.0 # center of extent of raster _map.zoom_all() # Should RuntimeError here try: _map.query_point(0, x, y).features except RuntimeError, e: eq_( "this_file_should_not_exist.tif' does not exist in the file system" in str(e), True) else: assert False
def __init__(self): BaseWMSFactory.__init__(self) layer = mapnik.Layer('TOP', modis_srs) layer.datasource = mapnik.Gdal(file=str(data),band=1) layer.title = "Modis VI Layer" layer.queryable = True layer.wms_srs = None style = mapnik.Style() rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color("transparent")) scale = getModisScale(product) for color in scale: sym.colorizer.add_stop(color['stop'], mapnik.Color(*color['color'])) rule.symbols.append(sym) style.rules.append(rule) self.register_style('modis_style', style) self.register_layer(layer, "modis_style",("modis_style",)) layer = mapnik.Layer('ocean_mask') layer.datasource = mapnik.Shapefile(file=str("/data/health/data1/web/data/shapes/50m_ocean.shp")) layer.queryable = True layer.wms_srs = None style = mapnik.Style() rule = mapnik.Rule() poly_sym = mapnik.PolygonSymbolizer(mapnik.Color('#50649B')) rule.symbols.append(poly_sym) style.rules.append(rule) self.register_style('mask_style', style) self.register_layer(layer, "mask_style",("mask_style",))
def style_map(self, Map): style = mapnik.Style() rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() sym.opacity = self.opacity colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color('white')) # colorizer.epsilon = 0.001 if self.colormap: for stop in self.colormap: colorizer.add_stop(stop['quantity'], mapnik.Color(stop['color'].encode('ascii'))) sym.colorizer = colorizer rule.symbols.append(sym) style.rules.append(rule) Map.append_style('Raster Style', style) lyr = mapnik.Layer('GDAL Layer from TIFF', self.layer_srs) lyr.datasource = mapnik.Gdal(base=os.path.dirname(self.vrt_path), file=os.path.basename(self.vrt_path), band=self.mapnik_band) lyr.styles.append('Raster Style') Map.layers.append(lyr) return Map
def __init__(self, file, band, nodata): self.file = file self.band = band self.style = self.create_style() self.mapnik_datasource = mapnik.Gdal(file=file, band=band.index, nodata=nodata, shared=True) self.mapnik_layer = self.create_mapnik_layer()
def render(self, input_file, extent, lyr_style): proj4lyr = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' county_file = '../datas/county.shp' # river_file = '../datas/river.shp' # capital_file ='Capital3.json' filename = os.path.split(input_file)[1] areaCode = os.path.splitext(filename)[0] output_file = input_file.split('.')[0] + '.png' print areaCode # ----------create map--------------------- m = mapnik.Map(extent.xsize, extent.ysize) mapnik.load_map(m, 'cg_config.xml') # ----------create layer 1----------------- layer = mapnik.Layer('dataraster', proj4lyr) # ----------create layer 1 datasource------ layer.datasource = mapnik.Gdal(file=input_file, band=1, nodata=-999) layer.styles.append(lyr_style) # ----------append layer 1 to map---------- m.layers.append(layer) # ----------create layer 2----------------- layer2 = mapnik.Layer('county', proj4lyr) # Create new styles and add the rules. s_county = m.find_style('county') r_county = s_county.rules[0] r_county.filter = mapnik.Filter('[CITY]=' + areaCode) m.append_style(areaCode, s_county) # ----------create layer 2 datasource------ layer2.datasource = mapnik.Shapefile(file=county_file) layer2.styles.append(areaCode) # ----------append layer 2 to map---------- m.layers.append(layer2) # ----------create layer 3----------------- layer3 = mapnik.Layer('capital', proj4lyr) # Create new styles and add the rules. s_capital = m.find_style('capital') r_capital = s_capital.rules[0] r_capital.filter = mapnik.Filter('[CITY]=' + areaCode) m.append_style('symbol', s_capital) # ----------create layer 3 datasource------ layer3.datasource = mapnik.Shapefile(file=county_file) layer3.styles.append('symbol') # ----------append layer 3 to map---------- m.layers.append(layer3) ll = mapnik.Coord(extent.xmax, extent.ymax) tr = mapnik.Coord(extent.xmin, extent.ymin) map_bbox = mapnik.Box2d(tr, ll) # mapnik.Envelope(tr, ll) m.zoom_to_box(map_bbox) print m.envelope(), m.scale() mapnik.render_to_file(m, output_file, 'png') return 'true'
def test_dataraster_coloring(): srs = '+init=epsg:32630' lyr = mapnik.Layer('dataraster') if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file='../data/raster/dataraster.tif', band=1, ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) style = mapnik.Style() rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() # Assigning a colorizer to the RasterSymbolizer tells the later # that it should use it to colorize the raw data raster colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.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"), ]: colorizer.add_stop(value, mapnik.Color(color)) sym.colorizer = colorizer 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 = mapnik.Image(_map.width, _map.height) mapnik.render(_map, im) expected_file = './images/support/dataraster_coloring.png' actual_file = '/tmp/' + os.path.basename(expected_file) im.save(actual_file, 'png32') if not os.path.exists(expected_file) or os.environ.get('UPDATE'): im.save(expected_file, 'png32') actual = mapnik.Image.open(actual_file) expected = mapnik.Image.open(expected_file) eq_( actual.tostring('png32'), expected.tostring('png32'), 'failed comparing actual (%s) and expected (%s)' % (actual_file, expected_file))
def as_mapnik_layer(self): """Open the geofile as Mapnik layer.""" # TODO: extract this from raster in advance layer = mapnik.Layer(self.name) layer_path = self._get_raster_path() layer.srs = self.projection # TODO: get this from the upload folder, check layer at that point ? gdal_source = mapnik.Gdal(file=layer_path) layer.datasource = gdal_source layer.queryable = False # layer.minimum_scale_denominator return layer
def test_dataraster_coloring(): srs = '+init=epsg:32630' lyr = mapnik.Layer('dataraster') if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Gdal( file='../data/raster/dataraster.tif', band=1, ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) style = mapnik.Style() rule = mapnik.Rule() sym = mapnik.RasterSymbolizer() # Assigning a colorizer to the RasterSymbolizer tells the later # that it should use it to colorize the raw data raster sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.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, mapnik.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 = mapnik.Image(_map.width, _map.height) mapnik.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 get_map(): if 'BBOX' in request.args: req_bbox = request.args.get('BBOX') else: return "BBOX is required" if 'WIDTH' in request.args: req_width = request.args.get('WIDTH') else: return "WIDTH is required" if 'HEIGHT' in request.args: req_height = request.args.get('HEIGHT') else: return "HEIGHT is required" if 'PATH' in request.args: req_path = request.args.get('PATH') else: return "PATH is required" ret_map = mapnik.Map(int(req_width), int(req_height)) im = mapnik.Image(int(req_width), int(req_height)) layer = mapnik.Layer("requested_lyr") layer.styles.append("requested_lyr") layer.datasource = mapnik.Gdal(file=req_path) ret_map.append_style("requested_lyr", RGB_STYLE) ret_map.layers.append(layer) bbox = (float(i) for i in req_bbox.split(",")) bbox = mapnik.Box2d(next(bbox),next(bbox),next(bbox),next(bbox)) ret_map.zoom_to_box(bbox) mapnik.render(ret_map, im) response = make_response(im.tostring('png')) response.headers.set('Content-Type', 'image/png') return response
def test_raster_with_alpha_blends_correctly_with_background(): WIDTH = 500 HEIGHT = 500 map = mapnik.Map(WIDTH, HEIGHT) WHITE = mapnik.Color(255, 255, 255) map.background = WHITE style = mapnik.Style() rule = mapnik.Rule() symbolizer = mapnik.RasterSymbolizer() #XXX: This fixes it, see http://trac.mapnik.org/ticket/759#comment:3 # (and remove comment when this test passes) #symbolizer.scaling="bilinear_old" rule.symbols.append(symbolizer) style.rules.append(rule) map.append_style('raster_style', style) map_layer = mapnik.Layer('test_layer') filepath = '../data/raster/white-alpha.png' if 'gdal' in mapnik.DatasourceCache.instance().plugin_names(): map_layer.datasource = mapnik.Gdal(file=filepath) map_layer.styles.append('raster_style') map.layers.append(map_layer) map.zoom_all() mim = mapnik.Image(WIDTH, HEIGHT) mapnik.render(map, mim) save_data( 'test_raster_with_alpha_blends_correctly_with_background.png', mim.tostring('png')) imdata = mim.tostring() # All white is expected assert contains_word('\xff\xff\xff\xff', imdata)
def test_vrt_referring_to_missing_files(): srs = '+init=epsg:32630' if 'gdal' in mapnik.DatasourceCache.plugin_names(): lyr = mapnik.Layer('dataraster') lyr.datasource = mapnik.Gdal( file='../data/raster/missing_raster.vrt', band=1, ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) _map.layers.append(lyr) # center of extent of raster x, y = 556113.0, 4381428.0 # center of extent of raster _map.zoom_all() # Fancy stuff to supress output of error # open 2 fds null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)] # save the current file descriptors to a tuple save = os.dup(1), os.dup(2) # put /dev/null fds on 1 and 2 os.dup2(null_fds[0], 1) os.dup2(null_fds[1], 2) # *** run the function *** try: # Should RuntimeError here list(_map.query_point(0, x, y)) finally: # restore file descriptors so I can print the results os.dup2(save[0], 1) os.dup2(save[1], 2) # close the temporary fds os.close(null_fds[0]) os.close(null_fds[1])
def tileRaster(request, version, zoom, x, y): try: if version != "1.0": raise Http404 zoom = int(zoom) x = int(x) y = int(y) if zoom < 0 or zoom > MAX_ZOOM_LEVEL: raise Http404 xExtent = _unitsPerPixel(zoom) yExtent = _unitsPerPixel(zoom) minLong = x * xExtent - 20037508.34 minLat = y * yExtent - 20037508.34 maxLong = minLong + xExtent maxLat = minLat + yExtent if (minLong < -20037508.34 or maxLong > 20037508.34 or minLat < -20037508.34 or maxLat > 20037508.34): raise Http404 #create de mapnik.map object map = mapnik.Map( TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" ) #defining the feature layer datasource = mapnik.Gdal(file="bar_harbour.dem", base="C:\\Temp\\dem\\", band=1) featureLayer = mapnik.Layer("RasterLayer") featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over" featureLayer.datasource = datasource featureLayer.styles.append("RasterLayerStyle") #defining the feature layer styles rule = mapnik.Rule() rule.symbols.append(mapnik.RasterSymbolizer()) style = mapnik.Style() style.rules.append(rule) #add new feature to the map map.append_style("RasterLayerStyle", style) map.layers.append(featureLayer) #rendering the map tile #mapnik.save_map(map, "../tilestache/%s/raster.xml" % str(request.user)) config = { "cache": { "name": "Test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { "raster": { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/layers/raster/raster.xml" % (request.user) }, "projection": "spherical mercator", "metatile": { "rows": 2, "columns": 2, "buffer": 64 }, "write cache": False } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/raster/%s/%s/%s.png" % (zoom, x, y) config = TileStache.Config.buildConfiguration(config) #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png') type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, content_type="image/png") except: traceback.print_exc() return HttpResponse("")
def _add_elevation(m): s = mapnik.Style() r = mapnik.Rule() # rs = mapnik.RasterSymbolizer() # rs.opacity = 1.0 # rs.scaling = 'bilinear' # rs.comp_op = 'multiply' rs = mapnik.RasterSymbolizer() # COLORIZER_DISCRETE is a binned/classified renderer. # Other options are COLORIZER_LINEAR (stretched) and # COLORIZER_EXACT (unique) rs.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(0, 0, 0, 0)) #rs.colorizer.add_stop(0, mapnik.Color(217, 217, 229)) rs.colorizer.add_stop(250, mapnik.Color(58, 130, 72)) rs.colorizer.add_stop(500, mapnik.Color(37, 117, 69)) rs.colorizer.add_stop(1000, mapnik.Color(27, 75, 46)) r.symbols.append(rs) s.rules.append(r) m.append_style('HillShade', s) # old ETOPO5 data from 1988 with poor resolution # https://www.eea.europa.eu/data-and-maps/data/world-digital-elevation-model-etopo5 # ds = mapnik.Gdal( # base = '/Users/larsga/Desktop/DEM_geotiff', # file = 'alwdgg.tif', # band = 1, # ) # srs = '+proj=longlat +ellps=clrk66 +no_defs' # new, huge EU-EDM v1.0 # https://land.copernicus.eu/imagery-in-situ/eu-dem/eu-dem-v1-0-and-derived-products # The x,y-coordinates in the tiles are based on the EPSG:3035 # (ETRS89-LAEA) projection. -> # ds = mapnik.Gdal( # base = '/Users/larsga/Desktop/EUDEM1', # file = 'EUD_CP-DEMS_4500045000-AA.tif', # band = 1, # ) # srs = '+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs' # ETOPO1 # https://www.ngdc.noaa.gov/mgg/global/ ds = mapnik.Gdal( base=SHAPEDIR + '/ETOPO1', file='ETOPO1_Ice_c_geotiff.tif', band=1, ) srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' # ds = mapnik.Gdal( # base = '/Users/larsga/Desktop/DTM50_UTM33_20200904', # file = 'norge.tif', # band = 1, # ) # srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' layer = mapnik.Layer('Elevation') layer.datasource = ds layer.srs = srs layer.styles.append('HillShade') m.layers.append(layer)
variants = ("1A", "1B", "1C", "2C", "2D", "3B", "4A", "5A", "6A") for disease in diseases: for variant in variants: geotiff = "all/results/" + disease + "_" + variant + "/mean_prediction_masked.tif" png = "all/results/" + disease + "_" + variant + "/mean_prediction_masked.png" symbolizer = mapnik.RasterSymbolizer() colorizer = mapnik.RasterColorizer( default_mode=mapnik.COLORIZER_LINEAR, default_color=mapnik.Color("transparent")) symbolizer.colorizer = colorizer colorizer.add_stop(-9999.0, mapnik.Color("#000000")) colorizer.add_stop(0.0, mapnik.Color("#91ab84")) colorizer.add_stop(0.25, mapnik.Color("#c3d4bb")) colorizer.add_stop(0.5, mapnik.Color("#ffffcb")) colorizer.add_stop(0.75, mapnik.Color("#cf93ba")) colorizer.add_stop(1.0, mapnik.Color("#a44883")) colorizer.add_stop(9999.0, mapnik.Color("#eaeaea")) style = mapnik.Style() rule = mapnik.Rule() rule.symbols.append(symbolizer) style.rules.append(rule) layer = mapnik.Layer("raster") layer.datasource = mapnik.Gdal(file=geotiff, nodata=-9999, band=1) layer.styles.append("raster") world = mapnik.Map(1656, 667) world.append_style("raster", style) world.layers.append(layer) world.zoom_all() mapnik.render_to_file(world, png, 'png')
print('=' * 40) print(__file__) from helper.textool import get_tmp_file ################################################################################ import mapnik m = mapnik.Map(600, 500, "+proj=latlong +datum=WGS84") symbol = mapnik.RasterSymbolizer() ################################################################################ s = mapnik.Style() r = mapnik.Rule() r.symbols.append(symbol) s.rules.append(r) m.append_style('My Style', s) datasource = mapnik.Gdal(file='/gdata/geotiff_file.tif') layer = mapnik.Layer("myLayer") layer.datasource = datasource layer.styles.append('My Style') m.layers.append(layer) ################################################################################ layer.envelope() ################################################################################ m.zoom_to_box(layer.envelope()) # mapnik.render_to_file(m, 'xx_mapnik_result.png', 'png') mapnik.render_to_file(m, get_tmp_file(__file__, '1'), 'png') mapnik.render_to_file(m, get_tmp_file(__file__, '1',file_ext='pdf'), 'pdf')
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ############################################################################### import mapnik datasource = mapnik.Gdal(file="/gdata/foo.tif") ############################################################################### ############################################################################### datasource = mapnik.Ogr(file="/gdata/xian.shp", layer="xian") ############################################################################### ############################################################################### ############################################################################### ###############################################################################
s = mapnik.Style() r = mapnik.Rule() raster_symbolizer = mapnik.RasterSymbolizer() raster_symbolizer.colorizer = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR, mapnik.Color("transparent")) raster_symbolizer.colorizer.add_stop(0.0, mapnik.Color("black")) raster_symbolizer.colorizer.add_stop(1.0, mapnik.Color("white")) print -9999, raster_symbolizer.colorizer.get_color(-9999) print 0.0, raster_symbolizer.colorizer.get_color(0.0) print 1.0, raster_symbolizer.colorizer.get_color(1.0) print 0, raster_symbolizer.colorizer.get_color(0) print 1, raster_symbolizer.colorizer.get_color(1) print 0.5, raster_symbolizer.colorizer.get_color(0.5) r.symbols.append(raster_symbolizer) s.rules.append(r) m.append_style('raster_style', s) lyr = mapnik.Layer('urban') lyr.datasource = mapnik.Gdal(base='./', file='urban19901.tif', band=1) lyr.styles.append('raster_style') m.layers.append(lyr) m.zoom_all() mapnik.render_to_file(m, 'test1.png', 'png') print(time.time() - start)
#!/usr/bin/env python import mapnik m = mapnik.Map( 1000, 1000, '+init=epsg:32718') # create a map with a given width and height in pixels # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' # the 'map.srs' is the target projection of the map and can be whatever you wish m.background = mapnik.Color( 'transparent') # set background colour to 'steelblue'. s = mapnik.Style() # style object to hold rules r = mapnik.Rule() # rule object to hold symbolizers landsatDS = mapnik.Gdal(file='L5TM_086S772W_20090628_Classification2009.tif') landsatLyr = mapnik.Layer('Classification', '+init=epsg:32718') landsatLyr.datasource = landsatDS r.symbols.append(mapnik.RasterSymbolizer()) s.rules.append(r) m.append_style('My Style', s) # Styles are given names only as they are applied to the map landsatLyr.styles.append('My Style') m.layers.append(landsatLyr) m.zoom_all() #bbox = mapnik.Envelope(mapnik.Coord(220000.0, 8960000), mapnik.Coord(260000, 9000000))
#!/usr/bin/env python import mapnik m = mapnik.Map(1000,1000, '+init=epsg:32718') # create a map with a given width and height in pixels # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' # the 'map.srs' is the target projection of the map and can be whatever you wish m.background = mapnik.Color('transparent') # set background colour to 'steelblue'. s = mapnik.Style() # style object to hold rules r = mapnik.Rule() # rule object to hold symbolizers landsatDS = mapnik.Gdal(file='L5TM_086S772W_20090628_TOARefl_RGB_Strd.tif') landsatLyr = mapnik.Layer('Landsat', '+init=epsg:32718') landsatLyr.datasource = landsatDS r.symbols.append(mapnik.RasterSymbolizer()) s.rules.append(r) m.append_style('My Style',s) # Styles are given names only as they are applied to the map landsatLyr.styles.append('My Style') m.layers.append(landsatLyr) m.zoom_all() #bbox = mapnik.Envelope(mapnik.Coord(220000.0, 8960000), mapnik.Coord(260000, 9000000)) #m.zoom_to_box(bbox) page = mapnik.printing.PDFPrinter(pagesize=(0.20, 0.20), margin=0.0075, resolution=150, preserve_aspect=True, centering=5, is_latlon=False, use_ocg_layers=True)
def render_static(request, height=None, width=None, format='png', background='satellite', bounds=None, center=None, render_srid=3857): # width and height width = int(width) height = int(height) if width > settings.MAX_IMAGE_DIMENSION or \ height > settings.MAX_IMAGE_DIMENSION or \ width <= 1 or height <= 1: logging.debug("Invalid size") return HttpResponseBadRequest( "Invalid image size, both dimensions must be in range %i-%i" % (1, settings.MAX_IMAGE_DIMENSION)) # image format if format not in IMAGE_FORMATS: logging.error("unknown image format %s" % format) return HttpResponseBadRequest( "Unknown image format, available formats: " + ", ".join(IMAGE_FORMATS)) if format.startswith('png'): mimetype = 'image/png' elif format.startswith('jpeg'): mimetype = 'image/jpeg' # bounds bounds_box = None if bounds: bounds_components = bounds.split(',') if len(bounds_components) != 4: return HttpResponseBadRequest( "Invalid bounds, must be 4 , separated numbers") bounds_components = [float(f) for f in bounds_components] if not (-180 < bounds_components[0] < 180) or not (-180 < bounds_components[2] < 180): logging.error("x out of range %f or %f" % (bounds_components[0], bounds_components[2])) return HttpResponseBadRequest( "x out of range %f or %f" % (bounds_components[0], bounds_components[2])) if not (-90 < bounds_components[1] < 90) or not (-90 < bounds_components[3] < 90): logging.error("y out of range %f or %f" % (bounds_components[1], bounds_components[3])) return HttpResponseBadRequest( "y out of range %f or %f" % (bounds_components[1], bounds_components[3])) ll = Point(bounds_components[0], bounds_components[1], srid=4326) ll.transform(render_srid) ur = Point(bounds_components[2], bounds_components[3], srid=4326) ur.transform(render_srid) bounds_box = mapnik.Box2d(ll.x, ll.y, ur.x, ur.y) elif center: center_components = center.split(',') if len(center_components) != 3: return HttpResponseBadRequest() lon = float(center_components[0]) lat = float(center_components[1]) zoom = int(center_components[2]) # todo calc bounds from center and zoom # baselayer if background not in settings.BASE_LAYERS and background != 'none': return HttpResponseNotFound("Background not found") # GeoJSON post data if request.method == "POST" and len(request.body): input_data = json.loads(request.body) else: input_data = None if not bounds and not center and not input_data: return HttpResponseBadRequest( "Bounds, center, or post data is required.") # initialize map m = mapnik.Map(width, height) m.srs = '+init=epsg:' + str(render_srid) # add a tile source as a background if background != "none": background_file = settings.BASE_LAYERS[background] background_style = mapnik.Style() background_rule = mapnik.Rule() background_rule.symbols.append(mapnik.RasterSymbolizer()) background_style.rules.append(background_rule) m.append_style('background style', background_style) tile_layer = mapnik.Layer('background') tile_layer.srs = '+init=epsg:' + str(render_srid) tile_layer.datasource = mapnik.Gdal(base=settings.BASE_LAYER_DIR, file=background_file) tile_layer.styles.append('background style') m.layers.append(tile_layer) # add features from geojson if input_data and input_data['type'] == "Feature": features = [input_data] elif input_data and input_data['type'] == "FeatureCollection": if 'features' not in input_data: return HttpResponseBadRequest() features = input_data['features'] else: features = [] logging.debug("Adding %d features to map" % len(features)) geometries = [] point_features = [] fid = 0 for feature in features: if 'geometry' not in feature: logging.debug("feature does not have geometry") return HttpResponseBadRequest("Feature does not have a geometry") if 'type' not in feature['geometry']: logging.debug("geometry does not have type") return HttpResponseBadRequest("Geometry does not have a type") fid += 1 style_name = str(fid) if feature['geometry']['type'] == 'Point': point_features.append(feature) elif feature['geometry']['type'] in ('LineString', 'MultiLineString'): if feature['geometry']['type'] == 'LineString': geos_feature = LineString(feature['geometry']['coordinates']) elif feature['geometry']['type'] == 'MultiLineString': rings = feature['geometry']['coordinates'] rings = [[(c[0], c[1]) for c in r] for r in rings] if len(rings) == 1: geos_feature = LineString(rings[0]) else: linestrings = [] for ring in rings: try: linestrings.append(LineString(ring)) except Exception, e: logging.error("Error adding ring: %s", e) geos_feature = MultiLineString(linestrings) geos_feature.srid = 4326 geos_feature.transform(render_srid) geometries.append(geos_feature) style = mapnik.Style() line_rule = mapnik.Rule() style_dict = None if 'style' in feature: style_dict = feature['style'] elif 'properties' in feature: style_dict = feature['properties'] line_rule.symbols.append(line_symbolizer(style_dict)) style.rules.append(line_rule) m.append_style(style_name, style) wkt = geos_feature.wkt line_layer = mapnik.Layer(style_name + ' layer') line_layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"') line_layer.styles.append(style_name) line_layer.srs = '+init=epsg:' + str(render_srid) m.layers.append(line_layer) elif feature['geometry']['type'] == 'Polygon': geos_feature = GEOSGeometry(json.dumps(feature['geometry'])) geos_feature.srid = 4326 geos_feature.transform(render_srid) geometries.append(geos_feature) style = mapnik.Style() rule = mapnik.Rule() style_dict = None if 'style' in feature: style_dict = feature['style'] elif 'properties' in feature: style_dict = feature['properties'] rule.symbols.append(polygon_symbolizer(style_dict)) rule.symbols.append(line_symbolizer(style_dict)) style.rules.append(rule) m.append_style(style_name, style) wkt = geos_feature.wkt layer = mapnik.Layer(style_name + ' layer') layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"') layer.styles.append(style_name) layer.srs = '+init=epsg:' + str(render_srid) m.layers.append(layer)
# Script to draw a topo map with mapnik. import mapnik srs = '+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs' m = mapnik.Map(1200, 1200, srs) m.zoom_to_box(mapnik.Box2d(558800, 5112200, 566600, 5120500)) # Add a GDAL datasource. topo_lyr = mapnik.Layer('Topo', srs) topo_raster = mapnik.Gdal(file=r'D:\osgeopy-data\Washington\dem\st_helens.tif') topo_lyr.datasource = topo_raster # Use a raster symbolizer. topo_sym = mapnik.RasterSymbolizer() topo_rule = mapnik.Rule() topo_rule.symbols.append(topo_sym) topo_style = mapnik.Style() topo_style.rules.append(topo_rule) m.append_style('topo', topo_style) topo_lyr.styles.append('topo') m.layers.append(topo_lyr) mapnik.render_to_file(m, r'd:\temp\helens.png')