Example #1
0
def draw_title(m,ctx,text,size=10,color=mapnik.Color('black')):
    """ Draw a Map Title near the top of a page."""
    middle = m.width/2.0
    ctx.set_source_rgba(*cairo_color(color))
    ctx.select_font_face("DejaVu Sans Book", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)
    ctx.set_font_size(size)
    x_bearing, y_bearing, width, height = ctx.text_extents(text)[:4]
    ctx.move_to(middle - width / 2 - x_bearing, 20.0 - height / 2 - y_bearing)
    ctx.show_text(text)
Example #2
0
 def __init__(self, lower_borders):
     self.buckets = []
     self.stats = collections.defaultdict(int)
     for i, l in enumerate(lower_borders):
         p = mapnik.PolygonSymbolizer()
         c = 100.0 - i * 100.0 / len(lower_borders)
         p.fill = mapnik.Color('rgb({}%,0%,0%)'.format(c))
         p.gamma = 0.0
         self.buckets.append((l, p))
Example #3
0
def add_base_style(m):
    # polygon styles
    polygon_symbolizer = mapnik.PolygonSymbolizer()
    polygon_symbolizer.fill = mapnik.Color(poly_fill)

    # line styles
    line_symbolizer = mapnik.LineSymbolizer()
    line_symbolizer.stroke = mapnik.Color(line_color)
    line_symbolizer.stroke_width = line_width

    # append styles
    rule = mapnik.Rule()
    rule.symbols.append(line_symbolizer)
    rule.symbols.append(polygon_symbolizer)
    style = mapnik.Style()
    style.rules.append(rule)
    m.append_style('My Style',style)
    return m
Example #4
0
 def mapnik_style(self):
     import mapnik
     polygon_style = mapnik.Style()
     ps = mapnik.PolygonSymbolizer(mapnik.Color('#551A8B'))
     ps.fill_opacity = 0.9
     ls = mapnik.LineSymbolizer(mapnik.Color('#ffffff'),0.75)
     ls.stroke_opacity = 0.9
     ts = mapnik.TextSymbolizer('name','DejaVu Sans Bold',11,mapnik.Color('#555555'))
     ts.displacement(15,15)
     ts.halo_fill = mapnik.Color('white')
     ts.halo_radius = 1
     ts.opacity = 0.5
     r = mapnik.Rule()
     r.symbols.append(ps)
     r.symbols.append(ls)
     r.symbols.append(ts)
     polygon_style.rules.append(r)
     return polygon_style
Example #5
0
def test_apply_opacity():
    im = mapnik.Image(4, 4)
    im.fill(mapnik.Color(128, 128, 128, 128))
    im.apply_opacity(0.75)
    c = im.get_pixel(0, 0, True)
    eq_(c.r, 128)
    eq_(c.g, 128)
    eq_(c.b, 128)
    eq_(c.a, 96)
def test_stop_label():
    stop = mapnik.ColorizerStop(1, mapnik.COLORIZER_LINEAR,
                                mapnik.Color('red'))
    assert not stop.label
    label = u"32º C"
    if not PYTHON3:
        label = label.encode('utf8')
    stop.label = label
    assert stop.label == label, stop.label
