Exemple #1
0
def renderMap(m, file, bbox):
    print('Rendering map with dimensions %s, %s' % (m.width, m.height))
    m.zoom_to_box(bbox)

    if mapnik.has_pycairo():
        print('Rendering PDF')

        pdf_surface = cairo.PDFSurface(file, m.width, m.height)
        mapnik.render(m, pdf_surface, 1 / 2.0, 0, 0)
        pdf_surface.finish()

        print('Rendered PDF')

    print('Rendering done')
Exemple #2
0
def test_render_points():
	# Test for effectivenes of ticket #402 (borderline points get lost on reprojection)
	raise Todo("See: http://trac.mapnik.org/ticket/402")
	
	if not mapnik.has_pycairo(): return

	# create and populate point datasource (WGS84 lat-lon coordinates)
	places_ds = mapnik.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 = mapnik.Style()
	r = mapnik.Rule()
	symb = mapnik.PointSymbolizer()
	symb.allow_overlap = True
	r.symbols.append(symb)
	s.rules.append(r)
	lyr = mapnik.Layer('Places','+proj=latlon +datum=WGS84')
	lyr.datasource = places_ds
	lyr.styles.append('places_labels')
	# latlon bounding box corners
	ul_lonlat = mapnik.Coord(142.30,-38.20)
	lr_lonlat = mapnik.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 = mapnik.Map(1000, 500, projs[projdescr])
		m.append_style('places_labels',s)
		m.layers.append(lyr)
		p = mapnik.Projection(projs[projdescr])
		m.zoom_to_box(p.forward(mapnik.Envelope(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)
		mapnik.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)) 
Exemple #3
0
def _pycairo_surface(type,sym):
    if mapnik.has_pycairo():
        import cairo
        test_cairo_file = 'test.%s' % type
        m = mapnik.Map(256,256)
        mapnik.load_map(m,'../data/good_maps/%s_symbolizer.xml' % sym)
        surface = getattr(cairo,'%sSurface' % type.upper())(test_cairo_file, m.width,m.height)
        mapnik.render(m, surface)
        surface.finish()        
        
        if os.path.exists(test_cairo_file):
            os.remove(test_cairo_file)
            return True
        else:
            # Fail, the file wasn't written
            return False
Exemple #4
0
def renderMap(m):
    print 'Rendering map with dimensions %s, %s' % (m.width, m.height)
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)

    # Render cairo examples
    if mapnik.has_pycairo():
        print 'Rendering PDF'

        pdf_surface = cairo.PDFSurface(OUTPUT_PATH + 'slovakia.pdf', m.width, m.height)
        mapnik.render(m, pdf_surface)
        pdf_surface.finish()
        print 'Rendered PDF to %s' % (OUTPUT_PATH + 'slovakia.pdf',)

    print 'Saving map configuration to %s' % (OUTPUT_PATH + "map_slovakia.xml",)
    mapnik.save_map(m, OUTPUT_PATH + "map_slovakia.xml")
Exemple #5
0
def _pycairo_surface(type, sym):
    if mapnik.has_pycairo():
        import cairo
        test_cairo_file = 'test.%s' % type
        m = mapnik.Map(256, 256)
        mapnik.load_map(m, '../data/good_maps/%s_symbolizer.xml' % sym)
        surface = getattr(cairo, '%sSurface' % type.upper())(test_cairo_file,
                                                             m.width, m.height)
        mapnik.render(m, surface)
        surface.finish()

        if os.path.exists(test_cairo_file):
            os.remove(test_cairo_file)
            return True
        else:
            # Fail, the file wasn't written
            return False
def test_renders_with_cairo():
    if not mapnik.has_pycairo():
        return
    sym = mapnik.GlyphSymbolizer("DejaVu Sans Condensed",
                                  mapnik.Expression("'í'"))
    sym.allow_overlap = True
    sym.angle = mapnik.Expression("[azimuth]+90") #+90 so the top of the glyph points upwards
    sym.size = mapnik.Expression("[value]")
    sym.color = mapnik.Expression("'#ff0000'")
    _map = create_map_and_append_symbolyzer(sym)

    from cStringIO import StringIO
    import cairo
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 256, 256)
    mapnik.render(_map, surface)
    im = mapnik.Image.from_cairo(surface)
    save_data('cairo_glyph_symbolizer.png', im.tostring('png'))
    assert contains_word('\xff\x00\x00\xff', im.tostring())
def test_renders_with_cairo():
    if not mapnik.has_pycairo():
        return
    sym = mapnik.GlyphSymbolizer("DejaVu Sans Condensed",
                                 mapnik.Expression("'í'"))
    sym.allow_overlap = True
    sym.angle = mapnik.Expression(
        "[azimuth]+90")  #+90 so the top of the glyph points upwards
    sym.size = mapnik.Expression("[value]")
    sym.color = mapnik.Expression("'#ff0000'")
    _map = create_map_and_append_symbolyzer(sym)
    if _map:
        from cStringIO import StringIO
        import cairo
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 256, 256)
        mapnik.render(_map, surface)
        im = mapnik.Image.from_cairo(surface)
        save_data('cairo_glyph_symbolizer.png', im.tostring('png'))
        assert contains_word('\xff\x00\x00\xff', im.tostring())
