Пример #1
0
    def _render_shape_file(self, shape_file, color, line_width):
        LOG.debug("render_shape_file")
        shape_file.flush()

        shpid = os.path.basename(shape_file.get_filepath())
        s, r = mapnik.Style(), mapnik.Rule()

        if ocitysmap.get_mapnik_major_version() == 2:
            r.symbols.append(mapnik.PolygonSymbolizer(color))
            r.symbols.append(mapnik.LineSymbolizer(color, line_width))
        else:
            poly_sym = mapnik.PolygonSymbolizer()
            poly_sym.fill = color
            r.symbols.append(poly_sym)
            line_sym = mapnik.LineSymbolizer()
            line_sym.stroke = color
            line_sym.stroke_width = float(line_width)
            r.symbols.append(line_sym)
            s.rules.append(r)

        self._map.append_style('style_%s' % shpid, s)
        layer = mapnik.Layer(shpid)
        layer.datasource = mapnik.Shapefile(file=shape_file.get_filepath())
        layer.styles.append('style_%s' % shpid)

        self._map.layers.append(layer)
Пример #2
0
def test_polygonsymbolizer_init():
    p = mapnik.PolygonSymbolizer()

    eq_(p.fill, mapnik.Color('gray'))
    eq_(p.fill_opacity, 1)

    p = mapnik.PolygonSymbolizer(mapnik.Color('blue'))

    eq_(p.fill, mapnik.Color('blue'))
    eq_(p.fill_opacity, 1)
Пример #3
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')
Пример #4
0
def test_polygon_symbolizer():
    p = mapnik.PolygonSymbolizer()
    eq_(p.smooth, 0.0)
    eq_(p.comp_op, mapnik.CompositeOp.src_over)
    eq_(p.clip, True)
    eq_(p.fill, mapnik.Color('gray'))
    eq_(p.fill_opacity, 1)

    p = mapnik.PolygonSymbolizer(mapnik.Color('blue'))

    eq_(p.fill, mapnik.Color('blue'))
    eq_(p.fill_opacity, 1)
Пример #5
0
def test_polygonsymbolizer_init():
    p = mapnik.PolygonSymbolizer()

    eq_(p.fill, mapnik.Color('gray'))
    eq_(p.fill_opacity, 1)
    eq_(p.placement, mapnik.point_placement.CENTROID)

    p = mapnik.PolygonSymbolizer(mapnik.Color('blue'))
    p.placement = mapnik.point_placement.INTERIOR

    eq_(p.fill, mapnik.Color('blue'))
    eq_(p.fill_opacity, 1)
    eq_(p.placement, mapnik.point_placement.INTERIOR)
Пример #6
0
def index(request):
    m = mapnik.Map(700, 700)
    m.background = mapnik.Color("white")
    

    polygons = mapnik.PolygonSymbolizer()
    polygons.fill = mapnik.Color("orange")

    rules = mapnik.Rule()
    rules.symbols.append(polygons)

    style = mapnik.Style()
    style.rules.append(rules)

    # Creating rules 
    highlight = mapnik.PolygonSymbolizer()

    highlight.fill = mapnik.Color('red')
    r = mapnik.Rule()
    r.filter = mapnik.Expression("[productivi] <= 31")
    r.symbols.append(highlight)
    style.rules.append(r)

    highlight.fill = mapnik.Color('green')
    g = mapnik.Rule()
    g.filter = mapnik.Expression("[productivi] >= 70")
    g.symbols.append(highlight)
    style.rules.append(g)


    m.append_style('Polygons', style)

    layer = mapnik.Layer('A')

    layer.datasource = mapnik.PostGIS(host='127.0.0.1',user='******', \
                                        password='******',dbname='geotest', \
                                        table='map_map', srid='3857')
    layer.styles.append('Polygons')
    m.layers.append(layer)


    rules.symbols.append(polygons)
    style.rules.append(rules)

    m.zoom_all()
    mapnik.render_to_file(m, os.path.abspath('FileStorage/polygons.png'), 'png')
    
    return render(request, 'base.html')