Example #7
0
def tms(z, x, y, service):
    # (4370311.220000, 4911352.860000) - (4403732.650000, 4958349.910000)
    # Extent: (4370177.610000, 4908530.650000) - (4411390.670000, 4958581.500000)
    bbox = dict(minx=4370177, miny=4908530, maxx=4411390, maxy=4958581)

    step = max(bbox['maxx'] - bbox['minx'], bbox['maxy'] - bbox['miny']) / 2**z

    extents = dict()

    extents['tms'] = (bbox['minx'] + x * step, bbox['miny'] + y * step,
                      bbox['minx'] + (x + 1) * step,
                      bbox['miny'] + (y + 1) * step)

    extents['xyz'] = (bbox['minx'] + x * step, bbox['maxy'] - (y + 1) * step,
                      bbox['minx'] + (x + 1) * step, bbox['maxy'] - y * step)

    tile = dict(width=256, height=256)
    map = mapnik.Map(tile['width'], tile['height'])
    map.background = mapnik.Color('steelblue')
    mapnik.load_map(map, 'tile_server/style/styles.xml')
    layer = mapnik.Layer('point')
    ds = mapnik.PostGIS(host='127.0.0.1',
                        dbname='isogd_sevastopol',
                        user='******',
                        password='******',
                        table='tableapi.table_test_2_points_2')
    layer.datasource = ds
    pdb.set_trace()
    style = mapnik.Style()
    rule = mapnik.Rule()
    point_symbolizer = mapnik.PointSymbolizer()
    point_symbolizer.file = "/style/point_style.png"
    # pdb.set_trace()

    rule.symbols.append(point_symbolizer)
    style.rules.append(rule)
    map.append_style('My Style', style)

    map.zoom_all()
    mapnik.render_to_file(map, 'altay.png', 'png')

    box = mapnik.Box2d(*extents.get(service))
    # map.zoom_all()
    map.zoom_to_box(box)
    mapnik.render_to_file(map, 'world.png', 'png')
    im = mapnik.Image(map.width, map.height)
    mapnik.render(map, im)
    output = im.tostring('png')

    # box = mapnik.Box2d(*extents.get(service))
    # map.zoom_to_box(box)
    # mapnik.render_to_file(map, 'world.png', 'png')
    # im = mapnik.Image(map.width, map.height)
    # mapnik.render(map, im)
    # output = im.tostring('png')
    # # Передаём ответ клиенту
    return output
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)
        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)
Example #9
0
def test_render_image_to_string():
    im = mapnik.Image(256, 256)
    im.fill(mapnik.Color('black'))
    eq_(im.painted(), False)
    eq_(im.is_solid(), True)
    s = im.tostring()
    if PYTHON3:
        eq_(s, 256 * 256 * b'\x00\x00\x00\xff')
    else:
        eq_(s, 256 * 256 * '\x00\x00\x00\xff')
Example #10
0
    def to_mapnik(self):
        sym = mapnik.ShieldSymbolizer(
                self.name, 
                self.face_name, 
                self.size or 10, 
                mapnik.Color(str(self.color)) if self.color else mapnik.Color('black'), 
                self.file,
                self.type,
                self.width,
                self.height)

        sym.character_spacing = self.character_spacing or sym.character_spacing
        sym.line_spacing = self.line_spacing or sym.line_spacing
        sym.spacing = self.spacing or sym.line_spacing
        sym.minimum_distance = self.minimum_distance or sym.minimum_distance
        if self.fontset:
            sym.fontset = self.fontset.value
        
        return sym
Example #11
0
def test_render_image_to_string():
    i = mapnik.Image(256, 256)

    i.background = mapnik.Color('black')

    s = i.tostring()

    eq_(s, 256 * 256 * '\x00\x00\x00\xff')

    s = i.tostring('png')
Example #12
0
def test_background_image_and_background_color():
    m = mapnik.Map(8,8)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    m.background_image = '../data/images/stripes_pattern.png'
    im = mapnik.Image(m.width,m.height)
    mapnik.render(m,im)
    # note: data loss due to rounding as per https://github.com/mapnik/mapnik/issues/1519
    # means that background will roundtrip to 253 not 255
    #eq_(get_unique_colors(im),['rgba(255,255,255,128)', 'rgba(74,74,74,255)'])
    eq_(get_unique_colors(im),['rgba(253,253,253,128)', 'rgba(74,74,74,255)'])