Exemple #8
0
    def _render_surface(self, map, map_size):
        if self.format.startswith('image/'):
            # AGG
            f = str(self.format.split('/')[1].lower())
            im = mapnik.Image(*map_size)
            mapnik.render(map, im)
            return im.tostring(f)

        elif self.format in ('application/pdf', 'application/postscript',
                             'text/svg+xml'):
            # CAIRO
            try:
                # first, check if Cairo is available
                import cairo
                # newer Mapniks have better ways of checking whether they were actually
                # compiled with Cairo support
                if hasattr(mapnik, 'has_cairo') and (not mapnik.has_cairo()):
                    raise ImportError
                if hasattr(mapnik,
                           'has_pycairo') and (not mapnik.has_pycairo()):
                    raise ImportError
            except ImportError:
                raise ImportError(
                    "Mapnik wasn't compiled with Cairo support, or Cairo isn't installed."
                )

            surface_file = StringIO()
            if (self.format == 'application/pdf'):
                surface = cairo.PDFSurface(surface_file, *map_size)
            elif (self.format == 'application/postscript'):
                surface = cairo.PSSurface(surface_file, *map_size)
            elif (self.format == 'text/svg+xml'):
                surface = cairo.SVGSurface(surface_file, *map_size)

            mapnik.render(map, surface)
            surface.finish()
            return surface_file.getvalue()

        else:
            raise ValueError("Unknown format: %s" % self.format)
Exemple #9
0
 def _render_surface(self, map, map_size):
     if self.format.startswith('image/'):
         # AGG
         f = str(self.format.split('/')[1].lower())
         im = mapnik.Image(*map_size)
         mapnik.render(map, im)
         return im.tostring(f)
     
     elif self.format in ('application/pdf', 'application/postscript', 'text/svg+xml'):
         # CAIRO
         try:
             # first, check if Cairo is available
             import cairo
             # newer Mapniks have better ways of checking whether they were actually
             # compiled with Cairo support
             if hasattr(mapnik, 'has_cairo') and (not mapnik.has_cairo()):
                 raise ImportError
             if hasattr(mapnik, 'has_pycairo') and (not mapnik.has_pycairo()):
                 raise ImportError
         except ImportError:
             raise ImportError("Mapnik wasn't compiled with Cairo support, or Cairo isn't installed.")
         
         surface_file = StringIO()
         if (self.format == 'application/pdf'):
             surface = cairo.PDFSurface(surface_file, *map_size)
         elif (self.format == 'application/postscript'):
             surface = cairo.PSSurface(surface_file, *map_size)
         elif (self.format == 'text/svg+xml'):
             surface = cairo.SVGSurface(surface_file, *map_size)
         
         mapnik.render(map, surface)
         surface.finish()
         return surface_file.getvalue()
     
     else:
         raise ValueError("Unknown format: %s" % self.format)
Exemple #10
0
    m.layers.append(lyr)
    m.zoom_all()

    im = mapnik.Image(m.width, m.height)
    detector = mapnik.LabelCollisionDetector(m)
    mapnik.render_layer_with_detector(m, im, detector, lyr)

    eq_(im.is_solid(), True)
    c = im.get_pixel(0, 0, True)
    eq_(c.r, 255)
    eq_(c.g, 0)
    eq_(c.b, 0)
    eq_(c.a, 255)


if mapnik.has_pycairo():
    import cairo

    def test_render_layer_to_cairo_surface():
        ds = mapnik.MemoryDatasource()
        context = mapnik.Context()
        context.push('Name')
        f = mapnik.Feature(context, 1)
        f['Name'] = 'poly'
        f.geometry = mapnik.Geometry.from_wkt(
            'POLYGON ((1 1, -1 1, -1 -1, 1 -1, 1 1))')
        ds.add_feature(f)
        s = mapnik.Style()
        r = mapnik.Rule()
        symb = mapnik.PolygonSymbolizer()
        symb.fill = mapnik.Color('red')
Exemple #11
0
    ]
    ctx.set_line_width(inset/2)
    for idx,pt in enumerate(inline):
        if (idx == 0):
          ctx.move_to(*pt)
        else:
          ctx.line_to(*pt)
    ctx.close_path()
    ctx.stroke()

def cairo_color(c):
    """ Return a Cairo color tuple from a Mapnik Color."""
    ctx_c = (c.r/255.0,c.g/255.0,c.b/255.0,c.a/255.0)
    return ctx_c