Пример #7
0
    def __call__(self, feature_layers):
        # take the feature_layers dict and generate a gif response

        # this just puts all the features across all layers into a
        # single one, and then just renders them all with a very
        # simple style as a proof of concept
        # we probably want to do this per layer with a separate style
        # for each
        features = feature_layers_to_features_list(feature_layers)

        layer = mapnik.Layer('tile')
        memds = mapnik.MemoryDatasource()
        ctx = mapnik.Context()
        for feature in features:
            wkb, properties, fid = feature
            for key in properties.keys():
                ctx.push(key.encode('utf-8'))
        i = 1
        for feature in features:
            wkb, properties, fid = feature
            mf = mapnik.Feature(ctx, i)
            i += 1
            mf.add_geometries_from_wkb(wkb)
            for k, v in properties.items():
                mf[k.encode('utf-8')] = str(v)
                memds.add_feature(mf)

        layer.datasource = memds

        m = mapnik.Map(256, 256)

        m.background = mapnik.Color('blue')

        s = mapnik.Style()
        r = mapnik.Rule()
        polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
        r.symbols.append(polygon_symbolizer)
        line_symbolizer = mapnik.LineSymbolizer(
            mapnik.Color('rgb(50%,50%,50%)'), 0.1)
        r.symbols.append(line_symbolizer)
        s.rules.append(r)
        m.append_style('my style', s)
        layer.styles.append('my style')

        m.layers.append(layer)
        m.zoom_all()
        # from mapnik import Image
        # im = Image(m.width, m.height)
        # mapnik.render(m, im)
        # png_contents = im.tostring()

        # this was just the easiest way for me to get this to work
        import tempfile
        tmpfile = tempfile.NamedTemporaryFile()
        with tmpfile.file as fp:
            mapnik.render_to_file(m, tmpfile.name, 'png')
            fp.seek(0)
            png_contents = fp.read()

        return png_contents
Пример #8
0
    def addPreviewToMap(self, name, scaleDenoms, filter, symbol_type,
                        datasource, layerSRS, prevColor):
        s = mapnik.Style()
        r = mapnik.Rule()
        if symbol_type == 'polygon':
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color(prevColor))
            r.symbols.append(polygon_symbolizer)
        elif symbol_type == 'line':
            line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(prevColor), 3)
            r.symbols.append(line_symbolizer)
#        elif 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 symbol_type, 'has to be implemented to preview!!!'
        if filter != None:
            #f = mapnik.Expression("[waterway] != ''") #'Expression' stands for 'Filter' as this will be replaced in Mapnik3
            r.filter = filter  #f
            if scaleDenoms != -1:
                r.min_scale = scaleDenoms[0]
                r.max_scale = scaleDenoms[1]
        s.rules.append(r)

        proof = self.tileParams.getMapnikMap().append_style(name, s)
        layer = mapnik.Layer('world')
        layer.datasource = datasource[1]
        layer.srs = layerSRS
        layer.styles.append(name)
        self.tileParams.getMapnikMap().layers.append(layer)
Пример #9
0
    def addPreviewOfGeneralizedGeometriesToMap(self, table_name, symbol_type,
                                               layerSRS, name):
        genColor = 'rgb(0%,0%,100%)'
        s = mapnik.Style()
        r = mapnik.Rule()
        if symbol_type == 'polygon':
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color(genColor))
            r.symbols.append(polygon_symbolizer)
        elif symbol_type == 'line':
            line_symbolizer = mapnik.LineSymbolizer(mapnik.Color(genColor), 2)
            r.symbols.append(line_symbolizer)
        else:
            print symbol_type, 'has to be implemented to preview!!!'
        s.rules.append(r)
        self.tileParams.getMapnikMap().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 ' +
                                        table_name + ' ) as geometries')
        lyr.srs = layerSRS
        lyr.styles.append(name)
        self.tileParams.getMapnikMap().layers.append(lyr)
