示例#1
0
        def __init__(self):
            BaseWMSFactory.__init__(self)
            for data in datas:
                name = data['name']
                title = data['long_name']      
                data = base_path+"/ecohealth/"+name+'.asc'
                
                layer = mapnik.Layer(name,"+init=epsg:4326")
                layer.datasource = mapnik.Gdal(file=str(data),band=1) 
                layer.title = title
                layer.queryable = True
                layer.wms_srs = None
                style = mapnik.Style()
                rule = mapnik.Rule()
                sym = mapnik.RasterSymbolizer()
                sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))
                scale = getEcohealthScale(name)
                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(name,style)
                self.register_layer(layer, name, (name,))
            self.finalize()
示例#2
0
def test_raster_warping_does_not_overclip_source():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file = '../data/raster/dataraster.tif',
            band = 1,
            )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE, mapnik.Color(255,255,0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256,256, mapSrs)
        _map.background=mapnik.Color('white')
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(mapnik.Box2d(3,42,4,43))

        im = mapnik.Image(_map.width,_map.height)
        mapnik.render(_map, im)
        expected_file = './images/support/raster_warping_does_not_overclip_source.png'
        actual_file = '/tmp/' + os.path.basename(expected_file)
        im.save(actual_file,'png32')
        if not os.path.exists(expected_file) or os.environ.get('UPDATE'):
            im.save(expected_file,'png32')
        actual = mapnik.Image.open(actual_file)
        expected = mapnik.Image.open(expected_file)
        eq_(actual.tostring('png32'),expected.tostring('png32'), 'failed comparing actual (%s) and expected (%s)' % (actual_file,expected_file))
示例#3
0
def get_raster_map():
    m = mapnik.Map(map_width, map_height)
    m.background = mapnik.Color('black')
    m.srs = map_srs
    s = mapnik.Style()
    r = mapnik.Rule()
    raster_symbolizer = mapnik.RasterSymbolizer()
    
    raster_symbolizer.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))
    
    raster_symbolizer.colorizer.add_stop(0.0, mapnik.COLORIZER_LINEAR, mapnik.Color("black"))
    raster_symbolizer.colorizer.add_stop(1.0, mapnik.COLORIZER_LINEAR, mapnik.Color("white"))
    


    r.symbols.append(raster_symbolizer)

    s.rules.append(r)

    m.append_style('raster_style', s)

    lyr = mapnik.Layer('urban')
    lyr.datasource = mapnik.Gdal(base='./ne_110m_admin_0_countries', file='urban19901.tif', band=1)
    lyr.styles.append('raster_style')
    m.layers.append(lyr)
    return m
示例#4
0
    def _addStyleToMap(self, m, layerSrs, colorizer=None, band=-1, extent=None,
                       composite=None, nodata=None):
        """
        Add a mapik raster symbolizer to a map.

        :param m: mapnik map.
        :param layerSrs: the layer projection
        :param colorizer: a mapnik colorizer.
        :param band: an integer band number.  -1 for default.
        :param extent: the extent to use for the mapnik layer.
        :param composite: the composite operation to use.  This is one of
            mapnik.CompositeOp.xxx, typically lighten or multiply.
        :param nodata: the value to use for missing data or None to use all
            data.
        """
        styleName = 'Raster Style'
        if band != -1:
            styleName += ' ' + str(band)
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        if colorizer is not None:
            sym.colorizer = colorizer
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        if composite is not None:
            style.comp_op = composite
        m.append_style(styleName, style)
        lyr = mapnik.Layer('layer')
        lyr.srs = layerSrs
        lyr.datasource = mapnik.Gdal(
            base=None, file=self._path, band=band, extent=extent, nodata=nodata)
        lyr.styles.append(styleName)
        m.layers.append(lyr)
示例#5
0
    def to_mapnik(self):
        sym = mapnik.RasterSymbolizer()
        sym.opacity = self.opacity
        sym.mode = self.mode or sym.mode
        sym.scaling = self.scaling or sym.scaling

        return sym