if mapnik.has_pycairo():
    import cairo

    def test_passing_pycairo_context_svg():
        m = make_tmp_map()
        m.zoom_to_box(mapnik.Box2d(-180,-90,180,90))
        test_cairo_file = '/tmp/mapnik-cairo-context-test.svg'
        surface = cairo.SVGSurface(test_cairo_file, m.width, m.height)
        expected_cairo_file = './images/pycairo/cairo-cairo-expected.svg'
        context = cairo.Context(surface)
        mapnik.render(m,context)
        draw_title(m,context,"Hello Map",size=20)
        draw_neatline(m,context)
        surface.finish()
        if not os.path.exists(expected_cairo_file):
            print 'generated expected cairo surface file %s' % expected_cairo_file
Exemple #12
0
images_.append('demo64_binary_transparency.png')

im.save('demo128_colors_hextree_no_alpha.png', 'png8:c=100:m=h:t=0')
images_.append('demo128_colors_hextree_no_alpha.png')

im.save('demo_high.jpg', 'jpeg100')
images_.append('demo_high.jpg')

im.save('demo_low.jpg', 'jpeg50')
images_.append('demo_low.jpg')

im.save('demo.tif', 'tiff')
images_.append('demo.tif')

# Render cairo examples
if HAS_PYCAIRO_MODULE and mapnik.has_pycairo():

    svg_surface = cairo.SVGSurface('demo.svg', m.width, m.height)
    mapnik.render(m, svg_surface)
    svg_surface.finish()
    images_.append('demo.svg')

    pdf_surface = cairo.PDFSurface('demo.pdf', m.width, m.height)
    mapnik.render(m, pdf_surface)
    images_.append('demo.pdf')
    pdf_surface.finish()

    postscript_surface = cairo.PSSurface('demo.ps', m.width, m.height)
    mapnik.render(m, postscript_surface)
    images_.append('demo.ps')
    postscript_surface.finish()
Exemple #13
0
#!/usr/bin/env python

import os
import mapnik
from nose.tools import *
from utilities import execution_path, run_all

def setup():
    # All of the paths used are relative, if we run the tests
    # from another directory we need to chdir()
    os.chdir(execution_path('.'))

if mapnik.has_pycairo() and 'sqlite' in mapnik.DatasourceCache.plugin_names():

    def _pycairo_surface(type,sym):
            import cairo
            test_cairo_file = '/tmp/test.%s' % type
            m = mapnik.Map(256,256)
            mapnik.load_map(m,'../data/good_maps/%s_symbolizer.xml' % sym)
            if hasattr(cairo,'%sSurface' % type.upper()):
                surface = getattr(cairo,'%sSurface' % type.upper())(test_cairo_file, m.width,m.height)
                mapnik.render(m, surface)
                surface.finish()
                if os.path.exists(test_cairo_file):
                    os.remove(test_cairo_file)
                    return True
                else:
                    # Fail, the file wasn't written
                    return False
            else:
                print 'skipping cairo.%s test since surface is not available' % type.upper()
#images_.append('demo64_binary_transparency.png')
#
#im.save('demo128_colors_hextree_no_alpha.png', 'png8:c=100:m=h:t=0')
#images_.append('demo128_colors_hextree_no_alpha.png')
#
#im.save('demo_high.jpg', 'jpeg100')
#images_.append('demo_high.jpg')
#
#im.save('demo_low.jpg', 'jpeg50')
#images_.append('demo_low.jpg')
#
#im.save('demo.tif', 'tiff')
#images_.append('demo.tif')
#
## Render cairo examples
if HAS_PYCAIRO_MODULE and mapnik.has_pycairo():
 
     svg_surface = cairo.SVGSurface('demo.svg', m.width,m.height)
     mapnik.render(m, svg_surface)
     svg_surface.finish()
     images_.append('demo.svg')
 
#    pdf_surface = cairo.PDFSurface('demo.pdf', m.width,m.height)
#    mapnik.render(m, pdf_surface)
#    images_.append('demo.pdf')
#    pdf_surface.finish()
#
#    postscript_surface = cairo.PSSurface('demo.ps', m.width,m.height)
#    mapnik.render(m, postscript_surface)
#    images_.append('demo.ps')
#    postscript_surface.finish()
Exemple #15
0
#!/usr/bin/env python

import os
import mapnik
from nose.tools import *
from utilities import execution_path, run_all


def setup():
    # All of the paths used are relative, if we run the tests
    # from another directory we need to chdir()
    os.chdir(execution_path('.'))


if mapnik.has_pycairo() and 'sqlite' in mapnik.DatasourceCache.plugin_names():

    def _pycairo_surface(type, sym):
        import cairo
        test_cairo_file = '/tmp/test.%s' % type
        m = mapnik.Map(256, 256)
        mapnik.load_map(m, '../data/good_maps/%s_symbolizer.xml' % sym)
        if hasattr(cairo, '%sSurface' % type.upper()):
            surface = getattr(cairo,
                              '%sSurface' % type.upper())(test_cairo_file,
                                                          m.width, m.height)
            mapnik.render(m, surface)
            surface.finish()
            if os.path.exists(test_cairo_file):
                os.remove(test_cairo_file)
                return True
            else: