def serialize(xml, options): try: import mapnik2 as mapnik except: try: import mapnik except: 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 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 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 test_gen_map(): mapxmlfile = '../data/good_maps/raster_colorizer.xml' mapxmloutputfile = 'raster_colorizer_test_save.xml' outputfile = 'raster_colorizer_test.png' m = mapnik2.Map(800, 600) mapnik2.load_map(m, mapxmlfile) mapnik2.save_map(m, mapxmloutputfile) m.zoom_all() mapnik2.render_to_file(m, outputfile)
def test_gen_map(): mapxmlfile = '../data/good_maps/raster_colorizer.xml' mapxmloutputfile = 'raster_colorizer_test_save.xml' outputfile = 'raster_colorizer_test.png' m = mapnik2.Map(800, 600) try: mapnik2.load_map(m, mapxmlfile) mapnik2.save_map(m, mapxmloutputfile) m.zoom_all() mapnik2.render_to_file(m, outputfile) except RuntimeError,e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(str(e))
def get_paired_images(w,h,mapfile): tmp_map = 'tmp_map.xml' m = mapnik2.Map(w,h) mapnik2.load_map(m,mapfile) i = mapnik2.Image(w,h) m.zoom_all() mapnik2.render(m,i) mapnik2.save_map(m,tmp_map) m2 = mapnik2.Map(w,h) mapnik2.load_map(m2,tmp_map) i2 = mapnik2.Image(w,h) m2.zoom_all() mapnik2.render(m2,i2) os.remove(tmp_map) return i,i2
def get_paired_images(w, h, mapfile): tmp_map = 'tmp_map.xml' m = mapnik2.Map(w, h) mapnik2.load_map(m, mapfile) i = mapnik2.Image(w, h) m.zoom_all() mapnik2.render(m, i) mapnik2.save_map(m, tmp_map) m2 = mapnik2.Map(w, h) mapnik2.load_map(m2, tmp_map) i2 = mapnik2.Image(w, h) m2.zoom_all() mapnik2.render(m2, i2) os.remove(tmp_map) return i, i2
def save_xml(self): # need to expose as an option! relative_paths = True mapfile = QFileDialog.getSaveFileName(None, "Save file dialog", "mapnik.xml", "Mapfile (*.xml)") if mapfile: e_c = sync.EasyCanvas(self, self.canvas) mapfile_ = str(mapfile) base_path = os.path.dirname(mapfile_) e_c.base_path = base_path m = e_c.to_mapnik() mapnik.save_map(m, mapfile_) if relative_paths: relativism.fix_paths(mapfile_, base_path)
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 save_xml(self): # need to expose as an option! relative_paths = True mapfile = QFileDialog.getSaveFileName(None, "Save file dialog", 'mapnik.xml', "Mapfile (*.xml)") if mapfile: e_c = sync.EasyCanvas(self, self.canvas) mapfile_ = str(mapfile) base_path = os.path.dirname(mapfile_) e_c.base_path = base_path m = e_c.to_mapnik() mapnik.save_map(m, mapfile_) if relative_paths: relativism.fix_paths(mapfile_, base_path)
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 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))
postscript_surface = cairo.PSSurface('demo.ps', m.width,m.height) mapnik2.render(m, postscript_surface) images_.append('demo.ps') postscript_surface.finish() else: print '\n\nPycairo not available...', if mapnik2.has_cairo(): print ' will render Cairo formats using alternative method' mapnik2.render_to_file(m,'demo.pdf') images_.append('demo.pdf') mapnik2.render_to_file(m,'demo.ps') images_.append('demo.ps') mapnik2.render_to_file(m,'demo.svg') images_.append('demo.svg') mapnik2.render_to_file(m,'demo_cairo_rgb.png','RGB24') images_.append('demo_cairo_rgb.png') mapnik2.render_to_file(m,'demo_cairo_argb.png','ARGB32') images_.append('demo_cairo_argb.png') print "\n\n", len(images_), "maps have been rendered in the current directory:" for im_ in images_: print "-", im_ print "\n\nHave a look!\n\n" mapnik2.save_map(m,"map.xml")
postscript_surface = cairo.PSSurface('demo.ps', m.width, m.height) mapnik2.render(m, postscript_surface) images_.append('demo.ps') postscript_surface.finish() else: print '\n\nPycairo not available...', if mapnik2.has_cairo(): print ' will render Cairo formats using alternative method' mapnik2.render_to_file(m, 'demo.pdf') images_.append('demo.pdf') mapnik2.render_to_file(m, 'demo.ps') images_.append('demo.ps') mapnik2.render_to_file(m, 'demo.svg') images_.append('demo.svg') mapnik2.render_to_file(m, 'demo_cairo_rgb.png', 'RGB24') images_.append('demo_cairo_rgb.png') mapnik2.render_to_file(m, 'demo_cairo_argb.png', 'ARGB32') images_.append('demo_cairo_argb.png') print "\n\n", len(images_), "maps have been rendered in the current directory:" for im_ in images_: print "-", im_ print "\n\nHave a look!\n\n" mapnik2.save_map(m, "map.xml")
def createMapnikXML(jobCfg,sysCfg): ''' Modifies the base mapnik xml style sheet to add layers for the grid, hillshading and contour lines as requested by the user in the jobCfg object.''' print "createMapnikXML" print "Imported settings as:\n%s\n" % (sysCfg.__str__()) print "Imported Mapspec as:\n%s\n" % (jobCfg.__str__()) jobNo = jobCfg['jobNo'] projection = jobCfg['projection'] lat = float(jobCfg['origin']['lat']) lon = float(jobCfg['origin']['lon']) scale = float(jobCfg['mapScale']) paper = jobCfg['paper']['size'] if 'resolution' in jobCfg: img_dpi = float(jobCfg['resolution']) else: img_dpi = 300 styleFname = str(jobCfg['baseMapnikStyleFile']) outputFname = str("%s/%s" % \ (jobCfg['jobDir'],"mapnikStyle.xml")) jobCfg['mapnikStyleFile']=outputFname print "jobNo = %d." % (jobNo) print "origin = (%f,%f)." % (lon,lat) print "scale = %f." % (scale) print "paper = %s." % (paper) (imgw,imgh) = getPaperSize(jobCfg['paper']) print "(imgw,imgh) = (%f,%f)." % (imgw,imgh) projStr = getProjStr(jobCfg['projection']); print "projStr = %s" % projStr ###################################################### # Calculate map Bounding Box (in degrees and metres) # ###################################################### prj = mapnik.Projection(projStr) # Convert origin (centre) to metres as c_origin c_origin = prj.forward(mapnik.Coord(lon,lat)) # calculate top right in metres given image size and map scale. mapw = scale*imgw/100. # width of map representation in metres. maph = scale*imgw/100. # height of map representation in metres. # c0 = bottom left corner position in metres. c0 = mapnik.Coord(c_origin.x - mapw/2.0, c_origin.y - maph/2.0) # c1 = top right corner position in metres. c1 = mapnik.Coord(c_origin.x + mapw/2.0, c_origin.y + maph/2.0) print c0,c1 # Calculate the image size based on the required physical width and # height, and the requested resolution (img_dpi). #mapnik_scale_factor = img_dpi / 90.7 mapnik_scale_factor = 1.0 imgx = int(imgw * 72 / 2.54) # size in points (72nds of an inch). imgy = int(imgh * 72 / 2.54) # ~ print "generating map...." m = mapnik.Map(imgx,imgy) mapnik.load_map(m,styleFname) if (jobCfg['hillshade']): ###################################### # First get list of all the hillshade # files in the job directory hillshadeFiles = [] for file in os.listdir(jobCfg['jobDir']): if fnmatch.fnmatch(file,'*.hillshade.tiff'): print "found hillshade file %s\n" % file hillshadeFiles.append(file) if len(hillshadeFiles) == 0: print "*******ERROR - NO HILLSHADE FILES *****" print "* Will carry on anyway..." ############################################# # Now add a mapnik style for the hillshading style = mapnik.Style() rule = mapnik.Rule() rs = mapnik.RasterSymbolizer() rs.opacity=0.5 rule.symbols.append(rs) style.rules.append(rule) m.append_style('hillshade',style) ############################################ # And a layer for each hillshade file i=0 for file in hillshadeFiles: lyr = mapnik.Layer('hillshade-%d' % i) lyr.srs="+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m" hillshadeFile="%s/%s" % (jobCfg['jobDir'],file) print "hillshadeFile=%s" % (hillshadeFile) ds = mapnik.Gdal(base=jobCfg['jobDir'],file=hillshadeFile.encode('utf-8')) ds.opacity = 0.5 lyr.datasource = ds lyr.styles.append('hillshade') # m.layers.append(lyr) m.layers[7:7]=lyr i = i+1 if (jobCfg['contours']): ###################################### # First get list of all the contours # files in the job directory contourFiles = [] for file in os.listdir(jobCfg['jobDir']): if fnmatch.fnmatch(file,'*.contours.shp'): print "found contours file %s\n" % file contourFiles.append(file) if len(contourFiles) == 0: print "*******ERROR - NO CONTOUR FILES *****" print "* Will carry on anyway..." ############################################# # Now add a mapnik style for the contours style = mapnik.Style() rule = mapnik.Rule() contourlines = mapnik.LineSymbolizer(mapnik.Color('green'),0.1) rule.symbols.append(contourlines) style.rules.append(rule) m.append_style('contours',style) ############################################ # And a layer for each hillshade file i = 0 for file in contourFiles: contourFile="%s/%s" % (jobCfg['jobDir'],file) print "contourFile=%s\n" % contourFile lyr = mapnik.Layer('contours-%d' % i) lyr.datasource = mapnik.Shapefile(file=contourFile.encode('utf-8')) lyr.styles.append('contours') #m.layers.append(lyr) m.layers[8:8]=lyr i = i + 1 if (jobCfg['grid']): style = mapnik.Style() rule = mapnik.Rule() gridlines = mapnik.LineSymbolizer(mapnik.Color('white'),0.1) rule.symbols.append(gridlines) style.rules.append(rule) m.append_style('grid',style) gridFile="%s/%s" % (jobCfg['jobDir'],'grid.shp') print "gridFile=%s\n" % gridFile lyr = mapnik.Layer('grid') lyr.srs = "+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m" lyr.datasource = mapnik.Shapefile(file=gridFile.encode('utf-8')) lyr.styles.append('grid') m.layers.append(lyr) i = 0 for lyr in m.layers: print i,lyr.name i=i+1 mapnik.save_map(m,outputFname)