示例#6
0
    def style_map(self, Map):
        style = mapnik.Style()
        rule = mapnik.Rule()

        sym = mapnik.RasterSymbolizer()
        sym.opacity = self.opacity

        colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                           mapnik.Color('white'))
        # colorizer.epsilon = 0.001
        if self.colormap:
            for stop in self.colormap:
                colorizer.add_stop(stop['quantity'],
                                   mapnik.Color(stop['color'].encode('ascii')))

        sym.colorizer = colorizer

        rule.symbols.append(sym)
        style.rules.append(rule)

        Map.append_style('Raster Style', style)

        lyr = mapnik.Layer('GDAL Layer from TIFF', self.layer_srs)

        lyr.datasource = mapnik.Gdal(base=os.path.dirname(self.vrt_path),
                                     file=os.path.basename(self.vrt_path),
                                     band=self.mapnik_band)

        lyr.styles.append('Raster Style')

        Map.layers.append(lyr)

        return Map
示例#7
0
def test_raster_warping():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color(255, 255, 0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256, 256, mapSrs)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        map_proj = mapnik.Projection(mapSrs)
        layer_proj = mapnik.Projection(lyrSrs)
        prj_trans = mapnik.ProjTransform(map_proj, layer_proj)
        _map.zoom_to_box(prj_trans.backward(lyr.envelope()))

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        imdata = im.tostring()
        assert contains_word('\xff\xff\x00\xff', imdata)
示例#8
0
def test_raster_with_alpha_blends_correctly_with_background():
    WIDTH = 500
    HEIGHT = 500

    map = mapnik.Map(WIDTH, HEIGHT)
    WHITE = mapnik.Color(255, 255, 255)
    map.background = WHITE

    style = mapnik.Style()
    rule = mapnik.Rule()
    symbolizer = mapnik.RasterSymbolizer()
    symbolizer.scaling = mapnik.scaling_method.BILINEAR

    rule.symbols.append(symbolizer)
    style.rules.append(rule)

    map.append_style('raster_style', style)

    map_layer = mapnik.Layer('test_layer')
    filepath = '../data/raster/white-alpha.png'
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        map_layer.datasource = mapnik.Gdal(file=filepath)
        map_layer.styles.append('raster_style')
        map.layers.append(map_layer)

        map.zoom_all()

        mim = mapnik.Image(WIDTH, HEIGHT)

        mapnik.render(map, mim)
        imdata = mim.tostring()
        # All white is expected
        eq_(get_unique_colors(mim),['rgba(254,254,254,255)'])
示例#9
0
def test_raster_warping_does_not_overclip_source():
    lyrSrs = "+init=epsg:32630"
    mapSrs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('dataraster', lyrSrs)
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        sym = mapnik.RasterSymbolizer()
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color(255, 255, 0))
        rule = mapnik.Rule()
        rule.symbols.append(sym)
        style = mapnik.Style()
        style.rules.append(rule)
        _map = mapnik.Map(256, 256, mapSrs)
        _map.background = mapnik.Color('white')
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(mapnik.Box2d(3, 42, 4, 43))

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        assert im.view(0, 200, 1, 1).tostring() == '\xff\xff\x00\xff'
示例#10
0
def rgb_style():
    rgb_symb = mapnik.RasterSymbolizer()
    rgb_rule = mapnik.Rule()
    rgb_rule.symbols.append(rgb_symb)
    rgb_style = mapnik.Style()
    rgb_style.rules.append(rgb_rule)
    return rgb_style
示例#11
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",))
示例#12
0
 def create_style(self):
     symbolizer = mapnik.RasterSymbolizer()
     symbolizer.colorizer = self.create_colorizer()
     rule = mapnik.Rule()
     rule.symbols.append(symbolizer)
     style = mapnik.Style()
     style.comp_op = mapnik.CompositeOp.plus
     style.rules.append(rule)
     return style
