Exemplo n.º 1
0
def createisomap(iso, mapscale, name, name_en):

    map_width = int(mapscale[0])
    map_height = int(mapscale[1])

    map_minx = float(mapscale[2])
    map_maxx = float(mapscale[3])
    map_miny = float(mapscale[4])
    map_maxy = float(mapscale[5])

    print("mapdata:", map_width, map_height, map_maxx, map_maxy, map_minx,
          map_miny)

    geojsonfile = '/osm/service/' + CONTINENT + '/' + iso + '/poly/osm.geojson'

    m = mapnik.Map(
        map_width,
        map_height)  # create a map with a given width and height in pixels
    # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    # the 'map.srs' is the target projection of the map and can be whatever you wish
    m.background = mapnik.Color(
        '#000000')  # set background colour to '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

    psymbolizer = mapnik.PolygonSymbolizer()
    #psymbolizer.fill = mapnik.Color('#f2eff9')
    psymbolizer.fill = mapnik.Color('#000000')
    r.symbols.append(psymbolizer)

    lsymbolizer = mapnik.LineSymbolizer()
    #lsymbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
    lsymbolizer.stroke = mapnik.Color('#FFA500')
    lsymbolizer.stroke_width = 0.8
    r.symbols.append(lsymbolizer)

    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

    ds = mapnik.Ogr(file=geojsonfile, layer_by_index=0)
    print(ds)

    ds.envelope()

    layer = mapnik.Layer(
        'world')  # new layer called 'world' (we could name it anything)
    # 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)

    bbox = mapnik.Box2d(map_maxx, map_maxy, map_minx, map_miny)
    m.zoom_to_box(bbox)

    # Write the data to a png image called world.png the current directory

    img_directory = '/osm/service/' + CONTINENT + '/' + iso + '/img/'
    if not os.path.exists(img_directory):
        os.makedirs(img_directory)

    os.system("rm -f " + img_directory + "*")

    mapnik.render_to_file(m, img_directory + 'dbackground0.png', 'png')

    gdalw1 = 'gdalwarp    -te {} {} {} {}  -ts {} {} '.format(
        map_minx, map_miny, map_maxx, map_maxy, map_width, map_height)
    # NE1_HR_LC_SR_W_DR.tif
    gdalw2 = ' -of GTiff   /osm/ne/ne.tif {}  '.format(img_directory +
                                                       'nebackground.geotif')

    print("gdalw:", gdalw1, gdalw2)

    os.system(gdalw1 + gdalw2)

    os.system('gdal_translate -of PNG  {} {} '.format(
        img_directory + 'nebackground.geotif',
        img_directory + 'nebackground.png'))

    os.system('convert   {} -transparent Black {} '.format(
        img_directory + 'dbackground0.png',
        img_directory + 'tdbackground.png'))
    os.system('composite {} -compose over   {} {} '.format(
        img_directory + 'tdbackground.png', img_directory + 'nebackground.png',
        img_directory + 'dbackground.png'))

    ######################  flag ##################################

    im_cmd1 = r'convert /osm/setup/osmlogo.png -font DejaVu-Serif -fill darkblue  -pointsize 34 -gravity center -draw "text 16,-18'
    im_cmd2 = r" '." + iso[:2] + "' "
    im_cmd3 = r'"  ' + img_directory + 'dflag.png'

    os.system(im_cmd1 + im_cmd2 + im_cmd3)

    ####################  Logo #####################################

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 448, 98)
    ctx = cairo.Context(surface)
    ctx.select_font_face("Courier", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)

    ctx.set_font_size(42)
    ctx.move_to(2, 50)
    ctx.set_source_rgb(0.0, 0.0, 0.15)
    ctx.show_text('Taginfo-' + CONTINENT + '-' + iso)

    ctx.select_font_face('Sans')
    if len(name_en) > 26:
        ctx.set_font_size(20)
    elif len(name_en) > 18:
        ctx.set_font_size(26)
    else:
        ctx.set_font_size(30)

    ctx.move_to(1, 90)
    ctx.set_source_rgb(0.0, 0.0, 0.35)
    ctx.show_text(name_en)

    # finish up
    ctx.stroke()
    surface.write_to_png(img_directory + 'dlogo.png')
Exemplo n.º 2
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
###############################################################################
import mapnik

map = mapnik.Map(600, 400)
###############################################################################
map.srs
###############################################################################
style1, style2, style3 = [mapnik.Style()] * 3
map.append_style("s1", style1)
map.append_style("s2", style2)
map.append_style("s3", style1)
map.append_style("s1", style3)
###############################################################################
layer = mapnik.Layer('lyrname')
layer.srs
###############################################################################
ds = mapnik.Shapefile(file='/gdata/GSHHS_c.shp')
layer.datasource = ds
layer.styles.append("s1")
layer.styles.append("s2")
###############################################################################
map.layers.append(layer)
Exemplo n.º 3
0
# Script to create an xml file to describe the National Atlas
# hydrography layer.

import mapnik

m = mapnik.Map(0, 0)

water_rule = mapnik.Rule()
water_rule.filter = mapnik.Expression("[Feature]='Canal' or [Feature]='Lake'")
water_rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color(165, 191,
                                                                221)))

marsh_rule = mapnik.Rule()
marsh_rule.filter = mapnik.Expression("[Feature]='Swamp or Marsh'")
marsh_color = mapnik.Color('#66AA66')
marsh_rule.symbols.append(mapnik.PolygonSymbolizer(marsh_color))
marsh_rule.symbols.append(mapnik.LineSymbolizer(marsh_color, 2))

atlas_style = mapnik.Style()
atlas_style.rules.append(water_rule)
atlas_style.rules.append(marsh_rule)
m.append_style('atlas', atlas_style)