Example #13
0
def test_stroke_init():
    s = mapnik.Stroke()

    eq_(s.width, 1)
    eq_(s.opacity, 1)
    eq_(s.color, mapnik.Color('black'))
    eq_(s.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(s.line_join, mapnik.line_join.MITER_JOIN)
    eq_(s.gamma, 1.0)

    s = mapnik.Stroke(mapnik.Color('blue'), 5.0)
    s.gamma = .5

    eq_(s.width, 5)
    eq_(s.opacity, 1)
    eq_(s.color, mapnik.Color('blue'))
    eq_(s.gamma, .5)
    eq_(s.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(s.line_join, mapnik.line_join.MITER_JOIN)
Example #14
0
def test_jpeg_round_trip():
    filepath = '/tmp/mapnik-jpeg-io.jpeg'
    im = mapnik.Image(255, 267)
    im.background = mapnik.Color('rgba(1,2,3,.5)')
    im.save(filepath, 'jpeg')
    im2 = mapnik.Image.open(filepath)
    eq_(im.width(), im2.width())
    eq_(im.height(), im2.height())
    eq_(len(im.tostring()), len(im2.tostring()))
    eq_(len(im.tostring('jpeg')), len(im2.tostring('jpeg')))
Example #15
0
def make_map():
    try:
        import mapnik
    except:
        import mapnik
    m = mapnik.Map(600, 300)
    m.background = mapnik.Color("steelblue")

    s = mapnik.Style()  # style object to hold rules
    r = mapnik.Rule()  # rule object to hold symbolizers
    # to fill a polygon we create a PolygonSymbolizer
    polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
    r.symbols.append(
        polygon_symbolizer)  # add the symbolizer to the rule object
    # to add outlines to a polygon we create a LineSymbolizer
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),
                                            0.1)
    r.symbols.append(line_symbolizer)  # add the symbolizer to the rule object
    s.rules.append(r)  # now add the rule to the style and we're done

    m.append_style(
        'My Style',
        s)  # Styles are given names only as they are applied to the map

    # South Carolina 400 Scale Grid. http://gis.sc.gov/data.html
    ds = mapnik.Shapefile(file='400/400.shp')
    print(ds.envelope())
    # Box2d(1290000.0,70000.0,2750000.0,1240000.0)

    layer = mapnik.Layer(
        'SouthCarolina'
    )  # new layer called 'world' (we could name it anything)
    layer.srs = '+proj=lcc +lat_1=32.5 +lat_2=34.83333333333334 +lat_0=31.83333333333333 +lon_0=-81 +x_0=609600 +y_0=0 +datum=NAD83 +units=ft +no_defs '
    # note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    layer.datasource = ds

    layer.styles.append('My Style')
    m.layers.append(layer)
    m.zoom_all()

    # Write the data to a png image called world.png the current directory
    mapnik.render_to_file(m, 'sc.png', 'png')
Example #16
0
    def test_psql_error_should_give_back_connections_opened_for_lower_layers_to_the_pool():
        map1 = mapnik.Map(600,300)
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.PolygonSymbolizer())
        s.rules.append(r)
        map1.append_style('style',s)

        # This layer will fail after a while
        buggy_s = mapnik.Style()
        buggy_r = mapnik.Rule()
        buggy_r.symbols.append(mapnik.PolygonSymbolizer())
        buggy_r.filter = mapnik.Filter("[fips] = 'FR'")
        buggy_s.rules.append(buggy_r)
        map1.append_style('style for buggy layer',buggy_s)
        buggy_layer = mapnik.Layer('this layer is buggy at runtime')
        # We ensure the query wille be long enough
        buggy_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='(SELECT geom as geom, pg_sleep(0.1), fips::int from world_merc) as failure_tabl',
            max_async_connection=2, max_size=2,asynchronous_request = True, geometry_field='geom')
        buggy_layer.styles.append('style for buggy layer')

        # The query for this layer will be sent, then the previous layer will raise an exception before results are read
        forced_canceled_layer = mapnik.Layer('this layer will be canceled when an exception stops map rendering')
        forced_canceled_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        forced_canceled_layer.styles.append('style')

        map1.layers.append(buggy_layer)
        map1.layers.append(forced_canceled_layer)
        map1.zoom_all()
        map2 = mapnik.Map(600,300)
        map2.background = mapnik.Color('steelblue')
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.LineSymbolizer())
        r.symbols.append(mapnik.LineSymbolizer())
        s.rules.append(r)
        map2.append_style('style',s)
        layer1 = mapnik.Layer('layer1')
        layer1.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        layer1.styles.append('style')
        map2.layers.append(layer1)
        map2.zoom_all()

        # We expect this to trigger a PSQL error
        try:
            mapnik.render_to_file(map1,'/tmp/mapnik-postgis-test-map1.png', 'png')
            # Test must fail if error was not raised just above
            eq_(False,True)
        except RuntimeError:
            pass
        # This used to raise an exception before correction of issue 2042
        mapnik.render_to_file(map2,'/tmp/mapnik-postgis-test-map2.png', 'png')