示例#13
0
def test_multi_tile_policy():
    srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    lyr = mapnik.Layer('raster')
    if 'raster' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Raster(
            file = '../data/raster_tiles/${x}/${y}.tif',
            lox = -180,
            loy = -90,
            hix = 180,
            hiy = 90,
            multi = 1,
            tile_size = 256,
            x_width = 2,
            y_width = 2
            )
        lyr.srs = srs
        _map = mapnik.Map(256, 256, srs)
        style = mapnik.Style()
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        rule.symbols.append(sym)
        style.rules.append(rule)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(lyr.envelope())

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)

        save_data('test_multi_tile_policy.png', im.tostring('png'))

        # test green chunk
        eq_(im.view(0,64,1,1).tostring(), '\x00\xff\x00\xff')
        eq_(im.view(127,64,1,1).tostring(), '\x00\xff\x00\xff')
        eq_(im.view(0,127,1,1).tostring(), '\x00\xff\x00\xff')
        eq_(im.view(127,127,1,1).tostring(), '\x00\xff\x00\xff')

        # test blue chunk
        eq_(im.view(128,64,1,1).tostring(), '\x00\x00\xff\xff')
        eq_(im.view(255,64,1,1).tostring(), '\x00\x00\xff\xff')
        eq_(im.view(128,127,1,1).tostring(), '\x00\x00\xff\xff')
        eq_(im.view(255,127,1,1).tostring(), '\x00\x00\xff\xff')

        # test red chunk
        eq_(im.view(0,128,1,1).tostring(), '\xff\x00\x00\xff')
        eq_(im.view(127,128,1,1).tostring(), '\xff\x00\x00\xff')
        eq_(im.view(0,191,1,1).tostring(), '\xff\x00\x00\xff')
        eq_(im.view(127,191,1,1).tostring(), '\xff\x00\x00\xff')

        # test magenta chunk
        eq_(im.view(128,128,1,1).tostring(), '\xff\x00\xff\xff')
        eq_(im.view(255,128,1,1).tostring(), '\xff\x00\xff\xff')
        eq_(im.view(128,191,1,1).tostring(), '\xff\x00\xff\xff')
        eq_(im.view(255,191,1,1).tostring(), '\xff\x00\xff\xff')
示例#14
0
def test_raster_symbolizer():
    s = mapnik.RasterSymbolizer()
    eq_(s.comp_op, mapnik.CompositeOp.src_over)  # note: mode is deprecated
    eq_(s.scaling, mapnik.scaling_method.NEAR)
    eq_(s.opacity, 1.0)
    eq_(s.colorizer, None)
    eq_(s.filter_factor, -1)
    eq_(s.mesh_size, 16)
    eq_(s.premultiplied, None)
    s.premultiplied = True
    eq_(s.premultiplied, True)
示例#15
0
def test_dataraster_coloring():
    srs = '+init=epsg:32630'
    lyr = mapnik.Layer('dataraster')
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        lyr.srs = srs
        _map = mapnik.Map(256, 256, srs)
        style = mapnik.Style()
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        # Assigning a colorizer to the RasterSymbolizer tells the later
        # that it should use it to colorize the raw data raster
        colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                           mapnik.Color("transparent"))

        for value, color in [
            (0, "#0044cc"),
            (10, "#00cc00"),
            (20, "#ffff00"),
            (30, "#ff7f00"),
            (40, "#ff0000"),
            (50, "#ff007f"),
            (60, "#ff00ff"),
            (70, "#cc00cc"),
            (80, "#990099"),
            (90, "#660066"),
            (200, "transparent"),
        ]:
            colorizer.add_stop(value, mapnik.Color(color))
        sym.colorizer = colorizer
        rule.symbols.append(sym)
        style.rules.append(rule)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(lyr.envelope())

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        expected_file = './images/support/dataraster_coloring.png'
        actual_file = '/tmp/' + os.path.basename(expected_file)
        im.save(actual_file, 'png32')
        if not os.path.exists(expected_file) or os.environ.get('UPDATE'):
            im.save(expected_file, 'png32')
        actual = mapnik.Image.open(actual_file)
        expected = mapnik.Image.open(expected_file)
        eq_(
            actual.tostring('png32'), expected.tostring('png32'),
            'failed comparing actual (%s) and expected (%s)' %
            (actual_file, expected_file))
