Ejemplo n.º 1
0
def ColorFactory(colorstring):
    if re.match('^0x[a-fA-F0-9]{6}$', colorstring):
        return Color(eval('0x' + colorstring[2:4]),
                     eval('0x' + colorstring[4:6]),
                     eval('0x' + colorstring[6:8]))
    else:
        try:
            return Color(colorstring)
        except:
            raise OGCException(
                'Invalid color value. Must be of format "0xFFFFFF", or any format acceptable my mapnik.Color()'
            )
Ejemplo n.º 2
0
def ColorFactory(colorstring):
    if re.match('^0x[a-fA-F0-9]{6}$', colorstring):
        return Color(eval('0x' + colorstring[2:4]),
                     eval('0x' + colorstring[4:6]),
                     eval('0x' + colorstring[6:8]))
    else:
        raise OGCException(
            'Invalid color value. Must be of format "0xFFFFFF".')
Ejemplo n.º 3
0
 def _buildMap(self, params):
     if str(params['crs']) not in self.allowedepsgcodes:
         raise OGCException(
             'Unsupported CRS "%s" requested.' % str(params['crs']).upper(),
             'InvalidCRS')
     if params['bbox'][0] >= params['bbox'][2]:
         raise OGCException(
             "BBOX values don't make sense.  minx is greater than maxx.")
     if params['bbox'][1] >= params['bbox'][3]:
         raise OGCException(
             "BBOX values don't make sense.  miny is greater than maxy.")
     if params.has_key('styles') and len(params['styles']) != len(
             params['layers']):
         raise OGCException('STYLES length does not match LAYERS length.')
     m = Map(params['width'], params['height'], '+init=%s' % params['crs'])
     if params.has_key('transparent') and params['transparent'] == 'FALSE':
         m.background = params['bgcolor']
     else:
         m.background = Color(0, 0, 0, 0)
     maplayers = self.mapfactory.layers
     mapstyles = self.mapfactory.styles
     mapaggregatestyles = self.mapfactory.aggregatestyles
     for layerindex, layername in enumerate(params['layers']):
         try:
             layer = maplayers[layername]
         except KeyError:
             raise OGCException('Layer "%s" not defined.' % layername,
                                'LayerNotDefined')
         reqstyle = params['styles'][layerindex]
         if reqstyle and reqstyle not in layer.wmsextrastyles:
             raise OGCException(
                 'Invalid style "%s" requested for layer "%s".' %
                 (reqstyle, layername), 'StyleNotDefined')
         if not reqstyle:
             reqstyle = layer.wmsdefaultstyle
         if reqstyle in mapaggregatestyles.keys():
             for stylename in mapaggregatestyles[reqstyle]:
                 layer.styles.append(stylename)
         else:
             layer.styles.append(reqstyle)
         for stylename in layer.styles:
             if stylename in mapstyles.keys():
                 m.append_style(stylename, mapstyles[stylename])
             else:
                 raise ServerConfigurationError(
                     'Layer "%s" refers to non-existent style "%s".' %
                     (layername, stylename))
         m.layers.append(layer)
     m.zoom_to_box(
         Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2],
                  params['bbox'][3]))
     return m
Ejemplo n.º 4
0
 def GetMap(self, params):
     if params['bbox'][0] >= params['bbox'][2]:
         raise OGCException(
             "BBOX values don't make sense.  minx is greater than maxx.")
     if params['bbox'][1] >= params['bbox'][3]:
         raise OGCException(
             "BBOX values don't make sense.  miny is greater than maxy.")
     if params.has_key('styles') and len(params['styles']) != len(
             params['layers']):
         raise OGCException('STYLES length does not match LAYERS length.')
     m = Map(params['width'], params['height'])
     if params.has_key('transparent') and params['transparent'] == 'FALSE':
         m.background = params['bgcolor']
     else:
         m.background = Color(0, 0, 0, 0)
     maplayers = self.mapfactory.layers
     mapstyles = self.mapfactory.styles
     for layername in params['layers']:
         try:
             layer = maplayers[layername]
         except KeyError:
             raise OGCException('Layer "%s" not defined.' % layername,
                                'LayerNotDefined')
         for stylename in layer.styles:
             if stylename in mapstyles.keys():
                 m.append_style(stylename, mapstyles[stylename])
             else:
                 raise ServerConfigurationError(
                     'Layer "%s" refers to non-existent style "%s".' %
                     (layername, stylename))
         m.layers.append(layer)
     m.zoom_to_box(
         Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2],
                  params['bbox'][3]))
     im = Image(params['width'], params['height'])
     render(m, im)
     im = fromstring('RGBA', (params['width'], params['height']),
                     rawdata(im))
     fh = StringIO()
     im.save(fh, PIL_TYPE_MAPPING[params['format']], quality=100)
     fh.seek(0)
     return Response(params['format'], fh.read())