def test_clearing_image_data():
    im = mapnik.Image(256, 256)
    # make sure it equals itself
    bytes = im.tostring()
    eq_(im.tostring(), bytes)
    # set background, then clear
    im.fill(mapnik.Color('green'))
    eq_(im.tostring() != bytes, True)
    # clear image, should now equal original
    im.clear()
    eq_(im.tostring(), bytes)
Example #18
0
 def draw_neatline(self, width=10, color=mapnik.Color('black')):
     ctx = cairo.Context(self.surface)
     w, h = self.m.width, self.m.height
     map_pts = [[0, 0], [w, 0], [w, h], [0, h]]
     ctx.set_line_width(width)
     ctx.set_source_rgba(*cairo_color(color))
     ctx.move_to(*map_pts[0])
     for pt in map_pts:
         ctx.line_to(*pt)
     ctx.close_path()
     ctx.stroke()
Example #19
0
def test_background_image_with_alpha_and_background_color_against_composited_control(
):
    m = mapnik.Map(10, 10)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    m.background_image = '../data/images/yellow_half_trans.png'
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    # create and composite the expected result
    im1 = mapnik.Image(10, 10)
    im1.background = mapnik.Color('rgba(255,255,255,.5)')
    im1.premultiply()
    im2 = mapnik.Image(10, 10)
    im2.background = mapnik.Color('rgba(255,255,0,.5)')
    im2.premultiply()
    im1.composite(im2)
    im1.demultiply()
    # compare image rendered (compositing in `agg_renderer<T>::setup`)
    # vs image composited via python bindings
    raise Todo("looks like we need to investigate PNG rounding when saving")
    eq_(get_unique_colors(im), get_unique_colors(im1))
Example #20
0
def qs_to_map(qs, styles=[], srs='+init=epsg:900913', buffer_size=128):
    m = mapnik.Map(256, 256, srs)
    if buffer_size:
        m.buffer_size = buffer_size
    m.background = mapnik.Color('transparent')
    adapter = PostgisLayer(qs, styles=styles)
    lyr = adapter.to_mapnik()
    for s in styles:
        m.append_style(s['name'], s['obj'])
    m.layers.append(lyr)
    return m
Example #21
0
def main(imagefilename, xmlfilename):
    m = mapnik.Map(image_width, image_height)
    m.srs = shapefile_projection
    m.background = mapnik.Color('lightgrey')
    style, envelope = build_stylesheet(shapefile, shapefile_projection,
                                       AGS_prefixes)
    mapnik.load_map_from_string(m, style)
    m.zoom_to_box(envelope)
    mapnik.render_to_file(m, imagefilename)
    if xmlfilename:
        mapnik.save_map(m, xmlfilename)
Example #22
0
def test_background():
    im = mapnik.Image(256, 256)
    eq_(im.premultiplied(), False)
    im.fill(mapnik.Color(32, 64, 125, 128))
    eq_(im.premultiplied(), False)
    c = im.get_pixel(0, 0, True)
    eq_(c.get_premultiplied(), False)
    eq_(c.r, 32)
    eq_(c.g, 64)
    eq_(c.b, 125)
    eq_(c.a, 128)
    # Now again with a premultiplied alpha
    im.fill(mapnik.Color(32, 64, 125, 128, True))
    eq_(im.premultiplied(), True)
    c = im.get_pixel(0, 0, True)
    eq_(c.get_premultiplied(), True)
    eq_(c.r, 32)
    eq_(c.g, 64)
    eq_(c.b, 125)
    eq_(c.a, 128)