示例#16
0
文件: wms.py 项目: enermaps/enermaps
    def _get_map(self, normalized_args):
        """Return the Mapnik object (with hardcoded symbology/rule)."""
        # miss:
        # bgcolor
        # exceptions
        projection = parse_projection(normalized_args)
        # validate projection
        size = parse_size(normalized_args)

        mp = mapnik.Map(size.width, size.height, "+init=" + projection)
        # TODO: how do we manage style ? just have hardcoded
        # style list in a dir ?
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.RasterSymbolizer())
        s.rules.append(r)

        r.symbols.append(mapnik.PointSymbolizer())
        s.rules.append(r)

        polygon_symbolizer = mapnik.PolygonSymbolizer()
        polygon_symbolizer.fill = mapnik.Color("black")
        polygon_symbolizer.fill_opacity = 0
        r.symbols.append(polygon_symbolizer)

        line_symbolizer = mapnik.LineSymbolizer()
        line_symbolizer.stroke = mapnik.Color("black")
        line_symbolizer.stroke_width = 1.0
        r.symbols.append(line_symbolizer)
        s.rules.append(r)

        style_name = "My Style"
        mp.append_style(style_name, s)

        # TODO read the background set it
        # mp.background_color = 'steelblue'

        layer_names = parse_layers(normalized_args)
        for layer_name in layer_names:
            try:
                layer = geofile.load(layer_name)
            except FileNotFoundError as e:
                abort(404, e.strerror)
            mapnik_layer = layer.as_mapnik_layer()
            mapnik_layer.styles.append(style_name)
            mp.layers.append(mapnik_layer)
        return mp
示例#17
0
def test_dataraster_coloring():
    srs = '+init=epsg:32630'
    lyr = mapnik.Layer('dataraster')
    if 'gdal' in mapnik.DatasourceCache.plugin_names():
        lyr.datasource = mapnik.Gdal(
            file='../data/raster/dataraster.tif',
            band=1,
        )
        lyr.srs = srs
        _map = mapnik.Map(256, 256, srs)
        style = mapnik.Style()
        rule = mapnik.Rule()
        sym = mapnik.RasterSymbolizer()
        # Assigning a colorizer to the RasterSymbolizer tells the later
        # that it should use it to colorize the raw data raster
        sym.colorizer = mapnik.RasterColorizer(mapnik.COLORIZER_DISCRETE,
                                               mapnik.Color("transparent"))

        for value, color in [
            (0, "#0044cc"),
            (10, "#00cc00"),
            (20, "#ffff00"),
            (30, "#ff7f00"),
            (40, "#ff0000"),
            (50, "#ff007f"),
            (60, "#ff00ff"),
            (70, "#cc00cc"),
            (80, "#990099"),
            (90, "#660066"),
            (200, "transparent"),
        ]:
            sym.colorizer.add_stop(value, mapnik.Color(color))
        rule.symbols.append(sym)
        style.rules.append(rule)
        _map.append_style('foo', style)
        lyr.styles.append('foo')
        _map.layers.append(lyr)
        _map.zoom_to_box(lyr.envelope())

        im = mapnik.Image(_map.width, _map.height)
        mapnik.render(_map, im)
        # save a png somewhere so we can see it
        save_data('test_dataraster_coloring.png', im.tostring('png'))
        imdata = im.tostring()
        # we have some values in the [20,30) interval so check that they're colored
        assert contains_word('\xff\xff\x00\xff', imdata)
示例#18
0
def test_raster_with_alpha_blends_correctly_with_background():
    WIDTH = 500
    HEIGHT = 500

    map = mapnik.Map(WIDTH, HEIGHT)
    WHITE = mapnik.Color(255, 255, 255)
    map.background = WHITE

    style = mapnik.Style()
    rule = mapnik.Rule()
    symbolizer = mapnik.RasterSymbolizer()
    #XXX: This fixes it, see http://trac.mapnik.org/ticket/759#comment:3
    #     (and remove comment when this test passes)
    #symbolizer.scaling="bilinear_old"

    rule.symbols.append(symbolizer)
    style.rules.append(rule)

    map.append_style('raster_style', style)

    map_layer = mapnik.Layer('test_layer')
    filepath = '../data/raster/white-alpha.png'
    if 'gdal' in mapnik.DatasourceCache.instance().plugin_names():
        map_layer.datasource = mapnik.Gdal(file=filepath)
        map_layer.styles.append('raster_style')
        map.layers.append(map_layer)

        map.zoom_all()

        mim = mapnik.Image(WIDTH, HEIGHT)

        mapnik.render(map, mim)
        save_data(
            'test_raster_with_alpha_blends_correctly_with_background.png',
            mim.tostring('png'))
        imdata = mim.tostring()
        # All white is expected
        assert contains_word('\xff\xff\xff\xff', imdata)