Пример #10
0
    def render_png(self, show=True):
        import mapnik
        #TODO scale dimensions to aspect ratio of data
        m = mapnik.Map(800, 400)
        m.background = mapnik.Color('white')
        s = mapnik.Style()
        r = mapnik.Rule()

        if "point" in self.collection().schema['geometry'].lower():
            point_symbolizer = mapnik.PointSymbolizer()
            r.symbols.append(point_symbolizer)
        else:
            polygon_symbolizer = mapnik.PolygonSymbolizer(
                mapnik.Color('#f2eff9'))
            r.symbols.append(polygon_symbolizer)

            line_symbolizer = mapnik.LineSymbolizer(
                mapnik.Color('rgb(50%,50%,50%)'), 0.8)
            r.symbols.append(line_symbolizer)

        s.rules.append(r)
        m.append_style('My Style', s)
        ds = mapnik.Shapefile(file=self.path)
        layer = mapnik.Layer('world')
        layer.datasource = ds
        layer.styles.append('My Style')
        m.layers.append(layer)
        m.zoom_all()
        outfile = '/tmp/world.png'
        mapnik.render_to_file(m, outfile, 'png')
        if show:
            im = Image.open(outfile)
            im.show()
        return outfile
Пример #11
0
def _add_species(m, speciesfile):
    'speciesfile = shapefile with species distribution'

    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()
    polygon_symbolizer.fill = mapnik.Color('rgb(0,0,0)')
    polygon_symbolizer.fill_opacity = 0.25
    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()
    line_symbolizer.stroke = mapnik.Color('rgb(0%,0%,0%)')
    line_symbolizer.stroke_width = 1
    r.symbols.append(line_symbolizer)  # add the symbolizer to the rule object
    s.rules.append(r)  # now add the rule to the style

    m.append_style('Chorology', s)

    #ds = mapnik.Shapefile(file = speciesfile)
    ds = mapnik.GeoJSON(file=speciesfile)
    layer = mapnik.Layer('shrub')

    layer.datasource = ds
    layer.srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    layer.styles.append('Chorology')

    m.layers.append(layer)
Пример #12
0
    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')
        r.symbols.append(symb)
        s.rules.append(r)
        lyr = mapnik.Layer('poly')
        lyr.datasource = ds
        lyr.styles.append('poly')
        m = mapnik.Map(256, 256)
        m.append_style('poly', s)
        m.layers.append(lyr)
        m.zoom_all()

        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, m.width, m.height)
        mapnik.render_layer(m, surface, lyr)

        im = mapnik.Image.from_cairo(surface)

        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)
def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_csv():
    expected_color = mapnik.Color('white')
    projection = '+init=epsg:4326'
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    feat = mapnik.Feature.from_geojson(json.dumps(geojson), context)
    ds.add_feature(feat)
    geojson_string = "geojson\n'%s'" % json.dumps(geojson['geometry'])
    ds = mapnik.Datasource(**{'type': 'csv', 'inline': geojson_string})
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.PolygonSymbolizer()
    sym.fill = expected_color
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer', projection)
    lyr.datasource = ds
    lyr.styles.append('style')
    m = mapnik.Map(256, 256, projection)
    m.background_color = mapnik.Color('green')
    m.append_style('style', s)
    m.layers.append(lyr)
    # 17/20864/45265.png
    m.zoom_to_box(
        mapnik.Box2d(-13658379.710221574, 6197514.253362091,
                     -13657768.213995293, 6198125.749588372))
    # works 15/5216/11316.png
    # m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372))
    im = mapnik.Image(256, 256)
    mapnik.render(m, im)
    eq_(im.get_pixel(128, 128), expected_color.packed())