Example #23
0
 def addGeneralizedToMap(self, name='My New Style'):
     genColor = 'rgb(0%,0%,100%)'
     s = mapnik.Style()
     r = mapnik.Rule()
     if self.symbol_type == 'polygon':
         polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(genColor))
         r.symbols.append(polygon_symbolizer)
     elif self.symbol_type == 'line':
         line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(genColor),2)
         r.symbols.append(line_symbolizer)
     else:
         print self.symbol_type, 'has to be implemented to preview!!!'
     s.rules.append(r)
     self.mapnik_map.append_style(name,s)
     
     lyr = mapnik.Layer('Generalized geometry from PostGIS')
     lyr.datasource = mapnik.PostGIS(host='localhost',user='******',password='******',dbname='meingis',table='(select geom from generalized_line_cache ) as water_ways')
     lyr.srs = self.layerSRS
     lyr.styles.append(name)
     self.mapnik_map.layers.append(lyr)
Example #24
0
 def to_mapnik(self, mmap, dirs=None):
     """
     """
     prev_cwd = getcwd()
     
     if dirs:
         chdir(dirs.output)
     
     try:
         mmap.srs = self.srs or mmap.srs
         if self.background:
             mmap.background = mapnik.Color(str(self.background))
         
         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
             if layer.datasource:
                 lay.datasource = layer.datasource.to_mapnik()
             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)
     
     except:
         # pass it along, but first chdir back to the previous directory
         # in the finally clause below, to put things back the way they were.
         raise
     
     finally:
         chdir(prev_cwd)
Example #25
0
    def addPreviewToMap(self, name):
        #self.datasource[1]
        #self.layerSRS
        #self.symbol_type
        #self.filter
        #self.scaleDenoms

        s = mapnik.Style()
        r = mapnik.Rule()
        prevColor = self.ui.entry_color.get_text()  #'rgb(100%,0%,0%)'
        if self.symbol_type == 'polygon':
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color(prevColor))
            r.symbols.append(polygon_symbolizer)
        elif self.symbol_type == 'line':
            line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(prevColor), 3)
            r.symbols.append(line_symbolizer)
#        elif self.symbol_type == 'text':
#           t = mapnik.TextSymbolizer('FIELD_NAME', 'DejaVu Sans Book', 10, Color('black'))
#          t.halo_fill = Color('white')
#         t.halo_radius = 1
#        t.label_placement = label_placement.LINE_PLACEMENT
#       r.symbols.append(line_symbolizer)
        else:
            print self.symbol_type, 'has to be implemented to preview!!!'
        #print "Filtertest: ",self.filter
        if self.filter != None:
            #f = mapnik.Expression("[waterway] != ''") #'Expression' stands for 'Filter' as this will be replaced in Mapnik3
            r.filter = self.filter  #f
            r.min_scale = self.scaleDenoms[0]
            r.max_scale = self.scaleDenoms[1]
        s.rules.append(r)

        proof = self.mapnik_map.append_style(name, s)
        #print 'Style appending worked!?: ',proof
        #ds = mapnik.Shapefile(file='/home/klammer/Software/Quickly/TileGen/tilegen/data/media/testdaten/mercator_polygon/lines-vgtl-27-01-12.shp')
        layer = mapnik.Layer('world')
        layer.datasource = self.datasource[1]  #ds
        layer.srs = self.layerSRS  #self.mapnik_map.srs
        layer.styles.append(name)
        self.mapnik_map.layers.append(layer)
Example #26
0
def qickTest():

    m = mapnik.Map(600, 300)
    m.background = mapnik.Color('steelblue')
    s = mapnik.Style()
    r = mapnik.Rule()
    #polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#ff00ff'))
    #r.symbols.append(polygon_symbolizer)

    line_symbolizer = mapnik.LineSymbolizer(
        mapnik.Color('rgb(100%,100%,100%)'), 0.1)
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My Style', s)
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(100%,0%,100%)'),
                                            0.5)
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My New Style', s)
    ds = mapnik.Shapefile(
        file=
        '/home/klammer/Software/Quickly/TileGen/tilegen/data/media/testdaten/mercator_polygon/lines-vgtl-27-01-12.shp'
    )
    layer = mapnik.Layer('world')
    layer.datasource = ds
    layer.styles.append('My Style')
    m.layers.append(layer)

    lyr = mapnik.Layer('Generalized geometry from PostGIS')
    lyr.datasource = mapnik.PostGIS(host='localhost',
                                    user='******',
                                    password='******',
                                    dbname='meingis',
                                    table='generalized_line_cache')
    lyr.srs = layer.srs
    lyr.styles.append('My New Style')
    m.layers.append(lyr)

    m.zoom_all()
    mapnik.render_to_file(m, 'world.png', 'png')
    print "rendered image to 'world.png'"