示例#19
0
def render_static(request,
                  height=None,
                  width=None,
                  format='png',
                  background='satellite',
                  bounds=None,
                  center=None,
                  render_srid=3857):

    # width and height
    width = int(width)
    height = int(height)
    if width > settings.MAX_IMAGE_DIMENSION or \
        height > settings.MAX_IMAGE_DIMENSION or \
        width <= 1 or height <= 1:
        logging.debug("Invalid size")
        return HttpResponseBadRequest(
            "Invalid image size, both dimensions must be in range %i-%i" %
            (1, settings.MAX_IMAGE_DIMENSION))

# image format
    if format not in IMAGE_FORMATS:
        logging.error("unknown image format %s" % format)
        return HttpResponseBadRequest(
            "Unknown image format, available formats: " +
            ", ".join(IMAGE_FORMATS))

    if format.startswith('png'):
        mimetype = 'image/png'
    elif format.startswith('jpeg'):
        mimetype = 'image/jpeg'

# bounds
    bounds_box = None
    if bounds:
        bounds_components = bounds.split(',')
        if len(bounds_components) != 4:
            return HttpResponseBadRequest(
                "Invalid bounds, must be 4 , separated numbers")
        bounds_components = [float(f) for f in bounds_components]

        if not (-180 < bounds_components[0] <
                180) or not (-180 < bounds_components[2] < 180):
            logging.error("x out of range %f or %f" %
                          (bounds_components[0], bounds_components[2]))
            return HttpResponseBadRequest(
                "x out of range %f or %f" %
                (bounds_components[0], bounds_components[2]))
        if not (-90 < bounds_components[1] <
                90) or not (-90 < bounds_components[3] < 90):
            logging.error("y out of range %f or %f" %
                          (bounds_components[1], bounds_components[3]))
            return HttpResponseBadRequest(
                "y out of range %f or %f" %
                (bounds_components[1], bounds_components[3]))

        ll = Point(bounds_components[0], bounds_components[1], srid=4326)
        ll.transform(render_srid)

        ur = Point(bounds_components[2], bounds_components[3], srid=4326)
        ur.transform(render_srid)
        bounds_box = mapnik.Box2d(ll.x, ll.y, ur.x, ur.y)
    elif center:
        center_components = center.split(',')
        if len(center_components) != 3:
            return HttpResponseBadRequest()
        lon = float(center_components[0])
        lat = float(center_components[1])
        zoom = int(center_components[2])
        # todo calc bounds from center and zoom

# baselayer
    if background not in settings.BASE_LAYERS and background != 'none':
        return HttpResponseNotFound("Background not found")

# GeoJSON post data
    if request.method == "POST" and len(request.body):
        input_data = json.loads(request.body)
    else:
        input_data = None

    if not bounds and not center and not input_data:
        return HttpResponseBadRequest(
            "Bounds, center, or post data is required.")

# initialize map
    m = mapnik.Map(width, height)
    m.srs = '+init=epsg:' + str(render_srid)

    # add a tile source as a background
    if background != "none":
        background_file = settings.BASE_LAYERS[background]
        background_style = mapnik.Style()
        background_rule = mapnik.Rule()
        background_rule.symbols.append(mapnik.RasterSymbolizer())
        background_style.rules.append(background_rule)
        m.append_style('background style', background_style)
        tile_layer = mapnik.Layer('background')
        tile_layer.srs = '+init=epsg:' + str(render_srid)
        tile_layer.datasource = mapnik.Gdal(base=settings.BASE_LAYER_DIR,
                                            file=background_file)
        tile_layer.styles.append('background style')
        m.layers.append(tile_layer)