lyr = mapnik.Layer('National Atlas Hydro',
                   "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
lyr.datasource = mapnik.Shapefile(file=r'D:\osgeopy-data\US\wtrbdyp010')
lyr.styles.append('atlas')
m.layers.append(lyr)

mapnik.save_map(m, r'D:\osgeopy-data\US\national_atlas_hydro.xml')
Exemplo n.º 4
0
m.zoom_to_box(mapnik.Box2d(-90.3, 29.7, -89.5, 30.3))

# Create a layer from a shapefile.
tiger_fn = r'D:\osgeopy-data\Louisiana\tiger_la_water_CENSUS_2006'
tiger_shp = mapnik.Shapefile(file=tiger_fn)
tiger_lyr = mapnik.Layer('Tiger')
tiger_lyr.datasource = tiger_shp

# Create a polygon fill symbol.
water_color = mapnik.Color(165, 191, 221)
water_fill_sym = mapnik.PolygonSymbolizer(water_color)

# Create a symbology style and add it to the layer.
tiger_rule = mapnik.Rule()
tiger_rule.symbols.append(water_fill_sym)
tiger_style = mapnik.Style()
tiger_style.rules.append(tiger_rule)
m.append_style('tiger', tiger_style)

# Add the style and layer to the map.
tiger_lyr.styles.append('tiger')

# Comment out this line to get the layers in the right order.
m.layers.append(tiger_lyr)

#####################  Here's the new stuff.

atlas_lyr = mapnik.Layer('National Atlas')
atlas_shp = mapnik.Shapefile(file=r'D:\osgeopy-data\US\wtrbdyp010')
atlas_lyr.datasource = atlas_shp
Exemplo n.º 5
0
def getMapImage(osmFile, map_output):
    '''Uses the data from the osmFile to out a .png image
       of the area depicted by the input file'''

    if not HAS_MAPNIK:
        print('Error: Mapnik module is missing. ' +
              'Please install for getting the image functionality.')
        return -2

    if osmFile == '':
        print 'Error: getMapImage::No File Recieved'
        return -1

    highwaList = dict({
        "motorway": {
            'width': 4,
            'color': 'green',
            'fontSize': 12
        },
        "trunk": {
            'width': 3,
            'color': 'green',
            'fontSize': 11
        },
        "primary": {
            'width': 1.5,
            'color': '#0090ff',
            'fontSize': 10
        },
        "secondary": {
            'width': 0.8,
            'color': '#ff00ff',
            'fontSize': 8
        },
        "tertiary": {
            'width': 0.42,
            'color': '#000000',
            'fontSize': 8
        },
        "residential": {
            'width': 0.21,
            'color': 'black',
            'fontSize': 8
        },
        "living_street": {
            'width': 0.21,
            'color': 'black',
            'fontSize': 8
        },
        "pedestrian": {
            'width': 0.21,
            'color': 'brown',
            'fontSize': 8
        },
        "footway": {
            'width': 0.21,
            'color': 'brown',
            'fontSize': 8
        }
    })

    m = mapnik.Map(1024, 1024)
    m.background = mapnik.Color('white')

    for highwayType in highwaList.keys():
        styleType = mapnik.Style()

        rule = mapnik.Rule()

        rule.filter = mapnik.Expression('[highway]=' + "'" + highwayType + "'")

        stk = mapnik.Stroke()
        stk.color = mapnik.Color(highwaList[highwayType]['color'])
        stk.line_cap = mapnik.line_cap.ROUND_CAP
        stk.width = highwaList[highwayType]['width']

        line_symbolizer = mapnik.LineSymbolizer(stk)

        rule.symbols.append(line_symbolizer)

        rule2 = mapnik.Rule()

        rule2.filter = mapnik.Expression('[highway]=' + "'" + highwayType +
                                         "'")

        text_symbolizer = mapnik.TextSymbolizer(
            mapnik.Expression("[name]"), "DejaVu Sans Book",
            highwaList[highwayType]['fontSize'], mapnik.Color('black'))
        text_symbolizer.halo_fill = mapnik.Color('white')

        rule2.symbols.append(text_symbolizer)

        styleType.rules.append(rule)
        styleType.rules.append(rule2)

        m.append_style(highwayType, styleType)

    ds = mapnik.Osm(file=osmFile)

    layer = mapnik.Layer('world')
    layer.datasource = ds
    for highwayType in highwaList.keys():
        layer.styles.append(highwayType)

    m.layers.append(layer)
    m.zoom_all()
    mapnik.render_to_file(m, map_output, 'png')

    return os.system('xdg-open ' + map_output)
Exemplo n.º 6
0
provpoly_lyr = mapnik.Layer('Provinces')
provpoly_lyr.srs = "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"
provpoly_lyr.datasource = mapnik.Shapefile(file=path.join(
    root, '../data/boundaries'),
                                           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 = mapnik.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 = mapnik.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 = mapnik.Expression("[NAME_EN] = 'Ontario'")

# Here a symbolizer is defined.  Available are:
#     - LineSymbolizer(Color(),<width>)
#     - LineSymbolizer(Stroke())
Exemplo n.º 7
0
 def mapnik_style(self):
     """
     Mapnik style object containing rules for symbolizing features in staticmap
     """
     style = mapnik.Style()
     return style
Exemplo n.º 8
0
#!/usr/bin/python3
#coding:utf8
# [email protected]

# map有两层,一层里定义polygon、line的样式,用于画各个国家边界线
# 另一层里只定义了线的样式,用于画两国公共边界,红色的
import mapnik
# 第一部分,创建地图,指定地图底色
m = mapnik.Map(500, 1000)
m.background = mapnik.Color('#8080a0')

# 第二部分,画地图,此时是全世界所有国家均有
# 定义画显示出的所有国家的边界线,黑色的边界线
# 也定义各个国家内部填色steelblue
# 这些放在layer层
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer()
polygon_symbolizer.fill = mapnik.Color('steelblue')
r.symbols.append(polygon_symbolizer)

line_symbolizer = mapnik.LineSymbolizer()
line_symbolizer.stroke = mapnik.Color('black')
line_symbolizer.stroke_width = 0.5
r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style('My Style', s)
# 全世界所有国家的shp文件
ds = mapnik.Shapefile(file='./tm/TM_WORLD_BORDERS-0.3.shp')
layer = mapnik.Layer('world')
layer.datasource = ds
Exemplo n.º 9
0
 def _test_data_subquery(lbl, pixtype, value):
   #
   #      3   8   13
   #    +---+---+---+
   #  3 | v | v | v |  NOTE: writes different values
   #    +---+---+---+        in 13,8 and 8,13
   #  8 | v | v | a |  
   #    +---+---+---+  
   # 13 | v | b | v |
   #    +---+---+---+
   #
   val_a = value/3;
   val_b = val_a*2;
   sql = "(select 3 as i, " \
         " ST_SetValues(" \
         "  ST_SetValues(" \
         "   ST_AsRaster(" \
         "    ST_MakeEnvelope(0,0,14,14), " \
         "    1.0, -1.0, '%s', %s" \
         "   ), " \
         "   11, 6, 5, 5, %s::float8" \
         "  )," \
         "  6, 11, 5, 5, %s::float8" \
         " ) as \"R\"" \
         ") as foo" % (pixtype,value, val_a, val_b)
   overview = ''
   rescale = 0
   clip = 0
   if rescale:
     lbl += ' Sc'
   if clip:
     lbl += ' Cl'
   ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=sql,
     raster_field='R', use_overviews=0 if overview else 0,
     band=1, prescale_rasters=rescale, clip_rasters=clip)
   fs = ds.featureset()
   feature = fs.next()
   eq_(feature['i'],3)
   lyr = mapnik.Layer('data_subquery')
   lyr.datasource = ds
   expenv = mapnik.Box2d(0,0,14,14)
   env = lyr.envelope()
   assert_almost_equal(env.minx, expenv.minx, places=0)
   assert_almost_equal(env.miny, expenv.miny, places=0)
   assert_almost_equal(env.maxx, expenv.maxx, places=0)
   assert_almost_equal(env.maxy, expenv.maxy, places=0)
   mm = mapnik.Map(15, 15)
   style = mapnik.Style()
   col = mapnik.RasterColorizer();
   col.default_mode = mapnik.COLORIZER_DISCRETE;
   col.add_stop(val_a, mapnik.Color(0xff,0x00,0x00,255));
   col.add_stop(val_b, mapnik.Color(0x00,0xff,0x00,255));
   col.add_stop(value, mapnik.Color(0x00,0x00,0xff,255));
   sym = mapnik.RasterSymbolizer()
   sym.colorizer = col
   rule = mapnik.Rule()
   rule.symbols.append(sym)
   style.rules.append(rule)
   mm.append_style('foo', style)
   lyr.styles.append('foo')
   mm.layers.append(lyr)
   mm.zoom_to_box(expenv)
   im = mapnik.Image(mm.width, mm.height)
   t0 = time.time() # we want wall time to include IO waits
   mapnik.render(mm, im)
   lap = time.time() - t0
   log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
   #im.save('/tmp/xfull.png') # for debugging
   h = format(value, '02x')
   hex_v = '0000ffff'
   hex_a = 'ff0000ff'
   hex_b = '00ff00ff'
   eq_(hexlify(im.view( 3, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view(13, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 3, 8,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8, 8,1,1).tostring()), hex_v);
   eq_(hexlify(im.view(13, 8,1,1).tostring()), hex_a);
   eq_(hexlify(im.view( 3,13,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8,13,1,1).tostring()), hex_b);
   eq_(hexlify(im.view(13,13,1,1).tostring()), hex_v);
Exemplo n.º 10
0
 def _test_rgba_subquery(lbl, pixtype, r, g, b, a, g1, b1):
   #
   #      3   8   13
   #    +---+---+---+
   #  3 | v | v | h |  NOTE: writes different alpha
   #    +---+---+---+        in 13,8 and 8,13
   #  8 | v | v | a |  
   #    +---+---+---+  
   # 13 | v | b | v |
   #    +---+---+---+
   #
   sql = "(select 3 as i, " \
         " ST_SetValues(" \
         "  ST_SetValues(" \
         "   ST_AddBand(" \
         "    ST_AddBand(" \
         "     ST_AddBand(" \
         "      ST_AsRaster(" \
         "       ST_MakeEnvelope(0,0,14,14), " \
         "       1.0, -1.0, '%s', %s" \
         "      )," \
         "      '%s', %d::float" \
         "     ), " \
         "     '%s', %d::float" \
         "    ), " \
         "    '%s', %d::float" \
         "   ), " \
         "   2, 11, 6, 4, 5, %s::float8" \
         "  )," \
         "  3, 6, 11, 5, 4, %s::float8" \
         " ) as r" \
         ") as foo" % (pixtype, r, pixtype, g, pixtype, b, pixtype, a, g1, b1)
   overview = ''
   rescale = 0
   clip = 0
   if rescale:
     lbl += ' Sc'
   if clip:
     lbl += ' Cl'
   ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME, table=sql,
     raster_field='r', use_overviews=0 if overview else 0,
     prescale_rasters=rescale, clip_rasters=clip)
   fs = ds.featureset()
   feature = fs.next()
   eq_(feature['i'],3)
   lyr = mapnik.Layer('rgba_subquery')
   lyr.datasource = ds
   expenv = mapnik.Box2d(0,0,14,14)
   env = lyr.envelope()
   assert_almost_equal(env.minx, expenv.minx, places=0)
   assert_almost_equal(env.miny, expenv.miny, places=0)
   assert_almost_equal(env.maxx, expenv.maxx, places=0)
   assert_almost_equal(env.maxy, expenv.maxy, places=0)
   mm = mapnik.Map(15, 15)
   style = mapnik.Style()
   sym = mapnik.RasterSymbolizer()
   rule = mapnik.Rule()
   rule.symbols.append(sym)
   style.rules.append(rule)
   mm.append_style('foo', style)
   lyr.styles.append('foo')
   mm.layers.append(lyr)
   mm.zoom_to_box(expenv)
   im = mapnik.Image(mm.width, mm.height)
   t0 = time.time() # we want wall time to include IO waits
   mapnik.render(mm, im)
   lap = time.time() - t0
   log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
   im.save('/tmp/xfull.png') # for debugging
   hex_v = format(r << 24 | g  << 16 | b  << 8 | a, '08x')
   hex_a = format(r << 24 | g1 << 16 | b  << 8 | a, '08x')
   hex_b = format(r << 24 | g  << 16 | b1 << 8 | a, '08x')
   eq_(hexlify(im.view( 3, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view(13, 3,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 3, 8,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8, 8,1,1).tostring()), hex_v);
   eq_(hexlify(im.view(13, 8,1,1).tostring()), hex_a);
   eq_(hexlify(im.view( 3,13,1,1).tostring()), hex_v);
   eq_(hexlify(im.view( 8,13,1,1).tostring()), hex_b);
   eq_(hexlify(im.view(13,13,1,1).tostring()), hex_v);
Exemplo n.º 11
0
 def _test_rgb_8bui_rendering(lbl, tnam, overview, rescale, clip):
   if rescale:
     lbl += ' Sc'
   if clip:
     lbl += ' Cl'
   ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME,table=tnam,
     use_overviews=1 if overview else 0,
     prescale_rasters=rescale,clip_rasters=clip)
   fs = ds.featureset()
   feature = fs.next()
   eq_(feature['rid'],1)
   lyr = mapnik.Layer('rgba_8bui')
   lyr.datasource = ds
   expenv = mapnik.Box2d(-12329035.7652168,4508650.39854396, \
                         -12328653.0279471,4508957.34625536)
   env = lyr.envelope()
   # As the input size is a prime number both horizontally
   # and vertically, we expect the extent of the overview
   # tables to be a pixel wider than the original, whereas
   # the pixel size in geographical units depends on the
   # overview factor. So we start with the original pixel size
   # as base scale and multiply by the overview factor.
   # NOTE: the overview table extent only grows north and east
   pixsize = 2 # see gdalinfo nodata-edge.tif
   tol = pixsize * max(overview.split(',')) if overview else 0
   assert_almost_equal(env.minx, expenv.minx, places=0)
   assert_almost_equal(env.miny, expenv.miny, delta=tol)
   assert_almost_equal(env.maxx, expenv.maxx, delta=tol)
   assert_almost_equal(env.maxy, expenv.maxy, places=0)
   mm = mapnik.Map(256, 256)
   style = mapnik.Style()
   sym = mapnik.RasterSymbolizer()
   rule = mapnik.Rule()
   rule.symbols.append(sym)
   style.rules.append(rule)
   mm.append_style('foo', style)
   lyr.styles.append('foo')
   mm.layers.append(lyr)
   mm.zoom_to_box(expenv)
   im = mapnik.Image(mm.width, mm.height)
   t0 = time.time() # we want wall time to include IO waits
   mapnik.render(mm, im)
   lap = time.time() - t0
   log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
   #im.save('/tmp/xfull.png') # for debugging
   # no data
   eq_(hexlify(im.view(3,16,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(128,16,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(250,16,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(3,240,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(128,240,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(250,240,1,1).tostring()), '00000000')
   # dark brown
   eq_(hexlify(im.view(174,39,1,1).tostring()), 'c3a698ff') 
   # dark gray
   eq_(hexlify(im.view(195,132,1,1).tostring()), '575f62ff') 
   # Now zoom over a portion of the env (1/10)
   newenv = mapnik.Box2d(-12329035.7652168, 4508926.651484220, \
                         -12328997.49148983,4508957.34625536)
   mm.zoom_to_box(newenv)
   t0 = time.time() # we want wall time to include IO waits
   mapnik.render(mm, im)
   lap = time.time() - t0
   log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
   #im.save('/tmp/xtenth.png') # for debugging
   # no data
   eq_(hexlify(im.view(3,16,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(128,16,1,1).tostring()), '00000000')
   eq_(hexlify(im.view(250,16,1,1).tostring()), '00000000')
   # black
   eq_(hexlify(im.view(3,42,1,1).tostring()), '000000ff')
   eq_(hexlify(im.view(3,134,1,1).tostring()), '000000ff')
   eq_(hexlify(im.view(3,244,1,1).tostring()), '000000ff')
   # gray
   eq_(hexlify(im.view(135,157,1,1).tostring()), '4e555bff')
   # brown
   eq_(hexlify(im.view(195,223,1,1).tostring()), 'f2cdbaff')
Exemplo n.º 12
0
    def _test_rgba_8bui_rendering(lbl, overview, rescale, clip):
      if rescale:
        lbl += ' Sc'
      if clip:
        lbl += ' Cl'
      ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME,table='(select * from "River") foo',
        use_overviews=1 if overview else 0,
        prescale_rasters=rescale,clip_rasters=clip)
      fs = ds.featureset()
      feature = fs.next()
      eq_(feature['rid'],1)
      lyr = mapnik.Layer('rgba_8bui')
      lyr.datasource = ds
      expenv = mapnik.Box2d(0, -210, 256, 0)
      env = lyr.envelope()
      # As the input size is a prime number both horizontally
      # and vertically, we expect the extent of the overview
      # tables to be a pixel wider than the original, whereas
      # the pixel size in geographical units depends on the
      # overview factor. So we start with the original pixel size
      # as base scale and multiply by the overview factor.
      # NOTE: the overview table extent only grows north and east
      pixsize = 1 # see gdalinfo river.tif
      tol = pixsize * max(overview.split(',')) if overview else 0
      assert_almost_equal(env.minx, expenv.minx)
      assert_almost_equal(env.miny, expenv.miny, delta=tol) 
      assert_almost_equal(env.maxx, expenv.maxx, delta=tol)
      assert_almost_equal(env.maxy, expenv.maxy)
      mm = mapnik.Map(256, 256)
      style = mapnik.Style()
      sym = mapnik.RasterSymbolizer()
      rule = mapnik.Rule()
      rule.symbols.append(sym)
      style.rules.append(rule)
      mm.append_style('foo', style)
      lyr.styles.append('foo')
      mm.layers.append(lyr)
      mm.zoom_to_box(expenv)
      im = mapnik.Image(mm.width, mm.height)
      t0 = time.time() # we want wall time to include IO waits
      mapnik.render(mm, im)
      lap = time.time() - t0
      log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
      #im.save('/tmp/xfull.png') # for debugging
      # no data
      eq_(hexlify(im.view(3,3,1,1).tostring()), '00000000')
      eq_(hexlify(im.view(250,250,1,1).tostring()), '00000000') 
      # full opaque river color
      eq_(hexlify(im.view(175,118,1,1).tostring()), 'b9d8f8ff') 
      # half-transparent pixel
      pxstr = hexlify(im.view(122,138,1,1).tostring())
      apat = ".*(..)$"
      match = re.match(apat, pxstr)
      assert match, 'pixel ' + pxstr + ' does not match pattern ' + apat
      alpha = match.group(1)
      assert alpha != 'ff' and alpha != '00', \
        'unexpected full transparent/opaque pixel: ' + alpha

      # Now zoom over a portion of the env (1/10)
      newenv = mapnik.Box2d(166,-105,191,-77)
      mm.zoom_to_box(newenv)
      t0 = time.time() # we want wall time to include IO waits
      mapnik.render(mm, im)
      lap = time.time() - t0
      log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
      #im.save('/tmp/xtenth.png') # for debugging
      # no data
      eq_(hexlify(im.view(255,255,1,1).tostring()), '00000000')
      eq_(hexlify(im.view(200,40,1,1).tostring()), '00000000')
      # full opaque river color
      eq_(hexlify(im.view(100,168,1,1).tostring()), 'b9d8f8ff')
      # half-transparent pixel
      pxstr = hexlify(im.view(122,138,1,1).tostring())
      apat = ".*(..)$"
      match = re.match(apat, pxstr)
      assert match, 'pixel ' + pxstr + ' does not match pattern ' + apat
      alpha = match.group(1)
      assert alpha != 'ff' and alpha != '00', \
        'unexpected full transparent/opaque pixel: ' + alpha
Exemplo n.º 13
0
    def _test_dataraster_16bsi_rendering(lbl, overview, rescale, clip):
      if rescale:
        lbl += ' Sc'
      if clip:
        lbl += ' Cl'
      ds = mapnik.PgRaster(dbname=MAPNIK_TEST_DBNAME,table='"dataRaster"',
        band=1,use_overviews=1 if overview else 0,
        prescale_rasters=rescale,clip_rasters=clip)
      fs = ds.featureset()
      feature = fs.next()
      eq_(feature['rid'],1)
      lyr = mapnik.Layer('dataraster_16bsi')
      lyr.datasource = ds
      expenv = mapnik.Box2d(-14637, 3903178, 1126863, 4859678)
      env = lyr.envelope()
      # As the input size is a prime number both horizontally
      # and vertically, we expect the extent of the overview
      # tables to be a pixel wider than the original, whereas
      # the pixel size in geographical units depends on the
      # overview factor. So we start with the original pixel size
      # as base scale and multiply by the overview factor.
      # NOTE: the overview table extent only grows north and east
      pixsize = 500 # see gdalinfo dataraster.tif
      pixsize = 2497 # see gdalinfo dataraster-small.tif
      tol = pixsize * max(overview.split(',')) if overview else 0
      assert_almost_equal(env.minx, expenv.minx)
      assert_almost_equal(env.miny, expenv.miny, delta=tol) 
      assert_almost_equal(env.maxx, expenv.maxx, delta=tol)
      assert_almost_equal(env.maxy, expenv.maxy)
      mm = mapnik.Map(256, 256)
      style = mapnik.Style()
      col = mapnik.RasterColorizer();
      col.default_mode = mapnik.COLORIZER_DISCRETE;
      col.add_stop(0, mapnik.Color(0x40,0x40,0x40,255));
      col.add_stop(10, mapnik.Color(0x80,0x80,0x80,255));
      col.add_stop(20, mapnik.Color(0xa0,0xa0,0xa0,255));
      sym = mapnik.RasterSymbolizer()
      sym.colorizer = col
      rule = mapnik.Rule()
      rule.symbols.append(sym)
      style.rules.append(rule)
      mm.append_style('foo', style)
      lyr.styles.append('foo')
      mm.layers.append(lyr)
      mm.zoom_to_box(expenv)
      im = mapnik.Image(mm.width, mm.height)
      t0 = time.time() # we want wall time to include IO waits
      mapnik.render(mm, im)
      lap = time.time() - t0
      log('T ' + str(lap) + ' -- ' + lbl + ' E:full')
      # no data
      eq_(im.view(1,1,1,1).tostring(), '\x00\x00\x00\x00') 
      eq_(im.view(255,255,1,1).tostring(), '\x00\x00\x00\x00') 
      eq_(im.view(195,116,1,1).tostring(), '\x00\x00\x00\x00') 
      # A0A0A0
      eq_(im.view(100,120,1,1).tostring(), '\xa0\xa0\xa0\xff')
      eq_(im.view( 75, 80,1,1).tostring(), '\xa0\xa0\xa0\xff')
      # 808080
      eq_(im.view( 74,170,1,1).tostring(), '\x80\x80\x80\xff')
      eq_(im.view( 30, 50,1,1).tostring(), '\x80\x80\x80\xff')
      # 404040
      eq_(im.view(190, 70,1,1).tostring(), '\x40\x40\x40\xff')
      eq_(im.view(140,170,1,1).tostring(), '\x40\x40\x40\xff')

      # Now zoom over a portion of the env (1/10)
      newenv = mapnik.Box2d(273663,4024478,330738,4072303)
      mm.zoom_to_box(newenv)
      t0 = time.time() # we want wall time to include IO waits
      mapnik.render(mm, im)
      lap = time.time() - t0
      log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
      # nodata
      eq_(hexlify(im.view(255,255,1,1).tostring()), '00000000')
      eq_(hexlify(im.view(200,254,1,1).tostring()), '00000000')
      # A0A0A0
      eq_(hexlify(im.view(90,232,1,1).tostring()), 'a0a0a0ff')
      eq_(hexlify(im.view(96,245,1,1).tostring()), 'a0a0a0ff')
      # 808080
      eq_(hexlify(im.view(1,1,1,1).tostring()), '808080ff') 
      eq_(hexlify(im.view(128,128,1,1).tostring()), '808080ff') 
      # 404040
      eq_(hexlify(im.view(255, 0,1,1).tostring()), '404040ff')
Exemplo n.º 14
0
def make_image(shapefile,
               output,
               color_count=256,
               upper=-0.5,
               lower=0.5,
               opening=False,
               with_world=False):
    stops, colors = make_colors(shapefile, color_count)

    m = mapnik.Map(1300,
                   900)  # Create a map with a given width and height in pixels
    # Note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs' which is epsg:4326
    # The 'map.srs' is the target projection of the map and can be whatever you wish
    # Output projection
    m.srs = '+init=epsg:3857'
    m.background = mapnik.Color('white')  # Set background colour
    # mapnik.load_map(m, 'text_sym.xml')

    if with_world:
        world_style = mapnik.Style()
        world_rule = mapnik.Rule()
        world_psym = mapnik.PolygonSymbolizer()
        world_psym.fill = mapnik.Color('#c7e9b4')
        world_rule.symbols.append(world_psym)
        world_style.rules.append(world_rule)
        m.append_style('World Style', world_style)

        world_ds = mapnik.Shapefile(file='../../data/world_merc.shp')
        print("World envelope:", world_ds.envelope())
        world_layer = mapnik.Layer('world_layer')
        world_layer.srs = '+init=epsg:3857'
        world_layer.datasource = world_ds
        world_layer.styles.append('World Style')
        m.layers.append(world_layer)

    s = mapnik.Style()  # Style object to hold rules
    '''
    # To add outlines to a polygon we create a LineSymbolizer
    line_symbolizer = mapnik.LineSymbolizer()
    line_symbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
    line_symbolizer.stroke_width = 0.1
    r.symbols.append(line_symbolizer) # Add the symbolizer to the rule object
    '''
    for i in range(0, color_count):
        r = mapnik.Rule()  # Rule object to hold symbolizers
        # To fill a polygon we create a PolygonSymbolizer
        psym = mapnik.PolygonSymbolizer()
        # Make opacity in between 0.2 and 0.85
        psym.fill_opacity = 0.2 + 0.65 * ((i + 1) / color_count) if (
            stops[i] >= lower or stops[i] <= upper) else 0
        psym.fill = mapnik.Color(colors[i].web)
        r.symbols.append(psym)  # Add the symbolizer to the rule object
        r.filter = mapnik.Expression("[Data] >= {} and [Data] < {}".format(
            stops[i], stops[i + 1]))
        s.rules.append(r)  # Add the rule to the style

    # It is possible to define styles in an xml file then get those styles in python
    # text_s = m.find_style('style1')
    # for ru in text_s.rules:
    #     s.rules.append(ru)

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

    ds = mapnik.Shapefile(file=shapefile)
    print("Datasource envelope:", ds.envelope())
    l_shp = mapnik.Layer('data_layer')
    # Note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    # Input projection
    l_shp.srs = GeoFunctions.get_shapefile_srs(shapefile).ExportToProj4()
    print("Shapefile SRS:", l_shp.srs)
    l_shp.datasource = ds
    l_shp.styles.append('data_style')
    m.layers.append(l_shp)

    # bbox = mapnik.Box2d(85.5, 5.0, 100.5, 19.0)
    # merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')
    # longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    # transform = mapnik.ProjTransform(longlat, merc)
    # merc_bbox = transform.forward(bbox)
    # print(merc_bbox)
    # m.zoom_to_box(merc_bbox)
    m.zoom_all()
    mapnik.render_to_file(m, output)
    if opening:
        os.system('xdg-open ' + output)
Exemplo n.º 15
0
 def mapnik_style(self):
     point_style = mapnik.Style()
     r = mapnik.Rule()
     r.symbols.append(mapnik.PointSymbolizer())
     point_style.rules.append(r)
     return point_style
Exemplo n.º 16
0
def main():
    """ Our main program.
    """

    # Open up each layer's data source, remember the projection, and calculate
    # the overall boundary for all the displayed data that matches our bounds
    # filter.

    projections = []
    minLong = None
    maxLong = None
    minLat = None
    maxLat = None

    try:
        boundsFilter = BOUNDS_FILTER
    except NameError:
        boundsFilter = {}

    for i in range(len(LAYERS)):
        src = LAYERS[i]

        print "Processing " + src['sourceFile'] + "..."

        shapefile = osgeo.ogr.Open(src['sourceFile'])
        layer = shapefile.GetLayer(0)
        spatialRef = layer.GetSpatialRef()
        if spatialRef != None:
            projection = spatialRef.ExportToProj4()
        else:
            if len(projections) > 0:
                projection = projections[0]
            else:
                spatialRef = osgeo.osr.SpatialReference()
                spatialRef.SetWellKnownGeogCS('WGS84')
                projection = spatialRef.ExportToProj4()

        for i in range(layer.GetFeatureCount()):
            feature = layer.GetFeature(i)

            matches = True
            for key, value in boundsFilter.items():
                if feature.GetField(key) != value:
                    matches = False
                    break

            if not matches:
                continue

            if src.get("printAttrs") == True:
                print "  " + repr(feature.items().items())

            bounds = feature.GetGeometryRef().GetEnvelope()

            if minLong == None:
                minLong, maxLong, minLat, maxLat = bounds
            else:
                if bounds[0] < minLong: minLong = bounds[0]
                if bounds[1] > maxLong: maxLong = bounds[1]
                if bounds[2] < minLat: minLat = bounds[2]
                if bounds[3] > maxLat: maxLat = bounds[3]

        projections.append(projection)

    # Adjust the calculated bounds by the bounds margin, if any.

    try:
        minLong = minLong - BOUNDS_MARGIN
        maxLong = maxLong + BOUNDS_MARGIN
        minLat = minLat - BOUNDS_MARGIN
        maxLat = maxLat + BOUNDS_MARGIN
    except NameError:
        pass

    # If we've been asked to do so, print out the calculated bounds.

    try:
        if PRINT_BOUNDS:
            print "MIN_LAT  = %0.4f" % minLat
            print "MAX_LAT  = %0.4f" % maxLat
            print "MIN_LONG = %0.4f" % minLong
            print "MAX_LONG = %0.4f" % maxLong
    except NameError:
        pass

    # Calculate the size of the map image, based on the calculated boundaries.

    if OVERRIDE_MIN_LAT != None: minLat = OVERRIDE_MIN_LAT
    if OVERRIDE_MAX_LAT != None: maxLat = OVERRIDE_MAX_LAT
    if OVERRIDE_MIN_LONG != None: minLong = OVERRIDE_MIN_LONG
    if OVERRIDE_MAX_LONG != None: maxLong = OVERRIDE_MAX_LONG

    mapBounds = mapnik.Envelope(minLong, minLat, maxLong, maxLat)
    aspectRatio = mapBounds.width() / mapBounds.height()

    mapWidth = MAX_WIDTH
    mapHeight = int(mapWidth / aspectRatio)

    if mapHeight > MAX_HEIGHT:
        # Scale the map to fit.
        scaleFactor = float(MAX_HEIGHT) / float(mapHeight)
        mapWidth = int(mapWidth * scaleFactor)
        mapHeight = int(mapHeight * scaleFactor)

    # Create our map.

    m = mapnik.Map(mapWidth, mapHeight, projections[0])
    m.background = mapnik.Color(BACKGROUND_COLOR)

    # Setup the stylesheets to show the contents of each shapefile.

    for i in range(len(LAYERS)):
        src = LAYERS[i]

        s = mapnik.Style()
        r = mapnik.Rule()

        if src.get("filter") != None:
            r.filter = mapnik.Filter(src['filter'])

        if src['fillColor'] != None:
            ps = mapnik.PolygonSymbolizer(mapnik.Color(src['fillColor']))
            r.symbols.append(ps)
        if src['lineColor'] != None:
            stroke = mapnik.Stroke(mapnik.Color(src['lineColor']),
                                   src['lineWidth'])

            if src.get("lineJoin") == "miter":
                stroke.line_join = mapnik.line_join.MITER_JOIN
            elif src.get("lineJoin") == "round":
                stroke.line_join = mapnik.line_join.ROUND_JOIN
            elif src.get("linJoin") == "bevel":
                stroke.line_join = mapnik.line_join.BEVEL_JOIN

            if src.get("lineCap") == "round":
                stroke.line_cap = mapnik.line_cap.ROUND_CAP
            elif src.get("lineCap") == "square":
                stroke.line_cap = mapnik.line_cap.SQUARE_CAP
            elif src.get("lineCap") == "butt":
                stroke.line_cap = mapnik.line_cap.BUTT_CAP

            if src.get("lineDash") != None:
                stroke.add_dash(src['lineDash'], src['lineDash'] * 2)

            ls = mapnik.LineSymbolizer(stroke)
            r.symbols.append(ls)
        if src['labelField'] != None:
            ts = mapnik.TextSymbolizer(
                mapnik.Expression("[" + src['labelField'] + "]"),
                "DejaVu Sans Bold", src['labelSize'],
                mapnik.Color(src['labelColor']))
            if src.get("labelHalo") != None:
                ts.halo_radius = src['labelHalo']
            if src.get("labelPlacement") == "line":
                ts.label_placement = mapnik.label_placement.LINE_PLACEMENT
            if src.get("labelAllowOverlap") != None:
                ts.allow_overlap = src['labelAllowOverlap']
            else:
                ts.allow_overlap = True
            r.symbols.append(ts)

        s.rules.append(r)

        m.append_style("style-" + str(i + 1), s)

    # Setup our various map layers.

    for i in range(len(LAYERS)):
        src = LAYERS[i]

        l = mapnik.Layer("layer-" + str(i + 1), projections[i])
        if src['sourceFile'].endswith(".shp"):
            l.datasource = mapnik.Shapefile(file=src['sourceFile'])
        else:
            l.datasource = mapnik.Ogr(file=src['sourceFile'],
                                      layer=src.get("layer"))
        l.styles.append("style-" + str(i + 1))
        m.layers.append(l)

    # Finally, render the map.

    m.zoom_to_box(mapBounds)
    mapnik.render_to_file(m, "map.png", "png")

    os.system("open map.png")
Exemplo n.º 17
0
# Create the map object.
srs = "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs"
m = mapnik.Map(800, 600, srs)
m.zoom_to_box(mapnik.Box2d(-90.3, 29.7, -89.5, 30.3))

# Create a layer from a shapefile.
tiger_fn = r'D:\osgeopy-data\Louisiana\tiger_la_water_CENSUS_2006'
tiger_shp = mapnik.Shapefile(file=tiger_fn)
tiger_lyr = mapnik.Layer('Tiger')
tiger_lyr.datasource = tiger_shp

# Create a polygon fill symbol.
water_color = mapnik.Color(165, 191, 221)
water_fill_sym = mapnik.PolygonSymbolizer(water_color)

# Create a symbology style and add it to the layer.
tiger_rule = mapnik.Rule()
tiger_rule.symbols.append(water_fill_sym)
tiger_style = mapnik.Style()
tiger_style.rules.append(tiger_rule)
m.append_style('tiger', tiger_style)

# All of the code for the atlas layer is now gone...

# Add the atlas layer using the xml.
mapnik.load_map(m, r'D:\osgeopy-data\US\national_atlas_hydro.xml')
m.layers.append(tiger_lyr)

# Save the map.
mapnik.render_to_file(m, r'd:\temp\nola5.png')
Exemplo n.º 18
0
pic_output_format = 'jpeg'
###
###

# create a map with a given width and height in pixels
# note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
# the 'map.srs' is the target projection of the map and can be whatever you wish
m = mapnik.Map(pic_output_width, pic_output_height)

# Background color of the data
m.background = mapnik.Color(
    'White'
)  # set background colour to. List of RGB-Colors: http://gucky.uni-muenster.de/cgi-bin/rgbtab

# style object to hold rules
s = mapnik.Style()
s2 = mapnik.Style()
s3 = mapnik.Style()
s4 = mapnik.Style()

# rule object to hold symbolizers
r = mapnik.Rule()
r2 = mapnik.Rule()
r3 = mapnik.Rule()
r4 = mapnik.Rule()

###
### Color of the lines
###
polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#00d200'))  # green
polygon_symbolizer2 = mapnik.PolygonSymbolizer(
Exemplo n.º 19
0
def createisomap(iso, mapscale, name, name_en):

    map_width = int(mapscale[0])
    map_height = int(mapscale[1])

    map_minx = float(mapscale[2])
    map_maxx = float(mapscale[3])
    map_miny = float(mapscale[4])
    map_maxy = float(mapscale[5])

    print "mapdata:", map_width, map_height, map_maxx, map_maxy, map_minx, map_miny

    m = mapnik.Map(
        map_width,
        map_height)  # create a map with a given width and height in pixels
    # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    # the 'map.srs' is the target projection of the map and can be whatever you wish
    m.background = mapnik.Color(
        'steelblue')  # set background colour to '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

    psymbolizer = mapnik.PolygonSymbolizer()
    psymbolizer.fill = mapnik.Color('#f2eff9')
    r.symbols.append(psymbolizer)

    lsymbolizer = mapnik.LineSymbolizer()
    lsymbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
    lsymbolizer.stroke_width = 0.1
    r.symbols.append(lsymbolizer)

    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

    ds = mapnik.Shapefile(file='/osm/setup/ne_10m_admin_0_countries.shp')

    ds.envelope()

    layer = mapnik.Layer(
        'world')  # new layer called 'world' (we could name it anything)
    # 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)

    bbox = mapnik.Box2d(map_maxx, map_maxy, map_minx, map_miny)
    m.zoom_to_box(bbox)

    # .zoom_to_box(mapnik.Box2d(   ))
    # m.zoom_all()

    # Write the data to a png image called world.png the current directory

    img_directory = '/osm/service/' + CONTINENT + '/' + iso + '/img/'
    if not os.path.exists(img_directory):
        os.makedirs(img_directory)

    mapnik.render_to_file(m, img_directory + 'dbackground.png', 'png')

    ######################  flag ##################################

    copyfile('/osm/setup/dflag.png', img_directory + 'dflag.png')

    ####################  Logo #####################################

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 348, 98)
    ctx = cairo.Context(surface)
    ctx.select_font_face("Courier", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)

    ctx.set_font_size(42)
    ctx.move_to(2, 50)
    ctx.set_source_rgb(0.0, 0.0, 0.15)
    ctx.show_text('Taginfo-' + CONTINENT + '-' + iso)

    ctx.select_font_face('Sans')
    if len(name_en) > 26:
        ctx.set_font_size(20)
    elif len(name_en) > 18:
        ctx.set_font_size(26)
    else:
        ctx.set_font_size(30)

    ctx.move_to(1, 90)
    ctx.set_source_rgb(0.0, 0.0, 0.35)
    ctx.show_text(name_en)

    # finish up
    ctx.stroke()
    surface.write_to_png(img_directory + 'dlogo.png')
Exemplo n.º 20
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')
Exemplo n.º 21
0
def tile(request, version, rasterlayer_id, zoom, x, y):
    try:
        rasterlayer = RasterLayer.objects.get(id=rasterlayer_id)

        if version != "1.0":
            raise Http404

        zoom = int(zoom)
        x = int(x)
        y = int(y)

        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404

        xExtent = _unitsPerPixel(zoom) * TILE_WIDTH
        yExtent = _unitsPerPixel(zoom) * TILE_HEIGHT

        minLong = x * xExtent - 20026376.39
        minLat = y * yExtent - 20026376.39
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent

        map = mapnik.Map(
            TILE_WIDTH, TILE_HEIGHT,
            "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +units=m +k=1.0 +nadgrids=@null +no_defs"
        )
        map.background = mapnik.Color("#00000000")
        raster = mapnik.Layer("raster")
        raster.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"

        # se carga el archivo
        file_path = rasterlayer.file_path
        file_name = rasterlayer.file_name
        file_format = rasterlayer.file_format
        ext = file_format
        file_name = file_name.replace(ext, "-proj" + ext)
        fullName = join(file_path, file_name)
        numBands = rasterlayer.numBands

        # se obtiene el estilo
        layer_styles = Style.objects.filter(layers__id=rasterlayer.id)
        if numBands == 1 and layer_styles.count() == 1:
            raster.datasource = mapnik.Gdal(file=fullName, band=1)
        else:
            raster.datasource = mapnik.Gdal(file=fullName)

        style = mapnik.Style()
        rule = mapnik.Rule()

        symbol = mapnik.RasterSymbolizer()

        # agregar estilo si existe
        if layer_styles.count() == 1:
            layer_style = layer_styles[0]
            colorMap = getColorMap(layer_style)
            c = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR,
                                       mapnik.Color(0, 0, 0, 0))

            for entry in colorMap:
                color = entry["color"]
                quantity = entry["quantity"]
                c.add_stop(quantity, mapnik.Color(color))

            symbol.colorizer = c

        rule.symbols.append(symbol)
        style.rules.append(rule)
        map.append_style("estilo", style)
        raster.styles.append("estilo")
        map.layers.append(raster)

        map.zoom_to_box(mapnik.Box2d(minLong, minLat, maxLong, maxLat))
        image = mapnik.Image(TILE_WIDTH, TILE_HEIGHT)
        mapnik.render(map, image)

        imageData = image.tostring('png')
        return HttpResponse(imageData, content_type="image/png")
    except:
        traceback.print_exc()
        return HttpResponse("Error")
Exemplo n.º 22
0
                    level=logging.INFO)

# Parameters
countryListXml = "C:/Projects/BirthsAndPregnanciesMapping/code/country_list.xml"
dbPath = "C:/Projects/BirthsAndPregnanciesMapping/data/2014-05-23/adminBoundaries.sqlite"
epsDir = "C:/Projects/BirthsAndPregnanciesMapping/results/eps"
max_img_size = 1000  # Max width or height of output image

# Create style
stroke = mapnik.Stroke()
stroke.color = mapnik.Color(0, 0, 0)
stroke.width = 1.0
symbolizer = mapnik.LineSymbolizer(stroke)
rule = mapnik.Rule()
rule.symbols.append(symbolizer)
style = mapnik.Style()
style.rules.append(rule)

# Loop through countries in xml
countryList = ET.parse(countryListXml).getroot()
for country in countryList.findall("country"):
    name = country.find("name").text
    iso3 = country.find("iso3").text

    logging.info("Processing %s" % name)

    # Create Datasource
    query = '(SELECT * FROM GAUL_2010_2 WHERE ISO3 = "%s")' % iso3
    datasource = mapnik.SQLite(file=dbPath,
                               table=query,
                               geometry_field="Geometry",
Exemplo n.º 23
0
import mapnik

#Membuat Map
m = mapnik.Map(6024, 2480, '+init=epsg:4326')
m.background = mapnik.Color('steelblue')

#------------------------Layer1 Surabaya----------------------#
#Membuat lapisan
layer_sby = mapnik.Layer('SurabayaLayer1', '+init=epsg:4326')
layer_sby.datasource = mapnik.Shapefile(
    file='../Tugas 4/peta kecamatan indonesia/INDONESIA_KEC.shp'
)  #mengambil lapisan dari sumber data

#Membuat Style
ssby = mapnik.Style()

#Membuat poligon area
rsby = mapnik.Rule()
polygon_sby = mapnik.PolygonSymbolizer(mapnik.Color(217, 235, 203))
rsby.symbols.append(polygon_sby)  #membuat rule polygon indonesia

#Menggambar garis tepi
#line_sby = mapnik.LineSymbolizer()
#line_sby = mapnik.LineSymbolizer(mapnik.Color('grey'),1)
#line_sby.stroke_width = 2.0
#rsby.symbols.append(line_sby) #menerapkan garis tepi ke rule map

#Poin wisata
ssby_wisata = mapnik.Style()
rsby_wisata = mapnik.Rule()
poin_wisata = mapnik.MarkersSymbolizer()
# -*- coding: utf-8 -*-
print('=' * 40)
print(__file__)
from helper.textool import get_tmp_file

################################################################################

################################################################################
import os
import mapnik
stylesheet = '/gdata/world_population.xml'
m = mapnik.Map(600, 300)
mapnik.load_map(m, stylesheet)
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)
s.rules.append(r)
m.append_style('My Style2', s)

################################################################################
wkt_geom = 'POLYGON ((5 21,-18 -10, -16 -52, 37 -21, 5 21))'
csv_string = '''
     wkt,Name
    "{wkt_geom}","test"
    '''.format(wkt_geom=wkt_geom)

ds = mapnik.Datasource(**{"type": "csv", "inline": csv_string})
layer2 = mapnik.Layer('world', '+proj=latlong +datum=WGS84')
def render(parameters):
    if not parameters.verbose:
        mapnik.logger.set_severity(getattr(mapnik.severity_type, 'None'))

    merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')
    longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')

    imgwidth = math.trunc(parameters.pagewidth / inch * parameters.dpi)
    imgheight = math.trunc(parameters.pageheight / inch * parameters.dpi)

    m = mapnik.Map(imgwidth, imgheight)
    #mapnik.load_map(m, parameters.mapstyle)
    mapnik.load_map(m, parameters.hikingmapstyle)
    m.srs = merc.params()

    if hasattr(mapnik, 'Box2d'):
        bbox = mapnik.Box2d(parameters.minlon, parameters.minlat, parameters.maxlon, parameters.maxlat)
    else:
        bbox = mapnik.Envelope(parameters.minlon, parameters.minlat, parameters.maxlon, parameters.maxlat)

    transform = mapnik.ProjTransform(longlat, merc)
    merc_bbox = transform.forward(bbox)
    m.zoom_to_box(merc_bbox)

    # create raster symbolizer / rule / style
    rastersymbolizer = mapnik.RasterSymbolizer()
    rastersymbolizer.opacity = 1.0
    rasterrule = mapnik.Rule()
    rasterrule.symbols.append(rastersymbolizer)
    rasterstyle = mapnik.Style()
    rasterstyle.rules.append(rasterrule)
    m.append_style('RasterStyle', rasterstyle)

    # fetch tiles using the landez TileManager
    tm = create_tiles_manager(parameters)
    zoomlevel = calc_zoomlevel(parameters.pagewidth, parameters.pageheight, parameters.dpi, \
                               parameters.scale_factor, parameters.tile_size, \
                               parameters.minlon, parameters.minlat, \
                               parameters.maxlon, parameters.maxlat)
    if parameters.verbose:
        print("Calculated zoomlevel = %d" % zoomlevel[0])

    for tile in tm.tileslist(bbox = (parameters.minlon, parameters.minlat, \
                                     parameters.maxlon, parameters.maxlat), \
                             zoomlevels = zoomlevel):
        # calc tile metadata
        tile_path = tm.cache.tile_fullpath(tile)
        proj = GoogleProjection(tm.tile_size, zoomlevel, tm.tile_scheme)
        (tile_lox, tile_loy, tile_hix, tile_hiy) = proj.tile_bbox(tile)
        try:
            # make sure the tile is on disk; tiledata is not needed
            tiledata = tm.tile(tile)
            # add to mapnik layer
            rasterlayer = mapnik.Layer("RasterLayer-%d-%d-%d" % tile)
            rasterlayer.datasource = mapnik.Raster(file = tile_path, \
                                                   lox = tile_lox, loy = tile_loy, \
                                                   hix = tile_hix, hiy = tile_hiy)
            rasterlayer.styles.append('RasterStyle')
            m.layers.append(rasterlayer)
        except ExtractionError:
            print("warning: missing tile zoom=%d x=%d y=%d" % tile)

    for gpxfile in parameters.gpxfiles:
        gpxlayer = mapnik.Layer('GPXLayer')
        gpxlayer.datasource = mapnik.Ogr(file = gpxfile, layer = 'tracks')
        gpxlayer.styles.append('GPXStyle')
        m.layers.append(gpxlayer)

    if parameters.temptrackfile:
        overviewlayer = mapnik.Layer('OverviewLayer')
        overviewlayer.datasource = mapnik.Ogr(file = parameters.temptrackfile, layer = 'tracks')
        overviewlayer.styles.append('GPXStyle')
        m.layers.append(overviewlayer)
    
    if parameters.tempwaypointfile:
        waypointlayer = mapnik.Layer('WaypointLayer')
        waypointlayer.datasource = mapnik.Ogr(file = parameters.tempwaypointfile, layer = 'waypoints')
        waypointlayer.styles.append('WaypointStyle')
        m.layers.append(waypointlayer)

    mapnik.render_to_file(m, parameters.basefilename + "." + parameters.output_format,
                          parameters.output_format,
                          parameters.scale_factor)
Exemplo n.º 26
0
    bbox = mapnik.Box2d(xmin, ymin, xmax, ymax)
else:
    bbox = mapnik.Envelope(xmin, ymin, xmax, ymax)

# Project bounds to map projection
e = mapnik.forward_(bbox, prj)

# Zoom map to bounding box
m.zoom_to_box(e)

#
# START Layer 1
#

# style object to hold rules
s = mapnik.Style()

# rule object to hold symbolizers
r = mapnik.Rule()

# Lines (outlines of polygons and/or simple lines. Line-Color (RGB) line-thickness
#polygon_symbolizer = mapnik2.PolygonSymbolizer(mapnik2.Color('red')) #rgb(5%,5%,5%)
# add the polygon_symbolizer to the rule object
#r.symbols.append(polygon_symbolizer)

# Point Style. Path to marker.png
point_symbolizer = mapnik.PointSymbolizer(mapnik2.PathExpression(point_marker))

# Allow Overlaps and set opacity of marker
point_symbolizer.allow_overlap = True
point_symbolizer.opacity = 0.7
# createExampleMap.py

import mapnik

MIN_LAT = -35
MAX_LAT = +35
MIN_LONG = -12
MAX_LONG = +50

MAP_WIDTH = 700
MAP_HEIGHT = 800

# Define our polygon styles:

polygonStyle = mapnik.Style()

rule = mapnik.Rule()
rule.filter = mapnik.Filter("[NAME] = 'Angola'")
symbol = mapnik.PolygonSymbolizer(mapnik.Color("#604040"))
rule.symbols.append(symbol)

polygonStyle.rules.append(rule)

rule = mapnik.Rule()
rule.filter = mapnik.Filter("[NAME] != 'Angola'")
symbol = mapnik.PolygonSymbolizer(mapnik.Color("#406040"))
rule.symbols.append(symbol)

polygonStyle.rules.append(rule)

rule = mapnik.Rule()