Example #27
0
def mapnik_plot(shp_file):
    m = mapnik.Map(600, 300)
    m.background = mapnik.Color('steelblue')
    s = mapnik.Style()
    r = mapnik.Rule()
    # polygon_symbolizer = mapnik.PolygonSymbolizer()
    # polygon_symbolizer.fill = mapnik.Color('#f2eff9')
    # r.symbols.append(polygon_symbolizer)

    line_symbolizer = mapnik.LineSymbolizer()
    line_symbolizer.stroke = mapnik.Color('rgb(100%,100%,100%)')
    line_symbolizer.stroke_width = 3.0
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My Style', s)
    ds = mapnik.Shapefile(file=shp_file)
    layer = mapnik.Layer('world')
    layer.datasource = ds
    layer.styles.append('My Style')
    m.layers.append(layer)
    m.zoom_all()
Example #28
0
def do_encoding():

    image = None
    iterations = 10

    results = {}
    sortable = {}

    def run(func, im, format, t):
        global image
        image = im
        start = time.time()
        set = t.repeat(iterations,1)
        elapsed = (time.time() - start)
        min_ = min(set)*1000
        avg = (sum(set)/len(set))*1000
        name = func.__name__ + ' ' + format
        results[name] = [avg,min_,elapsed*1000,name]
        sortable[name] = [avg]

    def blank():
        eval('image.tostring("%s")' % c)
    blank_im = mapnik.Image(512,512)

    for c in combinations:
        t = Timer(blank)
        run(blank,blank_im,c,t)

    def solid():
        eval('image.tostring("%s")' % c)
    solid_im = mapnik.Image(512,512)
    solid_im.background = mapnik.Color("#f2efe9")

    for c in combinations:
        t = Timer(solid)
        run(solid,solid_im,c,t)

    def many_colors():
        eval('image.tostring("%s")' % c)
    # lots of colors: http://tile.osm.org/13/4194/2747.png
    many_colors_im = mapnik.Image.open('../data/images/13_4194_2747.png')

    for c in combinations:
        t = Timer(many_colors)
        run(many_colors,many_colors_im,c,t)

    for key, value in sorted(sortable.iteritems(), key=lambda (k,v): (v,k)):
        s = results[key]
        avg = str(s[0])[:6]
        min_ = str(s[1])[:6]
        elapsed = str(s[2])[:6]
        name = s[3]
        print 'avg: %sms | min: %sms | total: %sms <-- %s' % (min_,avg,elapsed,name)
Example #29
0
    def add_style_level(self, s, percent):
        color = "#{}".format(self.c1000_rainbow.colourAt(percent))
        width_multiplier = self.get_width_multiplier(self.zoom)

        # unpaved
        r = mapnik.Rule()
        r.filter = mapnik.Filter(self.filter_condition(False, percent))
        ls = mapnik.LineSymbolizer()
        ls.stroke = mapnik.Color(color)
        ls.stroke_width = 0.1 * width_multiplier
        r.symbols.append(ls)
        s.rules.append(r)

        #paved
        r = mapnik.Rule()
        r.filter = mapnik.Filter(self.filter_condition(True, percent))
        ls = mapnik.LineSymbolizer()
        ls.stroke = mapnik.Color(color)
        ls.stroke_width = 1 * width_multiplier
        r.symbols.append(ls)
        s.rules.append(r)
Example #30
0
 def mapnik_style(self):
     try:
         import mapnik
     except:
         import mapnik2 as mapnik
     line_style = mapnik.Style()
     ls = mapnik.LineSymbolizer(mapnik.Color('#444444'), 1.5)
     ls.stroke_opacity = 0.5
     r = mapnik.Rule()
     r.symbols.append(ls)
     line_style.rules.append(r)
     return line_style