#from variables_config import * # Contains shared variables (See http://docs.python.org/faq/programming.html#how-do-i-share-global-variables-across-modules)

# get extent from shp (for mapnik)
from ogr_extent import *

# Retrieve extent and projection using gdal
shp_extent, proj4 = extent_and_proj('departement.shp',
                                    sourcetype='ESRI Shapefile')

import cairo
from mapnik import Style, Rule, Color, Filter, LineSymbolizer, PolygonSymbolizer, TextSymbolizer, label_placement, Shapefile, SQLite, Layer, Map, render, Shapefile, Expression, save_map

map_output = 'france'
m = Map(300, 300, proj4)

m.background = Color('steelblue')

t = TextSymbolizer(Expression('[CODE_DEPT]'), 'DejaVu Sans Book', 8,
                   Color('black'))

f = Expression(
    "[CODE_DEPT]<>'75' and [CODE_DEPT]<>'92' and [CODE_DEPT]<>'93' and [CODE_DEPT]<>'94'"
)
t.allow_overlap = 1
t.label_placement = label_placement.POINT_PLACEMENT
s1 = Style()
r1 = Rule()
r1.symbols.append(t)
r1.filter = f
s1.rules.append(r1)
m.append_style('Text', s1)
Ejemplo n.º 6
0
    def _buildMap(self, params):
        if str(params['crs']) not in self.allowedepsgcodes:
            raise OGCException(
                'Unsupported CRS "%s" requested.' % str(params['crs']).upper(),
                'InvalidCRS')
        if params['bbox'][0] >= params['bbox'][2]:
            raise OGCException(
                "BBOX values don't make sense.  minx is greater than maxx.")
        if params['bbox'][1] >= params['bbox'][3]:
            raise OGCException(
                "BBOX values don't make sense.  miny is greater than maxy.")

        # relax this for now to allow for a set of specific layers (meta layers even)
        # to be used without known their styles or putting the right # of commas...

        #if params.has_key('styles') and len(params['styles']) != len(params['layers']):
        #    raise OGCException('STYLES length does not match LAYERS length.')
        m = Map(params['width'], params['height'], '+init=%s' % params['crs'])

        transparent = params.get('transparent', '').lower() == 'true'

        # disable transparent on incompatible formats
        if transparent and params.get('format', '') == 'image/jpeg':
            transparent = False

        if transparent:
            # transparent has highest priority
            pass
        elif params.has_key('bgcolor'):
            # if not transparent use bgcolor in url
            m.background = params['bgcolor']
        else:
            # if not bgcolor in url use map background
            if mapnik_version() >= 200000:
                bgcolor = self.mapfactory.map_attributes.get('bgcolor', None)
            else:
                bgcolor = self.mapfactory.map_attributes.get(
                    'background-color', None)

            if bgcolor:
                m.background = bgcolor
            else:
                # if not map background defined use white color
                m.background = Color(255, 255, 255, 255)

        if params.has_key('buffer_size'):
            if params['buffer_size']:
                m.buffer_size = params['buffer_size']
        else:
            buffer_ = self.mapfactory.map_attributes.get('buffer_size')
            if buffer_:
                m.buffer_size = self.mapfactory.map_attributes['buffer_size']

        # haiti spec tmp hack! show meta layers without having
        # to request huge string to avoid some client truncating it!
        if params['layers'] and params['layers'][0] in (
                'osm_haiti_overlay', 'osm_haiti_overlay_900913'):
            for layer_obj in self.mapfactory.ordered_layers:
                layer = copy_layer(layer_obj)
                if not hasattr(layer, 'meta_style'):
                    pass
                else:
                    layer.styles.append(layer.meta_style)
                    m.append_style(
                        layer.meta_style,
                        self.mapfactory.meta_styles[layer.meta_style])
                    m.layers.append(layer)
        # a non WMS spec way of requesting all layers
        # uses orderedlayers that preserves original ordering in XML mapfile
        elif params['layers'] and params['layers'][0] == '__all__':
            for layer_obj in self.mapfactory.ordered_layers:
                # if we don't copy the layer here we get
                # duplicate layers added to the map because the
                # layer is kept around and the styles "pile up"...
                layer = copy_layer(layer_obj)
                if hasattr(layer, 'meta_style'):
                    continue
                reqstyle = layer.wmsdefaultstyle
                if reqstyle in self.mapfactory.aggregatestyles.keys():
                    for stylename in self.mapfactory.aggregatestyles[reqstyle]:
                        layer.styles.append(stylename)
                else:
                    layer.styles.append(reqstyle)
                for stylename in layer.styles:
                    if stylename in self.mapfactory.styles.keys():
                        m.append_style(stylename,
                                       self.mapfactory.styles[stylename])
                m.layers.append(layer)
        else:
            for layerindex, layername in enumerate(params['layers']):
                if layername in self.mapfactory.meta_layers:
                    layer = copy_layer(self.mapfactory.meta_layers[layername])
                    layer.styles.append(layername)
                    m.append_style(layername,
                                   self.mapfactory.meta_styles[layername])
                else:
                    try:
                        # uses unordered dict of layers
                        # order based on params['layers'] request which
                        # should be originally informed by order of GetCaps response
                        layer = copy_layer(self.mapfactory.layers[layername])
                    except KeyError:
                        raise OGCException(
                            'Layer "%s" not defined.' % layername,
                            'LayerNotDefined')
                    try:
                        reqstyle = params['styles'][layerindex]
                    except IndexError:
                        reqstyle = ''
                    if len(layer.wmsextrastyles) > 1 and reqstyle == 'default':
                        reqstyle = ''
                    if reqstyle and reqstyle not in layer.wmsextrastyles:
                        raise OGCException(
                            'Invalid style "%s" requested for layer "%s".' %
                            (reqstyle, layername), 'StyleNotDefined')
                    if not reqstyle:
                        reqstyle = layer.wmsdefaultstyle
                    if reqstyle in self.mapfactory.aggregatestyles.keys():
                        for stylename in self.mapfactory.aggregatestyles[
                                reqstyle]:
                            layer.styles.append(stylename)
                    else:
                        layer.styles.append(reqstyle)

                    for stylename in layer.styles:
                        if stylename in self.mapfactory.styles.keys():
                            m.append_style(stylename,
                                           self.mapfactory.styles[stylename])
                        else:
                            raise ServerConfigurationError(
                                'Layer "%s" refers to non-existent style "%s".'
                                % (layername, stylename))

                m.layers.append(layer)
        m.zoom_to_box(
            Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2],
                     params['bbox'][3]))
        return m