# add features from geojson
    if input_data and input_data['type'] == "Feature":
        features = [input_data]
    elif input_data and input_data['type'] == "FeatureCollection":
        if 'features' not in input_data:
            return HttpResponseBadRequest()
        features = input_data['features']
    else:
        features = []

    logging.debug("Adding %d features to map" % len(features))

    geometries = []
    point_features = []
    fid = 0
    for feature in features:
        if 'geometry' not in feature:
            logging.debug("feature does not have geometry")
            return HttpResponseBadRequest("Feature does not have a geometry")
        if 'type' not in feature['geometry']:
            logging.debug("geometry does not have type")
            return HttpResponseBadRequest("Geometry does not have a type")

        fid += 1
        style_name = str(fid)

        if feature['geometry']['type'] == 'Point':
            point_features.append(feature)
        elif feature['geometry']['type'] in ('LineString', 'MultiLineString'):
            if feature['geometry']['type'] == 'LineString':
                geos_feature = LineString(feature['geometry']['coordinates'])
            elif feature['geometry']['type'] == 'MultiLineString':
                rings = feature['geometry']['coordinates']
                rings = [[(c[0], c[1]) for c in r] for r in rings]
                if len(rings) == 1:
                    geos_feature = LineString(rings[0])
                else:
                    linestrings = []
                    for ring in rings:
                        try:
                            linestrings.append(LineString(ring))
                        except Exception, e:
                            logging.error("Error adding ring: %s", e)

                    geos_feature = MultiLineString(linestrings)

            geos_feature.srid = 4326
            geos_feature.transform(render_srid)
            geometries.append(geos_feature)

            style = mapnik.Style()
            line_rule = mapnik.Rule()
            style_dict = None
            if 'style' in feature:
                style_dict = feature['style']
            elif 'properties' in feature:
                style_dict = feature['properties']
            line_rule.symbols.append(line_symbolizer(style_dict))
            style.rules.append(line_rule)
            m.append_style(style_name, style)

            wkt = geos_feature.wkt
            line_layer = mapnik.Layer(style_name + ' layer')
            line_layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt +
                                               '"')
            line_layer.styles.append(style_name)
            line_layer.srs = '+init=epsg:' + str(render_srid)
            m.layers.append(line_layer)
        elif feature['geometry']['type'] == 'Polygon':
            geos_feature = GEOSGeometry(json.dumps(feature['geometry']))
            geos_feature.srid = 4326
            geos_feature.transform(render_srid)
            geometries.append(geos_feature)

            style = mapnik.Style()
            rule = mapnik.Rule()
            style_dict = None
            if 'style' in feature:
                style_dict = feature['style']
            elif 'properties' in feature:
                style_dict = feature['properties']
            rule.symbols.append(polygon_symbolizer(style_dict))
            rule.symbols.append(line_symbolizer(style_dict))
            style.rules.append(rule)
            m.append_style(style_name, style)

            wkt = geos_feature.wkt
            layer = mapnik.Layer(style_name + ' layer')
            layer.datasource = mapnik.CSV(inline='wkt\n' + '"' + wkt + '"')
            layer.styles.append(style_name)
            layer.srs = '+init=epsg:' + str(render_srid)
            m.layers.append(layer)
示例#20
0
# -*- coding: utf-8 -*-
print('=' * 40)
print(__file__)
from helper.textool import get_tmp_file

################################################################################
import mapnik
m = mapnik.Map(600, 500, "+proj=latlong +datum=WGS84")
symbol = mapnik.RasterSymbolizer()

################################################################################
s = mapnik.Style()
r = mapnik.Rule()
r.symbols.append(symbol)
s.rules.append(r)
m.append_style('My Style', s)
datasource = mapnik.Gdal(file='/gdata/geotiff_file.tif')
layer = mapnik.Layer("myLayer")
layer.datasource = datasource
layer.styles.append('My Style')
m.layers.append(layer)

################################################################################
layer.envelope()

################################################################################
m.zoom_to_box(layer.envelope())

