def ogc_rule_to_mapnik(rule): m_rule = mapnik.Rule(str(getattr(rule, 'Name', ''))) ogc_filter = rule.find("{%s}Filter" % rule.nsmap['ogc']) if ogc_filter is not None: m_rule.filter = ogc_filter_to_mapnik(ogc_filter) else: if hasattr(rule, 'ElseFilter'): m_rule.set_else(True) if hasattr(rule, 'MaxScaleDenominator'): m_rule.max_scale = float(rule.MaxScaleDenominator) if hasattr(rule, 'MinScaleDenominator'): m_rule.min_scale = float(rule.MinScaleDenominator) syms = [] for possible_sym in rule.iterchildren(): if 'Symbolizer' in possible_sym.tag: translator = get_translator(possible_sym) if translator: syms.extend(translator(possible_sym)) else: log.warn("Could not translate symbolizer '%s'", possible_sym.tag) for sym in syms: m_rule.symbols.append(sym) return m_rule
def create_grid_map(width,height): places_ds = mapnik2.PointDatasource() places_ds.add_point(143.10,-38.60,'Name','South East') places_ds.add_point(142.48,-38.60,'Name','South West') places_ds.add_point(142.48,-38.38,'Name','North West') places_ds.add_point(143.10,-38.38,'Name','North East') s = mapnik2.Style() r = mapnik2.Rule() #symb = mapnik2.PointSymbolizer() symb = mapnik2.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) label = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'), 'DejaVu Sans Book', 10, mapnik2.Color('black') ) label.allow_overlap = True label.displacement = (0,-10) #r.symbols.append(label) s.rules.append(r) lyr = mapnik2.Layer('Places') lyr.datasource = places_ds lyr.styles.append('places_labels') m = mapnik2.Map(width,height) m.append_style('places_labels',s) m.layers.append(lyr) return m
def add_gpx_style(self, gpx_style): """Adds mapnik style for styling GPX track This is blue 40% transparent 4 width line. Parameters --------- gpx_style : str Name of the style layer Note ---- This doesn't work for some reason. Style is added and if mapnik XML is saved and read it is used. """ self._lazy_init_map() style = mapnik.Style() style.filter_mode = mapnik.filter_mode.FIRST rule = mapnik.Rule() line_symbolizer = mapnik.LineSymbolizer() line_symbolizer.stroke = mapnik.Color('rgb(0%,0%,100%)') line_symbolizer.stroke_width = 4 line_symbolizer.stroke_opacity = 0.4 #line_symbolizer.simplify = 0.1 rule.symbols.append(line_symbolizer) style.rules.append(rule) self.m.append_style(gpx_style, style) print("Making style")
def test_render_grid(): places_ds = mapnik2.PointDatasource() places_ds.add_point(143.10, -38.60, 'Name', 'South East') places_ds.add_point(142.48, -38.60, 'Name', 'South West') places_ds.add_point(142.48, -38.38, 'Name', 'North West') places_ds.add_point(143.10, -38.38, 'Name', 'North East') s = mapnik2.Style() r = mapnik2.Rule() #symb = mapnik2.PointSymbolizer() symb = mapnik2.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) label = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'), 'DejaVu Sans Book', 10, mapnik2.Color('black')) label.allow_overlap = True label.displacement = (0, -10) #r.symbols.append(label) s.rules.append(r) lyr = mapnik2.Layer('Places') lyr.datasource = places_ds lyr.styles.append('places_labels') m = mapnik2.Map(256, 256) m.append_style('places_labels', s) m.layers.append(lyr) ul_lonlat = mapnik2.Coord(142.30, -38.20) lr_lonlat = mapnik2.Coord(143.40, -38.80) m.zoom_to_box(mapnik2.Box2d(ul_lonlat, lr_lonlat)) grid = mapnik2.render_grid(m, 0, key='Name', resolution=4, fields=['Name']) eq_(grid, grid_correct) eq_(resolve(grid, 0, 0), None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid, 23, 9), expected) eq_(resolve(grid, 23, 10), expected) eq_(resolve(grid, 23, 11), expected) # core eq_(resolve(grid, 24, 8), expected) eq_(resolve(grid, 24, 9), expected) eq_(resolve(grid, 24, 10), expected) eq_(resolve(grid, 24, 11), expected) eq_(resolve(grid, 24, 12), expected) eq_(resolve(grid, 25, 8), expected) eq_(resolve(grid, 25, 9), expected) eq_(resolve(grid, 25, 10), expected) eq_(resolve(grid, 25, 11), expected) eq_(resolve(grid, 25, 12), expected) # bottom row eq_(resolve(grid, 26, 9), expected) eq_(resolve(grid, 26, 10), expected) eq_(resolve(grid, 26, 11), expected)
def test_introspect_symbolizers(): # create a symbolizer p = mapnik2.PointSymbolizer( mapnik2.PathExpression("../data/images/dummy.png")) p.allow_overlap = True p.opacity = 0.5 eq_(p.allow_overlap, True) eq_(p.opacity, 0.5) eq_(p.filename, '../data/images/dummy.png') # make sure the defaults # are what we think they are eq_(p.allow_overlap, True) eq_(p.opacity, 0.5) eq_(p.filename, '../data/images/dummy.png') # contruct objects to hold it r = mapnik2.Rule() r.symbols.append(p) s = mapnik2.Style() s.rules.append(r) m = mapnik2.Map(0, 0) m.append_style('s', s) # try to figure out what is # in the map and make sure # style is there and the same s2 = m.find_style('s') rules = s2.rules eq_(len(rules), 1) r2 = rules[0] syms = r2.symbols eq_(len(syms), 1) ## TODO here, we can do... sym = syms[0] # this is hackish at best p2 = sym.symbol() assert isinstance(p2, mapnik2.PointSymbolizer) eq_(p2.allow_overlap, True) eq_(p2.opacity, 0.5) eq_(p2.filename, '../data/images/dummy.png') ## but we need to be able to do: p2 = syms[0] # get the actual symbolizer, not the variant object # this will throw for now... assert isinstance(p2, mapnik2.PointSymbolizer) eq_(p2.allow_overlap, True) eq_(p2.opacity, 0.5) eq_(p2.filename, '../data/images/dummy.png')
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 generate_mapnik_style(self, user_id, global_id): style = mapnik.Style() for color in self.load_colors(user_id, global_id): c = mapnik.Color(str(color)) line = mapnik.LineSymbolizer(c, 1.5) line.stroke.opacity = 0.7 poly = mapnik.PolygonSymbolizer(c) poly.fill_opacity = 0.5 rule = mapnik.Rule() rule.filter = mapnik.Filter(str("[color] = '%s'" % (color,))) rule.symbols.extend([poly,line]) style.rules.append(rule) return style
def test_rule_init(): min_scale = 5 max_scale = 10 r = mapnik2.Rule() eq_(r.name, '') eq_(r.title, '') eq_(r.min_scale, 0) eq_(r.max_scale, float('inf')) r = mapnik2.Rule("Name") eq_(r.name, 'Name') eq_(r.title, '') eq_(r.min_scale, 0) eq_(r.max_scale, float('inf')) r = mapnik2.Rule("Name", "Title") eq_(r.name, 'Name') eq_(r.title, 'Title') eq_(r.min_scale, 0) eq_(r.max_scale, float('inf')) r = mapnik2.Rule("Name", "Title", min_scale) eq_(r.name, 'Name') eq_(r.title, 'Title') eq_(r.min_scale, min_scale) eq_(r.max_scale, float('inf')) r = mapnik2.Rule("Name", "Title", min_scale, max_scale) eq_(r.name, 'Name') eq_(r.title, 'Title') eq_(r.min_scale, min_scale) eq_(r.max_scale, max_scale)
def test_render_points(): if not mapnik2.has_cairo(): 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' } 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 svg_file = '/tmp/%s.svg' mapnik2.render_to_file(m, svg_file) num_points_present = len(places_ds.all_features()) svg = open(svg_file, 'r').read() 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 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 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 create_map_and_append_symbolyzer(sym): srs = '+init=epsg:32630' lyr = mapnik2.Layer('arrows') lyr.datasource = mapnik2.Shapefile(file='../data/shp/arrows.shp', ) lyr.srs = srs _map = mapnik2.Map(256, 256, srs) style = mapnik2.Style() rule = mapnik2.Rule() rule.symbols.append(sym) # put a test symbolizer to see what is the azimuth being read ts = mapnik2.TextSymbolizer(mapnik2.Expression('[azimuth]'), "DejaVu Sans Book", 10, mapnik2.Color("black")) ts.allow_overlap = True rule.symbols.append(ts) style.rules.append(rule) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(mapnik2.Box2d(0, 0, 8, 8)) return _map
def to_mapnik(self, mmap): """ """ mmap.srs = self.srs or mmap.srs mmap.bgcolor = str(self.bgcolor) or mmap.bgcolor ids = (i for i in xrange(1, 999999)) for layer in self.layers: for style in layer.styles: sty = mapnik.Style() for rule in style.rules: rul = mapnik.Rule('rule %d' % ids.next()) rul.filter = rule.filter and mapnik.Filter( rule.filter.text) or rul.filter rul.min_scale = rule.minscale and rule.minscale.value or rul.min_scale rul.max_scale = rule.maxscale and rule.maxscale.value or rul.max_scale for symbolizer in rule.symbolizers: if not hasattr(symbolizer, 'to_mapnik'): continue sym = symbolizer.to_mapnik() rul.symbols.append(sym) sty.rules.append(rul) mmap.append_style(style.name, sty) lay = mapnik.Layer(layer.name) lay.srs = layer.srs or lay.srs lay.minzoom = layer.minzoom or lay.minzoom lay.maxzoom = layer.maxzoom or lay.maxzoom for style in layer.styles: lay.styles.append(style.name) mmap.layers.append(lay)
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 test_raster_with_alpha_blends_correctly_with_background(): WIDTH = 500 HEIGHT = 500 map = mapnik2.Map(WIDTH, HEIGHT) WHITE = mapnik2.Color(255, 255, 255) map.background = WHITE style = mapnik2.Style() rule = mapnik2.Rule() symbolizer = mapnik2.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 = mapnik2.Layer('test_layer') filepath = '../data/raster/white-alpha.png' map_layer.datasource = mapnik2.Gdal(file=filepath) map_layer.styles.append('raster_style') map.layers.append(map_layer) map.zoom_all() mim = mapnik2.Image(WIDTH, HEIGHT) mapnik2.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)
# Project bounds to map projection e = mapnik2.forward_(bbox, prj) # Zoom map to bounding box m.zoom_to_box(e) ### ### START Layer 1 ### # style object to hold rules s = mapnik2.Style() s2 = mapnik2.Style() # rule object to hold symbolizers r = mapnik2.Rule() r2 = mapnik2.Rule() # Lines (outlines of polygons and/or simple lines. Line-Color (RGB) line-thickness polygon_symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color('#ec0000')) polygon_symbolizer.fill_opacity = 0.5 polygon_symbolizer2 = mapnik2.PolygonSymbolizer(mapnik2.Color('#00d200')) polygon_symbolizer2.fill_opacity = 0.5 # add the polygon_symbolizer to the rule object r.symbols.append(polygon_symbolizer) r2.symbols.append(polygon_symbolizer2) # now add the rule(s) to the style s.rules.append(r)
def mapnik_rendering(f_pct,f_vct,f_render): import mapnik2 as mapnik ref_pct = GR.geo_raster.open(f_pct) proj = ref_pct.projection tr = ref_pct.geo_transform width = ref_pct.width height = ref_pct.height size_p = tr[1] minx = tr[0] maxy = tr[3] miny = tr[3] - height * size_p maxx = tr[0] + width * size_p bbox = (minx, miny, maxx, maxy) #---- init _map = mapnik.Map(width,height) _map.background = mapnik.Color('black') #----==== raster style_gdal = mapnik.Style() # style object to hold rules rule_gdal = mapnik.Rule() # rule object to hold symbolizers symbol_gdal = mapnik.RasterSymbolizer() #symbol_gdal.opacity = 0.5 #$symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(255,255,255)) c = mapnik.RasterColorizer( mapnik.COLORIZER_LINEAR , mapnik.Color(0,0,0) ) c.epsilon = 0.001 c.add_stop(0) c.add_stop(900, mapnik.COLORIZER_LINEAR, mapnik.Color("#F3DDB4")) c.add_stop(1300, mapnik.COLORIZER_LINEAR, mapnik.Color("cyan")) c.add_stop(2000, mapnik.COLORIZER_LINEAR, mapnik.Color("white")) #c.get_color(2000) #c.stops[1].color #''' symbol_gdal.colorizer = c rule_gdal.symbols.append(symbol_gdal) style_gdal.rules.append(rule_gdal) _map.append_style("Raster Style", style_gdal) mlyr_gdal = mapnik.Layer('TM_images') mlyr_gdal.datasource = mapnik.Gdal(file=f_pct,band=1,bbox=bbox) #mlyr_gdal.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs ' mlyr_gdal.styles.append('Raster Style') _map.layers.append(mlyr_gdal) #''' #----==== shape style_vct = mapnik.Style() # style object to hold rules rule_vct = mapnik.Rule() # rule object to hold symbolizers #==== ==== add labels symbol_text = mapnik.TextSymbolizer(mapnik.Expression('[Code_uniq]'), 'DejaVu Sans Book', 20, mapnik.Color('black')) symbol_text.halo_fill = mapnik.Color('white') symbol_text.halo_radius = 1 symbol_text.avoid_edges = True #symbol_text.allow_overlap = False symbol_text.vertical_alignment = mapnik.vertical_alignment.TOP symbol_text.label_placement = mapnik.label_placement.POINT_PLACEMENT #LINE_PLACEMENT # is default rule_vct.symbols.append(symbol_text) #==== ==== 1.add polygon symbol_vct = mapnik.PolygonSymbolizer(mapnik.Color('#059BFF')) symbol_vct.opacity = 1#0.6 rule_vct.symbols.append(symbol_vct) # add the symbolizer to the rule object #==== ==== 2.add outlines line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('black'),0.3) rule_vct.symbols.append(line_symbolizer) # add the symbolizer to the rule object style_vct.rules.append(rule_vct) # now add the rule to the style and we're done _map.append_style('vector',style_vct) # Styles are given names only as they are applied to the map ds_shp = mapnik.Shapefile(file=f_vct) mlyr_shp = mapnik.Layer('lakes') mlyr_shp.datasource = ds_shp mlyr_shp.styles.append('vector') _map.layers.append(mlyr_shp) #''' _map.zoom_all() # Write the data to a png image called world.png the current directory mapnik.render_to_file(_map,f_render, 'png') print f_render
def mapnik_rendering(f_pct, f_vct, f_render): import mapnik2 as mapnik ref_pct = GR.geo_raster.open(f_pct) proj = ref_pct.projection tr = ref_pct.geo_transform width = ref_pct.width height = ref_pct.height size_p = tr[1] minx = tr[0] maxy = tr[3] miny = tr[3] - height * size_p maxx = tr[0] + width * size_p bbox = (minx, miny, maxx, maxy) #---- init _map = mapnik.Map(width, height) _map.background = mapnik.Color('black') #''' #----==== shape style_vct = mapnik.Style() # style object to hold rules rule_vct = mapnik.Rule() # rule object to hold symbolizers symbol_vct = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9')) symbol_vct.opacity = 0.8 rule_vct.symbols.append( symbol_vct) # add the symbolizer to the rule object line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'), 0.1) rule_vct.symbols.append( line_symbolizer) # add the symbolizer to the rule object style_vct.rules.append( rule_vct) # now add the rule to the style and we're done _map.append_style( 'vector', style_vct ) # Styles are given names only as they are applied to the map ds_shp = mapnik.Shapefile(file=f_vct) mlyr_shp = mapnik.Layer('lakes') mlyr_shp.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs ' mlyr_shp.datasource = ds_shp mlyr_shp.styles.append('vector') _map.layers.append(mlyr_shp) #''' #----==== raster style_gdal = mapnik.Style() # style object to hold rules rule_gdal = mapnik.Rule() # rule object to hold symbolizers symbol_gdal = mapnik.RasterSymbolizer() #symbol_gdal.mode = 'multiply' symbol_gdal.opacity = 0.5 #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255)) c = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color(255, 0, 0)) c.epsilon = 0.001 c.add_stop(0) c.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("red")) c.get_color(255) c.stops[1].color #''' symbol_gdal.colorizer = c rule_gdal.symbols.append(symbol_gdal) style_gdal.rules.append(rule_gdal) _map.append_style("Raster Style", style_gdal) mlyr_gdal = mapnik.Layer('TM_images') mlyr_gdal.datasource = mapnik.Gdal(file=f_pct, band=1, bbox=bbox) mlyr_gdal.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs ' mlyr_gdal.styles.append('Raster Style') _map.layers.append(mlyr_gdal) #==== style_gdal1 = mapnik.Style() # style object to hold rules rule_gdal1 = mapnik.Rule() # rule object to hold symbolizers symbol_gdal1 = mapnik.RasterSymbolizer() #symbol_gdal.mode = 'multiply' symbol_gdal1.opacity = 0.5 #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255)) c1 = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color(0, 255, 0)) c1.epsilon = 0.001 c1.add_stop(0) c1.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("green")) c1.get_color(255) c1.stops[1].color #''' symbol_gdal1.colorizer = c1 rule_gdal1.symbols.append(symbol_gdal1) style_gdal1.rules.append(rule_gdal1) _map.append_style("Raster Style2", style_gdal1) mlyr_gdal1 = mapnik.Layer('TM_images2') mlyr_gdal1.datasource = mapnik.Gdal(file=f_pct, band=2, bbox=bbox) mlyr_gdal1.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs ' mlyr_gdal1.styles.append('Raster Style2') _map.layers.append(mlyr_gdal1) #==== #==== style_gdal_b = mapnik.Style() # style object to hold rules rule_gdal_b = mapnik.Rule() # rule object to hold symbolizers symbol_gdal_b = mapnik.RasterSymbolizer() #symbol_gdal.mode = 'multiply' symbol_gdal_b.opacity = 0.5 #symbol_gdal.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_INHERIT, mapnik.Color(0,255,255)) c_b = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color(0, 0, 255)) c_b.epsilon = 0.001 c_b.add_stop(0) c_b.add_stop(255, mapnik.COLORIZER_LINEAR, mapnik.Color("blue")) c_b.get_color(255) c_b.stops[1].color #''' symbol_gdal_b.colorizer = c_b rule_gdal_b.symbols.append(symbol_gdal_b) style_gdal_b.rules.append(rule_gdal_b) _map.append_style("Raster Style3", style_gdal_b) mlyr_gdal_b = mapnik.Layer('TM_images3') mlyr_gdal_b.datasource = mapnik.Gdal(file=f_pct, band=3, bbox=bbox) mlyr_gdal_b.srs = '+proj=utm +zone=46 +ellps=WGS84 +units=m +no_defs ' mlyr_gdal_b.styles.append('Raster Style3') _map.layers.append(mlyr_gdal_b) #==== _map.zoom_all() # Write the data to a png image called world.png the current directory mapnik.render_to_file(_map, f_render, 'png')
# You can use 'named' colours, #rrggbb, #rgb or rgb(r%,g%,b%) format m.background = mapnik2.Color('steelblue') # Now lets create a style and add it to the Map. s = mapnik2.Style() # A Style can have one or more rules. A rule consists of a filter, min/max scale # demoninators and 1..N Symbolizers. If you don't specify filter and scale denominators # you get default values : # Filter = 'ALL' filter (meaning symbolizer(s) will be applied to all features) # MinScaleDenominator = 0 # MaxScaleDenominator = INF # Lets keep things simple and use default value, but to create a map we # we still must provide at least one Symbolizer. Here we want to fill countries polygons with # greyish colour and draw outlines with a bit darker stroke. r = mapnik2.Rule() r.symbols.append(mapnik2.PolygonSymbolizer(mapnik2.Color('#f2eff9'))) r.symbols.append(mapnik2.LineSymbolizer(mapnik2.Color('rgb(50%,50%,50%)'), 0.1)) s.rules.append(r) # Here we have to add our style to the Map, giving it a name. m.append_style('My Style', s) # Here we instantiate our data layer, first by giving it a name and srs (proj4 projections string), and then by giving it a datasource. lyr = mapnik2.Layer('world', "+proj=latlong +datum=WGS84") # Then provide the full filesystem path to a shapefile in WGS84 or EPSG 4326 projection without the .shp extension # A sample shapefile can be downloaded from http://mapnik-utils.googlecode.com/svn/data/world_borders.zip lyr.datasource = mapnik2.Shapefile( file='/home/garel/geodata/vecteur/world/ne_110m_admin_0_countries.shp') lyr.styles.append('My Style')
#!/usr/bin/env python import mapnik2 as mapnik m = mapnik.Map(6000,3000,"+proj=latlong +datum=WGS84") m.background = mapnik.Color('steelblue') s = mapnik.Style() r=mapnik.Rule() r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)) s.rules.append(r) m.append_style('My Style',s) lyr = mapnik.Layer('world',"+proj=latlong +datum=WGS84") lyr.datasource = mapnik.Shapefile(file='/opt/gdata/world_borders.shp') lyr.styles.append('My Style') m.layers.append(lyr) m.zoom_to_box(lyr.envelope()) mapnik.render_to_file(m,'world.png', 'png')
def main(root,**options): m = mapnik.Map(1,1) idx = 0 layers = [] if hasattr(root,'NamedLayer'): layers.extend(root.NamedLayer) if hasattr(root,'UserLayer'): layers.extend(root.UserLayer) for layer in layers: lyr = mapnik.Layer(str(getattr(layer,'Name',None) or 'Layer')) datasource = options.get('datasource') if datasource and datasource.endswith('shp'): shp_dir = os.path.abspath(datasource).split('.shp')[0] name = datasource.split('.shp')[0] lyr.datasource = mapnik.Shapefile(file=shp_dir) if options.get('srid'): lyr.srs = '+init=epsg:%s' % options.get('srid') m.srs = lyr.srs else: srs = proj4_from_osr(shp_dir) if srs: lyr.srs = srs for user_style in layer.UserStyle: for feature_style in user_style.FeatureTypeStyle: m_sty = mapnik.Style() # TODO = Styles should have title,abstract, etc... sty_name = getattr(feature_style,'Name',None) if not sty_name: sty_name = '%s %s' % (lyr.name,str(idx)) sty_name = str(sty_name) for rule in feature_style.Rule: #print rule.get_childen() m_rule = mapnik.Rule(str(getattr(rule,'Name',''))) ogc_filter = rule.find("{%s}Filter" % rule.nsmap['ogc']) if ogc_filter is not None: # TODO - support ogc:And and oc:Or m_rule.filter = ogc_filter_to_mapnik(ogc_filter) else: if hasattr(rule,'ElseFilter'): m_rule.set_else(True) if hasattr(rule,'MaxScaleDenominator'): m_rule.max_scale = float(rule.MaxScaleDenominator) if hasattr(rule,'MinScaleDenominator'): m_rule.min_scale = float(rule.MinScaleDenominator) if hasattr(rule,'LineSymbolizer'): stroke = rule.LineSymbolizer.Stroke m_stroke = stroke_to_mapnik(stroke) m_rule.symbols.append(mapnik.LineSymbolizer(m_stroke)) if hasattr(rule,'PolygonSymbolizer'): m_poly = mapnik.PolygonSymbolizer() if hasattr(rule.PolygonSymbolizer,'Fill'): fill = rule.PolygonSymbolizer.Fill for css in fill.CssParameter: if css.get('name') == 'fill': m_poly.fill = mapnik.Color(css.text) elif css.get('name') == 'fill-opacity': m_poly.opacity = float(css.text) else: raise Exception('unhanded: ' + css.get('name')) if hasattr(rule.PolygonSymbolizer,'Stroke'): stroke = rule.PolygonSymbolizer.Stroke m_stroke = stroke_to_mapnik(stroke) m_rule.symbols.append(mapnik.LineSymbolizer(m_stroke)) m_rule.symbols.append(m_poly) if hasattr(rule,'PointSymbolizer'): #fill = rule.PolygonSymbolizer.Fill #m_point = point_to_mapnik(point) # TODO m_rule.symbols.append(mapnik.PointSymbolizer()) if hasattr(rule,'TextSymbolizer'): text = rule.TextSymbolizer name = text.Label.find("{%s}PropertyName" % rule.nsmap['ogc']) if not name and hasattr(text,'Label'): name = shlex.split(str(text.Label))[0] face_name = '[%s]' % text.Font face_name = 'DejaVu Sans Book' size = 10 for css in text.Font.CssParameter: if css.get('name') == 'font-family': face_name = css.text elif css.get('name') == 'font-size': size = int(float(css.text)) color = mapnik.Color('black') for css in text.Fill.CssParameter: if css.get('name') == 'fill': color = mapnik.Color(css.text) m_text = mapnik.TextSymbolizer(mapnik.Expression('['+str(name)+']'),str(face_name),int(size),color) if hasattr(text,'LabelPlacement'): if hasattr(text.LabelPlacement,'LinePlacement'): m_text.label_placement = mapnik.label_placement.LINE_PLACEMENT if hasattr(text,'Halo'): h = text.Halo if hasattr(h,'Radius'): m_text.halo_radius = float(h.Radius) if hasattr(h,'Fill'): for css in h.Fill.CssParameter: if css.get('name') == 'fill': m_text.halo_fill = mapnik.Color(css.text) m_rule.symbols.append(m_text) m_sty.rules.append(m_rule) lyr.styles.append(sty_name) m.append_style(sty_name,m_sty) idx+= 1 m.layers.append(lyr) if FIX_HEX: (handle, path) = tempfile.mkstemp(suffix='.xml', prefix='geotools2mapnik-') os.close(handle) open(path,'w').write(mapnik.save_map_to_string(m)) tree = objectify.parse(path) fix_colors(tree) print etree.tostring(tree)#,pretty_print=True) else: print mapnik.save_map_to_string(m)
# uses mapnik 2 import mapnik2 symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color("darkgrey")) rule = mapnik2.Rule() rule.symbols.append(symbolizer) style = mapnik2.Style() style.rules.append(rule) layer = mapnik2.Layer("mapLayer") layer.datasource = mapnik2.Shapefile( file="/data/82945364-10m-admin-0-countries.shp") layer.styles.append("mapStyle") map = mapnik2.Map(2400, 1200) map.background = mapnik2.Color("black") map.append_style("mapStyle", style) map.layers.append(layer) map.zoom_all() mapnik2.render_to_file(map, "map.png", "png")
encoding='latin1') # We then define a style for the layer. A layer can have one or many styles. # Styles are named, so they can be shared across different layers. # Multiple styles per layer behaves functionally like multiple layers. The # data is completely re-scanned for each style within one layer, and a style # will be drawn entirely "above" the previous one. Performance wise using # multiple styles in one layer is the same has having multiple layers. # The paradigm is useful mostly as a convenience. provpoly_style = mapnik2.Style() # A Style needs one or more rules. A rule will normally consist of a filter # for feature selection, and one or more symbolizers. provpoly_rule_on = mapnik2.Rule() # A Expression() allows the selection of features to which the symbology will # be applied. More on Mapnik expressions can be found in Tutorial #2. # A given feature can only match one filter per rule per style. provpoly_rule_on.filter = mapnik2.Expression("[NAME_EN] = 'Ontario'") # Here a symbolizer is defined. Available are: # - LineSymbolizer(Color(),<width>) # - LineSymbolizer(Stroke()) # - PolygonSymbolizer(Color()) # - PointSymbolizer(<file>,<type>,<width>,<height>) # Some of them can accept a Color() instance, which can be created with: # - Color(<red>, <green>, <blue>)