Ejemplo n.º 7
0
    def _buildMap(self, params):
        """This variant of buildmap just serves up the map as defined in the
        xml file, plus some customizations from the params. Style and SRS are
        ignored."""
        if str(params['crs']) not in self.allowedepsgcodes:
            raise OGCException(
                'Unsupported CRS "%s" requested.' % str(params['crs']).upper(),
                'InvalidCRS')
        if params['bbox'][0] >= params['bbox'][2]:
            raise OGCException(
                "BBOX values don't make sense.  minx is greater than maxx.")
        if params['bbox'][1] >= params['bbox'][3]:
            raise OGCException(
                "BBOX values don't make sense.  miny is greater than maxy.")

        # There should be only one layer requested.
        if len(params['layers']) <> 1:
            raise OGCException(
                "When specifying a pre-rendered map, only one layer is allowed."
            )

        # retrieve the map object and set width and height.
        # leave srs alone.
        m = self.mapfactory.layers[params['layers'][0]]
        m.width = params['width']
        m.height = params['height']

        transparent = params.get('transparent', '').lower() == 'true'

        # disable transparent on incompatible formats
        if transparent and params.get('format', '') == 'image/jpeg':
            transparent = False

        if transparent:
            # transparent has highest priority
            pass
        elif params.has_key('bgcolor'):
            # if not transparent use bgcolor in url
            m.background = params['bgcolor']
        else:
            # if not bgcolor in url use map background
            if mapnik_version() >= 200000:
                bgcolor = self.mapfactory.map_attributes.get('bgcolor', None)
            else:
                bgcolor = self.mapfactory.map_attributes.get(
                    'background-color', None)

            if bgcolor:
                m.background = bgcolor
            else:
                # if not map background defined use white color
                m.background = Color(255, 255, 255, 255)

        if params.has_key('buffer_size'):
            if params['buffer_size']:
                m.buffer_size = params['buffer_size']
        else:
            buffer_ = self.mapfactory.map_attributes.get('buffer_size')
            if buffer_:
                m.buffer_size = self.mapfactory.map_attributes['buffer_size']

        m.zoom_to_box(
            Box2d(params['bbox'][0], params['bbox'][1], params['bbox'][2],
                  params['bbox'][3]))
        return m