# mapnik.render_to_file(m, 'xx_mapnik_result.png', 'png')

mapnik.render_to_file(m, get_tmp_file(__file__, '1'), 'png')
示例#21
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')
     expected = 'images/support/pgraster/%s-%s-%s-%s-%s-%s-%s-%s-%s.png' % (
         lyr.name, lbl, pixtype, r, g, b, a, g1, b1)
     compare_images(expected, im)
     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)
示例#22
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')
     expected = 'images/support/pgraster/%s-%s-%s-%s.png' % (lyr.name, lbl,
                                                             pixtype, value)
     compare_images(expected, im)
示例#23
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')
     expected = 'images/support/pgraster/%s-%s-%s-%s-%s-box1.png' % (
         lyr.name, tnam, lbl, overview, clip)
     compare_images(expected, im)
     # 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
     im = mapnik.Image(mm.width, mm.height)
     mapnik.render(mm, im)
     lap = time.time() - t0
     log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
     expected = 'images/support/pgraster/%s-%s-%s-%s-%s-box2.png' % (
         lyr.name, tnam, lbl, overview, clip)
     compare_images(expected, im)
     # 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')
示例#24
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')
        expected = 'images/support/pgraster/%s-%s-%s-%s-box1.png' % (
            lyr.name, lbl, overview, clip)
        compare_images(expected, im)
        # 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
        im = mapnik.Image(mm.width, mm.height)
        mapnik.render(mm, im)
        lap = time.time() - t0
        log('T ' + str(lap) + ' -- ' + lbl + ' E:1/10')
        expected = 'images/support/pgraster/%s-%s-%s-%s-box2.png' % (
            lyr.name, lbl, overview, clip)
        compare_images(expected, im)
        # 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
示例#25
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')
示例#26
0
 def _test_grayscale_subquery(lbl, pixtype, value):
     #
     #      3   8   13
     #    +---+---+---+
     #  3 | v | v | v |  NOTE: writes different color
     #    +---+---+---+        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, 4, 5, %s::float8" \
           "  )," \
           "  6, 11, 5, 4, %s::float8" \
           " ) as \"R\"" \
           ") as foo" % (pixtype,value, val_a, val_b)
     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=1,
                          prescale_rasters=rescale,
                          clip_rasters=clip)
     fs = ds.featureset()
     feature = fs.next()
     eq_(feature['i'], 3)
     lyr = mapnik.Layer('grayscale_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
     h = format(value, '02x')
     hex_v = h + h + h + 'ff'
     h = format(val_a, '02x')
     hex_a = h + h + h + 'ff'
     h = format(val_b, '02x')
     hex_b = h + h + h + 'ff'
     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)
示例#27
0
文件: tms.py 项目: DemersM/Basqui
def tileRaster(request, version, zoom, x, y):
    try:
        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)
        yExtent = _unitsPerPixel(zoom)
        minLong = x * xExtent - 20037508.34
        minLat = y * yExtent - 20037508.34
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent
        if (minLong < -20037508.34 or maxLong > 20037508.34
                or minLat < -20037508.34 or maxLat > 20037508.34):
            raise Http404

        #create de mapnik.map object
        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.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        )
        #defining the feature layer

        datasource = mapnik.Gdal(file="bar_harbour.dem",
                                 base="C:\\Temp\\dem\\",
                                 band=1)

        featureLayer = mapnik.Layer("RasterLayer")
        featureLayer.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"
        featureLayer.datasource = datasource
        featureLayer.styles.append("RasterLayerStyle")

        #defining the feature layer styles
        rule = mapnik.Rule()
        rule.symbols.append(mapnik.RasterSymbolizer())
        style = mapnik.Style()
        style.rules.append(rule)

        #add new feature to the map
        map.append_style("RasterLayerStyle", style)
        map.layers.append(featureLayer)

        #rendering the map tile
        #mapnik.save_map(map, "../tilestache/%s/raster.xml" % str(request.user))

        config = {
            "cache": {
                "name": "Test",
                "path": "../tilestache/%s" % (request.user),
                "umask": "0000",
                "dirs": "portable"
            },
            "layers": {
                "raster": {
                    "provider": {
                        "name":
                        "mapnik",
                        "mapfile":
                        "../tilestache/%s/layers/raster/raster.xml" %
                        (request.user)
                    },
                    "projection": "spherical mercator",
                    "metatile": {
                        "rows": 2,
                        "columns": 2,
                        "buffer": 64
                    },
                    "write cache": False
                }
            }
        }

        # like http://tile.openstreetmap.org/1/0/0.png
        #coord = ModestMaps.Core.Coordinate(y, x, zoom)
        path = "/raster/%s/%s/%s.png" % (zoom, x, y)
        config = TileStache.Config.buildConfiguration(config)
        #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png')
        type, bytes = TileStache.requestHandler(config, path)
        return HttpResponse(bytes, content_type="image/png")

    except:
        traceback.print_exc()
        return HttpResponse("")
