def serialize(xml, options): try: try: import mapnik2 as mapnik except ImportError: import mapnik except ImportError: sys.exit(color_text(1, "Error: saving xml requires Mapnik python bindings to be installed")) m = mapnik.Map(1, 1) if options.from_string: mapnik.load_map_from_string(m, xml, True) else: mapnik.load_map(m, xml, True) if options.output: mapnik.save_map(m, options.output) else: if hasattr(mapnik, "mapnik_version") and mapnik.mapnik_version() >= 700: print mapnik.save_map_to_string(m) else: sys.exit( color_text( 1, "Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file", ) )
def test_load_save_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/raster_symbolizer.xml" mapnik2.load_map(map, in_map) out_map = mapnik2.save_map_to_string(map) assert 'RasterSymbolizer' in out_map assert 'RasterColorizer' in out_map assert 'stop' in out_map
def main(root,**options): m = mapnik.Map(1,1) datasource = options.get('datasource') if datasource and datasource.endswith('shp'): shp_dir = os.path.abspath(datasource).split('.shp')[0] name = datasource.split('.shp')[0] datasource = mapnik.Shapefile(file=shp_dir) if srid is not None: m.srs = '+init=epsg:%s' % srid else: srs = proj4_from_osr(shp_dir) if srs: m.srs = srs layers = [] if hasattr(root,'NamedLayer'): layers.extend(root.NamedLayer) if hasattr(root,'UserLayer'): layers.extend(root.UserLayer) for layer in layers: m_layer, styles = ogc_layer_to_mapnik(layer) for (name, style) in styles: m.append_style(name, style) if datasource: m_layer.datasource = datasource m_layer.srs = m.srs m.layers.append(m_layer) 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)
def stream(self): self.initialize() for kml_reference in self.kmls: self.m('handling %s' % kml_reference) kml, tree = self.parse(kml_reference) self.m('found kml: %s' % kml) root = tree.getroot() #self.ogr_ds = ogr.Open(kml) #if not self.ogr_ds and not self.has_network_links: #sys.exit('Sorry this KML is not a valid datasource, there are no layers!') kml_name = self.kml_unique_name(kml) self.collect_layer_style_maps(kml,tree) features = self.get_features(root) #self.collect_feature_styles(kml_name,features) # make sense of stylemapping first #if hasattr(root,'Document') and hasattr(root.Document,'StyleMap'): style_maps,styles = self.get_all_style_data(tree,root) self.collect_style_maps(kml_name,style_maps) self.collect_styles(kml,kml_name,styles) # then collect actual styles #if hasattr(root,'Document') and hasattr(root.Document,'Style'): # self.collect_styles(kml,kml_name,root.Document.Style) # match stylesmaps to styles #if self.style_maps.get(kml_name): # if not self.style_maps[kml_name].get(sty_name): # if not hover... # pass#break self.handle_layers(kml,kml_name,features) if not self.quiet: print mapnik.save_map_to_string(self.map)
def test_load_save_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/raster_symbolizer.xml" try: mapnik2.load_map(map, in_map) out_map = mapnik2.save_map_to_string(map) assert 'RasterSymbolizer' in out_map assert 'RasterColorizer' in out_map assert 'stop' in out_map except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(str(e))
def test_load_save_load_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/glyph_symbolizer.xml" mapnik2.load_map(map, in_map) style = map.find_style('arrows') sym = style.rules[0].symbols[0] assert isinstance(sym, mapnik2.GlyphSymbolizer) assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH out_map = mapnik2.save_map_to_string(map).decode('utf8') map = mapnik2.Map(256,256) mapnik2.load_map_from_string(map, out_map.encode('utf8')) assert 'GlyphSymbolizer' in out_map # make sure non-ascii characters are well supported since most interesting # glyphs for symbology are usually in that range assert u'í' in out_map, out_map
def view_xml(self, m=None): if not self.dock_window: self.dock_window = TextEditor(self) self.iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self.dock_window) if not self.using_mapnik: # http://trac.osgeo.org/qgis/changeset/12955 - render starting signal QObject.connect(self.canvas, SIGNAL("renderComplete(QPainter *)"), self.checkLayers) self.dock_window.show() if self.loaded_mapfile: # if we have loaded a map xml or mml # so lets just display the active file xml = open(self.loaded_mapfile, "rb").read() else: if not m: # regenerate from qgis objects e_c = sync.EasyCanvas(self, self.canvas) m = e_c.to_mapnik() if hasattr(mapnik, "save_map_to_string"): xml = mapnik.save_map_to_string(m) else: (handle, mapfile) = tempfile.mkstemp(".xml", "quantumnik-map-") os.close(handle) mapnik.save_map(m, str(mapfile)) xml = open(mapfile, "rb").read() e = self.canvas.extent() bbox = "%s %s %s %s" % (e.xMinimum(), e.yMinimum(), e.xMaximum(), e.yMaximum()) cmd = "\n<!-- nik2img.py mapnik.xml out.png -d %s %s -e %s -->\n" % ( self.canvas.width(), self.canvas.height(), bbox, ) try: if self.mapnik_map: cmd += "<!-- <MinScaleDenominator>%s</MinScaleDenominator> -->\n" % ( self.mapnik_map.scale_denominator() ) except: pass code = xml + cmd if HIGHLIGHTING: highlighted = highlight(code, XmlLexer(), HtmlFormatter(linenos=False, nowrap=False, full=True)) self.dock_window.textEdit.setHtml(highlighted) else: self.dock_window.textEdit.setText(xml + cmd)
def test_load_save_load_map(): map = mapnik2.Map(256,256) in_map = "../data/good_maps/glyph_symbolizer.xml" try: mapnik2.load_map(map, in_map) style = map.find_style('arrows') sym = style.rules[0].symbols[0] assert isinstance(sym, mapnik2.GlyphSymbolizer) assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH out_map = mapnik2.save_map_to_string(map).decode('utf8') map = mapnik2.Map(256,256) mapnik2.load_map_from_string(map, out_map.encode('utf8')) assert 'GlyphSymbolizer' in out_map # make sure non-ascii characters are well supported since most interesting # glyphs for symbology are usually in that range assert u'í' in out_map, out_map except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(e)
def compare_map(in_map): mapnik2.load_map(map, in_map) (handle, test_map) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map1-') os.close(handle) (handle, test_map2) = tempfile.mkstemp(suffix='.xml', prefix='mapnik-temp-map2-') os.close(handle) if os.path.exists(test_map): os.remove(test_map) mapnik2.save_map(map, test_map) new_map = mapnik2.Map(256, 256) mapnik2.load_map(new_map, test_map) open(test_map2,'w').write(mapnik2.save_map_to_string(new_map)) diff = ' diff %s %s' % (os.path.abspath(test_map),os.path.abspath(test_map2)) try: eq_(open(test_map).read(),open(test_map2).read()) except AssertionError, e: raise AssertionError('serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s' % (in_map,diff))
def 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'): fill = rule.PolygonSymbolizer.Fill m_poly = fill_to_mapnik(fill) 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']) 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)
sty_name = lay+'_shape' m.append_style(sty_name,sty) layer.styles.append(sty_name) if hit: m.layers.append(layer) text_rules = unique_layers[lay]['text_rules'] if len(text_rules): sty = mapnik.Style() sty.filter_mode = mapnik.filter_mode.FIRST for rule in text_rules: # TODO - allow returning whole style for text and casings if catch: if catch in rule.name: sty.rules.append(rule) else: sty.rules.append(rule) if len(sty.rules): hit = True sty_name = lay+'_text' m.append_style(sty_name,sty) text_layer = utils.copy_layer(layer) text_layer.styles.append(sty_name) text_layers.append(text_layer) for lay in text_layers: m.layers.append(lay) print mapnik.save_map_to_string(m)
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)