Пример #14
0
    def __init__(self, id, file, fill_color, stroke_color, stroke_width):
        """Creates a shape layer."""
        super(ShapeLayer, self).__init__()
        self.id = id
        self.file = file
        self.fill_color = fill_color
        self.stroke_color = stroke_color
        self.stroke_width = stroke_width
        ds = mapnik.Shapefile(file=(os.path.splitext(file)[0]))
        srs = self._srs(file)
        self.mapnik_layer = mapnik.Layer('Shapefile Layer', srs)
        self.mapnik_layer.datasource = ds
        self.mapnik_layer.maximum_extent = self._extent(file)

        polygon_symbolizer = mapnik.PolygonSymbolizer()
        polygon_symbolizer.fill = mapnik.Color(str(fill_color))

        line_symbolizer = mapnik.LineSymbolizer()
        line_symbolizer.stroke = mapnik.Color(str(stroke_color))
        line_symbolizer.stroke_width = float(stroke_width)

        rule = mapnik.Rule()
        rule.symbols.append(polygon_symbolizer)
        rule.symbols.append(line_symbolizer)
        style = mapnik.Style()
        style.rules.append(rule)
        self.mapnik_style = style
        self.mapnik_layer.styles.append('Shapefile Layer')
def polygon_map():
    m = mapnik.Map(600, 300)  # 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
    polygon_symbolizer = mapnik.PolygonSymbolizer()
    polygon_symbolizer.fill = 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
    sym = mapnik.PointSymbolizer()
    # args are file, type, height, width
    sym.allow_overlap = True
    sym.opacity = .5
    r.symbols.append(sym)
    '''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
    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='I:\Data\shashankdata\LSMDATASET\INVENTORY\INVENTORY.shp')
    layer = mapnik.Layer('Petrolling Party')  # 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)
    # Write the data to a png image called world.png in the current directory
    mapnik.render_to_file(m, 'C:\Users\Hp\Desktop\pol\sha.png', 'png')

    # Exit the Python interpreter
    exit()  # or ctrl-d
Пример #16
0
        def __init__(self):
            BaseWMSFactory.__init__(self)

            layer = mapnik.Layer('TOP', modis_srs)
            layer.datasource = mapnik.Gdal(file=str(data),band=1) 
            layer.title = "Modis VI Layer"
            layer.queryable = True
            layer.wms_srs = None
            style = mapnik.Style()
            rule = mapnik.Rule()
            sym = mapnik.RasterSymbolizer()
            sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color("transparent"))
            scale = getModisScale(product)
            for color in scale:
                sym.colorizer.add_stop(color['stop'], mapnik.Color(*color['color']))
            rule.symbols.append(sym)
            style.rules.append(rule)
            self.register_style('modis_style', style)
            self.register_layer(layer, "modis_style",("modis_style",))

            layer = mapnik.Layer('ocean_mask')
            layer.datasource = mapnik.Shapefile(file=str("/data/health/data1/web/data/shapes/50m_ocean.shp"))
            layer.queryable = True
            layer.wms_srs = None
            style = mapnik.Style()
            rule = mapnik.Rule()
            poly_sym = mapnik.PolygonSymbolizer(mapnik.Color('#50649B'))
            rule.symbols.append(poly_sym)
            style.rules.append(rule)
            self.register_style('mask_style', style)
            self.register_layer(layer, "mask_style",("mask_style",))
Пример #17
0
def get_map():
    m = mapnik.Map(map_width, map_height)

    m.srs = map_srs # the output projection

    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()
    mapnik.LineSymbolizer(mapnik.Color('green'),0.1)
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My Style', s)
    
    ds = mapnik.Shapefile(file='./ne_110m_admin_0_countries/ne_110m_admin_0_countries.shp')

    layer = mapnik.Layer('world')
    # layer.srs = '+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 +wktext +no_defs' # the input projection, it mush be the same as the source's projection
    # '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    layer.datasource = ds
    layer.styles.append('My Style')
    m.layers.append(layer)
    return m 
Пример #18
0
def test_that_coordinates_do_not_overflow_and_polygon_is_rendered():
    expected_color = mapnik.Color('white')
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    ds.add_feature(mapnik.Feature.from_geojson(json.dumps(geojson), context))
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.PolygonSymbolizer()
    sym.fill = expected_color
    sym.clip = False
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer')
    lyr.datasource = ds
    lyr.styles.append('style')
    m = mapnik.Map(256, 256)
    m.background_color = mapnik.Color('black')
    m.append_style('style', s)
    m.layers.append(lyr)
    # 17/20864/45265.png
    m.zoom_to_box(
        mapnik.Box2d(-13658379.710221574, 6197514.253362091,
                     -13657768.213995293, 6198125.749588372))
    # works 15/5216/11316.png
    #m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372))
    im = mapnik.Image(256, 256)
    mapnik.render(m, im)
    eq_(im.get_pixel(128, 128), expected_color.packed())
Пример #19
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)
Пример #20
0
    def save(self, out, format):

        if format not in ('PNG'):
            raise KnownUnknown('We only saves .png tiles, not "%s"' % format)

        if not self.data['has_stuff']:
            im = Image.new('RGBA', (self.width, self.height))
            im.save(out, 'PNG')
            return

        fh, tmpfile = tempfile.mkstemp('.json')

        os.write(fh, json.dumps(self.data['geojson']))
        os.close(fh)

        map = mapnik.Map(0, 0)
        map.srs = '+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'

        datasource = mapnik.Ogr(base=os.path.dirname(tmpfile),
                                file=os.path.basename(tmpfile),
                                layer='OGRGeoJSON')
        os.unlink(tmpfile)

        lyr = mapnik.Layer('xapi_raster')
        lyr.srs = '+proj=latlong +datum=WGS84'
        lyr.datasource = datasource

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

        if self.data['filltype'] == 'line':
            fill = mapnik.Color(str(self.data['fill']))
            # TO DO: make me a config flag
            # rule.symbols.append(mapnik.LineSymbolizer(fill, 1.0))
            rule.symbols.append(mapnik.LineSymbolizer(fill, 3.0))
            style.rules.append(rule)
        else:
            fill = mapnik.Color(str(self.data['fill']))
            rule.symbols.append(mapnik.PolygonSymbolizer(fill))
            style.rules.append(rule)

        map.append_style('xapi_raster', style)

        lyr.styles.append('xapi_raster')
        map.layers.append(lyr)

        xmin, ymin, xmax, ymax = self.data['bbox']
        env = mapnik.Envelope(xmin, ymin, xmax, ymax)

        map.width = self.width
        map.height = self.height
        map.zoom_to_box(env)

        img = mapnik.Image(self.width, self.height)
        mapnik.render(map, img)

        img = Image.fromstring('RGBA', (self.width, self.height),
                               img.tostring())
        img.save(out, 'PNG')
Пример #21
0
def generate_raster(filename, img_size, coordinates, background_color,
                    building_color, config_filename):
    """Generate a raster through requesting a PostGIS database with Mapnik

    Parameters
    ----------
    filename : str
        Output raster path on the file system
    img_size : int
        Size of the desired output image, in pixel (height=width)
    coordinates : dict
        Geographical coordinates of area of interest (west, south, east, north)
    and corresponding geographical projection (SRID)
    background_color : list of 3 ints
        Color of background pixels in [R,G,B]-format
    building_color : list of 3 ints
        Color of building pixels in [R,G,B]-format
    config_filename : str
        Path to the database connexion configuration file

    """
    mapnik_projection = get_mapnik_projection(coordinates["srid"])
    m = mapnik.Map(img_size, img_size, mapnik_projection)
    m.background = mapnik.Color(RGBToHTMLColor(background_color))
    s = mapnik.Style()
    r = mapnik.Rule()
    polygon_symbolizer = mapnik.PolygonSymbolizer()
    polygon_symbolizer.fill = mapnik.Color(RGBToHTMLColor(building_color))
    r.symbols.append(polygon_symbolizer)
    s.rules.append(r)
    m.append_style('building_style', s)

    place_name = filename_sanity_check(filename.split("/")[-1].split(".")[0])
    subquery = ("(SELECT way "
                "FROM {place}_polygon WHERE building='yes') AS building"
                "").format(place=place_name)
    conn_dict = read_config(config_filename)
    postgis_params = {
        'host': conn_dict["host"],
        'port': conn_dict["port"],
        'user': conn_dict["user"],
        'dbname': conn_dict["dbname"],
        'table': subquery,
        'geometry_field': "way",
        'srid': coordinates["srid"],
        'extent_from_subquery': True
    }
    ds = mapnik.PostGIS(**postgis_params)

    layer = mapnik.Layer('buildings')
    layer.datasource = ds
    layer.srs = mapnik_projection
    layer.styles.append('building_style')
    m.layers.append(layer)

    m.zoom_to_box(
        mapnik.Box2d(coordinates['west'], coordinates['south'],
                     coordinates['east'], coordinates['north']))
    mapnik.render_to_file(m, filename, 'tif')
Пример #22
0
def test_polygonsymbolizer_pickle():
    p = mapnik.PolygonSymbolizer(mapnik.Color('black'))
    p.fill_opacity = .5
    # does not work for some reason...
    #eq_(pickle.loads(pickle.dumps(p)), p)
    p2 = pickle.loads(pickle.dumps(p, pickle.HIGHEST_PROTOCOL))
    eq_(p.fill, p2.fill)
    eq_(p.fill_opacity, p2.fill_opacity)
Пример #23
0
def render_image(conn, folder, pic):

	m = mapnik.Map(450,450)
	m.background = mapnik.Color("White")
	r = mapnik.Rule()
	s = mapnik.Style()

	polygon_symbolizer = mapnik.PolygonSymbolizer()
	polygon_symbolizer.fill = mapnik.Color('Grey')
	r.symbols.append(polygon_symbolizer)

	productivi_less_30 = mapnik.Rule()
	productivi_less_30.filter = mapnik.Expression("[productivi]<=30")
	productivi_less_30_polygon_symbolizer = mapnik.PolygonSymbolizer()
	productivi_less_30_polygon_symbolizer.fill = mapnik.Color('#ff5959')
	productivi_less_30.symbols.append(productivi_less_30_polygon_symbolizer)

	productivi_30_70 = mapnik.Rule()
	productivi_30_70.filter = mapnik.Expression("([productivi]>=31) and ([productivi]<70)")
	productivi_30_70_polygon_symbolizer = mapnik.PolygonSymbolizer()
	productivi_30_70_polygon_symbolizer.fill = mapnik.Color('#ffa159')
	productivi_30_70.symbols.append(productivi_30_70_polygon_symbolizer)

	productivi_more_then_70 = mapnik.Rule()
	productivi_more_then_70.filter = mapnik.Expression("[productivi]>=70")
	productivi_more_then_70_polygon_symbolizer = mapnik.PolygonSymbolizer()
	productivi_more_then_70_polygon_symbolizer.fill = mapnik.Color('#d0ff59')
	productivi_more_then_70.symbols.append(productivi_more_then_70_polygon_symbolizer)
	
	s.rules.append(productivi_less_30)
	s.rules.append(productivi_30_70)
	s.rules.append(productivi_more_then_70)

	m.append_style('My Style',s)

	layer = mapnik.Layer("Data from PostGIS")


	layer.datasource = mapnik.PostGIS(dbname=conn[1], host=conn[0], port=conn[2], table = conn[5], user=conn[3], password=conn[4])
	layer.styles.append('My Style')
	m.layers.append(layer)
	m.zoom_all()
	mapnik.render_to_file(m, folder + pic, 'png')

	return pic
Пример #24
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))
Пример #25
0
 def mapnik_style(self):
     polygon_style = mapnik.Style()
     ps = mapnik.PolygonSymbolizer(mapnik.Color('#ffffff'))
     ps.fill_opacity = 0.5
     ls = mapnik.LineSymbolizer(mapnik.Color('#555555'), 0.75)
     ls.stroke_opacity = 0.5
     r = mapnik.Rule()
     r.symbols.append(ps)
     r.symbols.append(ls)
     polygon_style.rules.append(r)
     return polygon_style
Пример #26
0
def setup_highlight_styles(m):
    # highlight styles
    highlight_style = mapnik.Style()
    highlight_rule = mapnik.Rule()

    high_poly_symbolizer = mapnik.PolygonSymbolizer()
    high_poly_symbolizer.fill = mapnik.Color(high_fill)
    highlight_rule.symbols.append(high_poly_symbolizer)

    highlight_style.rules.append(highlight_rule)
    m.append_style('highlight',highlight_style)
    return m
Пример #27
0
def render_tile(layer, z, x, y):
    """
    Render the tile using mapnik.
    """

    m = mapnik.Map(TILE_WIDTH, TILE_WIDTH)

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

    #line_symbolizer = mapnik.PointSymbolizer()
    line_symbolizer = mapnik.PolygonSymbolizer()
    line_symbolizer.fill = mapnik.Color('yellow')
    line_symbolizer.fill_opacity = 0.7
    #line_symbolizer.allow_overlap = True
    #line_symbolizer.transform="scale(5,5)"
    r.symbols.append(line_symbolizer)

    label = mapnik.TextSymbolizer(mapnik.Expression('[nama]'),
                                  'DejaVu Sans Book', 24, mapnik.Color('red'))
    label.halo_radius = 1
    label.avoid_edges = False
    r.symbols.append(label)

    s.rules.append(r)

    m.append_style('My Style', s)

    # Initialize layer from PostGIS table
    ds = mapnik.PostGIS(**POSTGIS_TABLE)
    layer2 = mapnik.Layer(LAYER_NAME)
    layer2.datasource = ds
    layer2.styles.append('My Style')
    m.layers.append(layer2)

    m.zoom_all()

    # ds = mapnik.Shapefile(file='C:\Users\ICS\Documents\kuliah\gis\gis mapnik\pantai indonesia\IND_PNT_polyline.shp')
    # layer = mapnik.Layer(LAYER_NAME)
    # layer.datasource = ds
    # layer.styles.append('My Style')
    # m.layers.append(layer)
    # m.zoom_all()

    renderer = TiledMapRenderer(m)
    im = renderer.render_tile(z, x, y)

    # im = mapnik.Image(TILE_WIDTH, TILE_WIDTH)
    # mapnik.render(m, im, 13, 0, 0)
    # im.save('tmp/bla.png')
    # mapnik.render_to_file(m,'aaa.png', 'png')

    return im.tostring('png'), 200, {'Content-type': 'image/png'}
Пример #28
0
def default_style():
    default_style = mapnik.Style()
    ps = mapnik.PolygonSymbolizer(mapnik.Color('#ffffff'))
    ps.fill_opacity = 0.5
    ls = mapnik.LineSymbolizer(mapnik.Color('#555555'), 0.75)
    ls.stroke_opacity = 0.5
    r = mapnik.Rule()
    r.symbols.append(ps)
    r.symbols.append(ls)
    r.symbols.append(mapnik.PointSymbolizer())
    default_style.rules.append(r)
    return default_style
Пример #29
0
def polygon_symbolizer(style):
    fill_color = "red"
    opacity = 0.6
    if style:
        if 'fill' in style:
            fill_color = str(style['fill'])
        if 'fill-opacity' in style:
            opacity = float(style['fill-opacity'])

    symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(fill_color))
    symbolizer.fill_opacity = opacity

    return symbolizer
Пример #30
0
def defaultPolygonStyle():
    """Returns a default style for polyshape features"""
    s = mapnik.Style()
    r = mapnik.Rule()
    polygon_symbolizer = mapnik.PolygonSymbolizer()
    polygon_symbolizer.fill = DEFAULT_FILL_COLOR
    r.symbols.append(polygon_symbolizer)
    line_symbolizer = mapnik.LineSymbolizer()
    line_symbolizer.stroke = DEFAULT_LINE_COLOR
    line_symbolizer.stroke_width = 0.5
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    return s