示例#28
0
# Script to draw a topo map with mapnik.

import mapnik
srs = '+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs'
m = mapnik.Map(1200, 1200, srs)
m.zoom_to_box(mapnik.Box2d(558800, 5112200, 566600, 5120500))

# Add a GDAL datasource.
topo_lyr = mapnik.Layer('Topo', srs)
topo_raster = mapnik.Gdal(file=r'D:\osgeopy-data\Washington\dem\st_helens.tif')
topo_lyr.datasource = topo_raster

# Use a raster symbolizer.
topo_sym = mapnik.RasterSymbolizer()
topo_rule = mapnik.Rule()
topo_rule.symbols.append(topo_sym)
topo_style = mapnik.Style()
topo_style.rules.append(topo_rule)

m.append_style('topo', topo_style)
topo_lyr.styles.append('topo')

m.layers.append(topo_lyr)
mapnik.render_to_file(m, r'd:\temp\helens.png')
import mapnik


m = mapnik.Map(1000,1000, '+init=epsg:32718') # 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('transparent') # set background colour to 'steelblue'.

s = mapnik.Style() # style object to hold rules
r = mapnik.Rule() # rule object to hold symbolizers

landsatDS = mapnik.Gdal(file='L5TM_086S772W_20090628_TOARefl_RGB_Strd.tif')
landsatLyr = mapnik.Layer('Landsat', '+init=epsg:32718')
landsatLyr.datasource = landsatDS

r.symbols.append(mapnik.RasterSymbolizer())
s.rules.append(r)

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

landsatLyr.styles.append('My Style')

m.layers.append(landsatLyr)

m.zoom_all()
#bbox = mapnik.Envelope(mapnik.Coord(220000.0, 8960000), mapnik.Coord(260000, 9000000))
#m.zoom_to_box(bbox) 

page = mapnik.printing.PDFPrinter(pagesize=(0.20, 0.20), margin=0.0075, resolution=150, preserve_aspect=True, centering=5, is_latlon=False, use_ocg_layers=True)

page.render_map(m,"Map2009Landsat.pdf")
示例#30
0
import mapnik
import time

if __name__ == '__main__':
    start = time.time()
    m = mapnik.Map(256, 256)
    m.srs = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    s = mapnik.Style()
    r = mapnik.Rule()
    raster_symbolizer = mapnik.RasterSymbolizer()

    raster_symbolizer.colorizer = mapnik.RasterColorizer(
        mapnik.COLORIZER_LINEAR, mapnik.Color("transparent"))

    raster_symbolizer.colorizer.add_stop(0.0, mapnik.Color("black"))
    raster_symbolizer.colorizer.add_stop(1.0, mapnik.Color("white"))

    print -9999, raster_symbolizer.colorizer.get_color(-9999)
    print 0.0, raster_symbolizer.colorizer.get_color(0.0)
    print 1.0, raster_symbolizer.colorizer.get_color(1.0)
    print 0, raster_symbolizer.colorizer.get_color(0)
    print 1, raster_symbolizer.colorizer.get_color(1)
    print 0.5, raster_symbolizer.colorizer.get_color(0.5)

    r.symbols.append(raster_symbolizer)

    s.rules.append(r)

    m.append_style('raster_style', s)

    lyr = mapnik.Layer('urban')