Exemplo n.º 1
0
def test_stroke_dash_arrays():
    s = mapnik.Stroke()
    s.add_dash(1, 2)
    s.add_dash(3, 4)
    s.add_dash(5, 6)

    eq_(s.get_dashes(), [(1, 2), (3, 4), (5, 6)])
Exemplo n.º 2
0
def test_line_symbolizer():
    s = mapnik.LineSymbolizer()
    eq_(s.rasterizer, mapnik.line_rasterizer.FULL)
    eq_(s.smooth, 0.0)
    eq_(s.comp_op, mapnik.CompositeOp.src_over)
    eq_(s.clip, True)
    eq_(s.stroke.width, 1)
    eq_(s.stroke.opacity, 1)
    eq_(s.stroke.color, mapnik.Color('black'))
    eq_(s.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(s.stroke.line_join, mapnik.line_join.MITER_JOIN)

    l = mapnik.LineSymbolizer(mapnik.Color('blue'), 5.0)

    eq_(l.stroke.width, 5)
    eq_(l.stroke.opacity, 1)
    eq_(l.stroke.color, mapnik.Color('blue'))
    eq_(l.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(l.stroke.line_join, mapnik.line_join.MITER_JOIN)

    s = mapnik.Stroke(mapnik.Color('blue'), 5.0)
    l = mapnik.LineSymbolizer(s)

    eq_(l.stroke.width, 5)
    eq_(l.stroke.opacity, 1)
    eq_(l.stroke.color, mapnik.Color('blue'))
    eq_(l.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(l.stroke.line_join, mapnik.line_join.MITER_JOIN)
Exemplo n.º 3
0
def test_linesymbolizer_init():
    l = mapnik.LineSymbolizer()

    eq_(l.stroke.width, 1)
    eq_(l.stroke.opacity, 1)
    eq_(l.stroke.color, mapnik.Color('black'))
    eq_(l.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(l.stroke.line_join, mapnik.line_join.MITER_JOIN)

    l = mapnik.LineSymbolizer(mapnik.Color('blue'), 5.0)

    eq_(l.stroke.width, 5)
    eq_(l.stroke.opacity, 1)
    eq_(l.stroke.color, mapnik.Color('blue'))
    eq_(l.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(l.stroke.line_join, mapnik.line_join.MITER_JOIN)

    s = mapnik.Stroke(mapnik.Color('blue'), 5.0)
    l = mapnik.LineSymbolizer(s)

    eq_(l.stroke.width, 5)
    eq_(l.stroke.opacity, 1)
    eq_(l.stroke.color, mapnik.Color('blue'))
    eq_(l.stroke.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(l.stroke.line_join, mapnik.line_join.MITER_JOIN)
Exemplo n.º 4
0
def test_stroke_dash_api():
    stroke = mapnik.Stroke()
    dashes = [(1.0, 1.0)]
    stroke.dasharray = dashes
    eq_(stroke.dasharray, dashes)
    stroke.add_dash(.1, .1)
    dashes.append((.1, .1))
    eq_(stroke.dasharray, dashes)
Exemplo n.º 5
0
    def to_mapnik(self):
        stroke = mapnik.Stroke(mapnik.Color(str(self.color)), self.width)
        stroke.opacity = self.opacity or stroke.opacity
        stroke.line_cap = self.cap or stroke.line_cap
        stroke.line_join = self.join or stroke.line_join
        sym = mapnik.LineSymbolizer(stroke)

        return sym
Exemplo n.º 6
0
 def singleLineStyle(self, clr, lineThikness=0.1):
     lineS = mapnik.Style()
     r = mapnik.Rule()
     s = mapnik.LineSymbolizer(
         mapnik.Stroke(mapnik.Color(clr), lineThikness))
     r.symbols.append(s)
     lineS.rules.append(r)
     return lineS
Exemplo n.º 7
0
def test_stroke_init():
    s = mapnik.Stroke()

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

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

    eq_(s.width, 5)
    eq_(s.opacity, 1)
    eq_(s.color, mapnik.Color('blue'))
    eq_(s.gamma, .5)
    eq_(s.line_cap, mapnik.line_cap.BUTT_CAP)
    eq_(s.line_join, mapnik.line_join.MITER_JOIN)
Exemplo n.º 8
0
def test_markers_symbolizer():
    p = mapnik.MarkersSymbolizer()
    eq_(p.allow_overlap, False)
    eq_(p.opacity,1.0)
    eq_(p.fill_opacity,None)
    eq_(p.filename,'shape://ellipse')
    eq_(p.placement,mapnik.marker_placement.POINT_PLACEMENT)
    eq_(p.multi_policy,mapnik.marker_multi_policy.EACH)
    eq_(p.fill,None)
    eq_(p.ignore_placement,False)
    eq_(p.spacing,100)
    eq_(p.max_error,0.2)
    eq_(p.width,None)
    eq_(p.height,None)
    eq_(p.transform,'')
    eq_(p.clip,True)
    eq_(p.comp_op,mapnik.CompositeOp.src_over)


    p.width = mapnik.Expression('12')
    p.height = mapnik.Expression('12')
    eq_(str(p.width),'12')
    eq_(str(p.height),'12')

    p.width = mapnik.Expression('[field] + 2')
    p.height = mapnik.Expression('[field] + 2')
    eq_(str(p.width),'([field]+2)')
    eq_(str(p.height),'([field]+2)')

    stroke = mapnik.Stroke()
    stroke.color = mapnik.Color('black')
    stroke.width = 1.0

    p.stroke = stroke
    p.fill = mapnik.Color('white')
    p.allow_overlap = True
    p.opacity = 0.5
    p.fill_opacity = 0.5
    p.placement = mapnik.marker_placement.LINE_PLACEMENT
    p.multi_policy = mapnik.marker_multi_policy.WHOLE

    eq_(p.allow_overlap, True)
    eq_(p.opacity, 0.5)
    eq_(p.fill_opacity, 0.5)
    eq_(p.multi_policy,mapnik.marker_multi_policy.WHOLE)
    eq_(p.placement,mapnik.marker_placement.LINE_PLACEMENT)

    #https://github.com/mapnik/mapnik/issues/1285
    #https://github.com/mapnik/mapnik/issues/1427
    p.marker_type = 'arrow'
    eq_(p.marker_type,'shape://arrow')
    eq_(p.filename,'shape://arrow')
Exemplo n.º 9
0
def line(width=1.0, color=None, dash=None, cap=None):
    stroke = mapnik.Stroke()
    if color is not None:
        stroke.color = color
    if dash is not None:
        stroke.add_dash(dash[0], dash[1])
    if cap is None:
        stroke.line_cap = mapnik.line_cap.ROUND_CAP
    elif cap == 'butt':
        stroke.line_cap = mapnik.line_cap.BUTT_CAP
    elif cap == 'square':
        stroke.line_cap = mapnik.line_cap.SQUARE_CAP
    stroke.line_join = mapnik.line_join.ROUND_JOIN
    stroke.width = width

    return mapnik.LineSymbolizer(stroke)
Exemplo n.º 10
0
def create_roi_output_style(attr_name):
    qgis_style_file = os.path.join(os.path.dirname(__file__),
                                   "plot_data/roi_pred_classes_4.qml")
    symbols = {}

    with open(qgis_style_file, 'rb') as qsf:
        doc = etree.parse(qsf)
        for range in doc.xpath('//range'):
            upper = range.attrib['upper']
            lower = range.attrib['lower']
            label = range.attrib['label']
            symbol = range.attrib['symbol']
            symbols[symbol] = {
                "lower": float(lower),
                "upper": float(upper),
                "label": str(label),
            }

        for node in doc.xpath("//prop[@k='color']"):
            layer = node.getparent()
            sym = layer.getparent()
            sym_name = sym.attrib['name']
            str_color = node.attrib["v"]
            c = str_color.split(",")
            symbols[sym_name]["color"] = mapnik.Color(
                "rgb(%d,%d,%d)" % (int(c[0]), int(c[1]), int(c[2])))

    style = mapnik.Style()

    for sname in symbols:
        r = mapnik.Rule()
        psym = mapnik.MarkersSymbolizer()
        psym.fill = symbols[sname]["color"]
        psym.width = mapnik.Expression('6')
        psym.height = mapnik.Expression('6')
        psym.stroke = mapnik.Stroke(mapnik.Color('white'), 0)
        r.symbols.append(psym)

        upper = symbols[sname]["upper"]
        lower = symbols[sname]["lower"]
        f = mapnik.Filter("[%s] >= %f and [%s] < %f" %
                          (attr_name, lower, attr_name, upper))
        r.filter = f

        style.opacity = 0.8
        style.rules.append(r)
    return style
Exemplo n.º 11
0
def test_stroke_pickle():
    s = mapnik.Stroke(mapnik.Color('black'), 4.5)

    eq_(s.width, 4.5)
    eq_(s.color, mapnik.Color('black'))

    s.add_dash(1, 2)
    s.add_dash(3, 4)
    s.add_dash(5, 6)

    s2 = pickle.loads(pickle.dumps(s, pickle.HIGHEST_PROTOCOL))
    eq_(s.color, s2.color)
    eq_(s.width, s2.width)
    eq_(s.opacity, s2.opacity)
    eq_(s.get_dashes(), s2.get_dashes())
    eq_(s.line_cap, s2.line_cap)
    eq_(s.line_join, s2.line_join)
Exemplo n.º 12
0
def calc_stroke(value, max_value):
    """ Return the mapnik.Stroke to use for drawing a given heatmap value.

        'value' will be between 0 and 'max_value'.
    """
    fraction = float(value) / float(max_value)  # 0..1.

    def interpolate(start_value, end_value, fraction):
        return start_value + (end_value - start_value) * fraction

    r = interpolate(0.7, 0.0, fraction)
    g = interpolate(0.7, 0.0, fraction)
    b = interpolate(1.0, 0.4, fraction)

    color = mapnik.Color(int(r * 255), int(g * 255), int(b * 255))
    width = max(4.0 * fraction, 1.5)

    return mapnik.Stroke(color, width)
Exemplo n.º 13
0
    def to_mapnik(self):
        line_caps = {'butt': mapnik.line_cap.BUTT_CAP,
                     'round': mapnik.line_cap.ROUND_CAP,
                     'square': mapnik.line_cap.SQUARE_CAP}

        line_joins = {'miter': mapnik.line_join.MITER_JOIN,
                      'round': mapnik.line_join.ROUND_JOIN,
                      'bevel': mapnik.line_join.BEVEL_JOIN}
    
        stroke = mapnik.Stroke(mapnik.Color(str(self.color)), self.width)
        stroke.opacity = self.opacity or stroke.opacity
        stroke.line_cap = self.cap and line_caps[self.cap] or stroke.line_cap
        stroke.line_join = self.join and line_joins[self.join] or stroke.line_join
        if self.dashes:
            stroke.add_dash(*self.dashes.values)
        sym = mapnik.LineSymbolizer(stroke)
        
        return sym
Exemplo n.º 14
0
def test_markersymbolizer_init():
    p = mapnik.MarkersSymbolizer()
    eq_(p.allow_overlap, False)
    eq_(p.opacity, 1)
    eq_(p.filename, '')
    eq_(p.marker_type, mapnik.marker_type.ARROW)
    eq_(p.placement, mapnik.marker_placement.LINE_PLACEMENT)
    eq_(p.fill, mapnik.Color(0, 0, 255))
    eq_(p.ignore_placement, False)
    eq_(p.spacing, 100)
    eq_(p.max_error, 0.2)

    stroke = mapnik.Stroke()
    stroke.color = mapnik.Color('black')
    stroke.width = 1.0

    p.stroke = stroke
    p.fill = mapnik.Color('white')
    p.allow_overlap = True
    p.opacity = 0.5

    eq_(p.allow_overlap, True)
    eq_(p.opacity, 0.5)
Exemplo n.º 15
0
def line_symbolizer(style):
    line_symbolizer = mapnik.LineSymbolizer()

    stroke_color = "red"
    stroke_width = 2
    if style:
        if 'stroke' in style:
            stroke_color = str(style['stroke'])
        if 'stroke-width' in style:
            stroke_width = float(style['stroke-width'])

    stroke = mapnik.Stroke(mapnik.Color(stroke_color), stroke_width)
    if style:
        if 'opacity' in style:
            stroke.opacity = float(style['opacity'])
        if 'stroke-dasharray' in style:
            dasharray = [float(d) for d in style['stroke-dasharray']]
            while len(dasharray) >= 2:
                length, gap = dasharray.pop(0), dasharray.pop(0)
                stroke.add_dash(length, gap)
        if 'stroke-linejoin' in style:
            if style['stroke-linejoin'] in LINEJOIN_OPTIONS:
                stroke.linejoin = LINEJOIN_OPTIONS[style['stroke-linejoin']]
            else:
                raise InvalidStyleException()
        if 'stroke-linecap' in style:
            if style['stroke-linecap'] in LINECAP_OPTIONS:
                stroke.linecap = LINECAP_OPTIONS[style['stroke-linecap']]
            else:
                return InvalidStyleException()

    line_symbolizer.stroke = stroke

    if style and 'smooth' in style:
        line_symbolizer.smooth = float(style['smooth'])

    return line_symbolizer
Exemplo n.º 16
0
precinct_style = mapnik.Style()
roads_style = mapnik.Style()

for precinct in range(1, 53):
    the_filter = '[PRECINCT] = {0}'.format(precinct)
    color = GREEN if winners[precinct] == HOWZE else RED

    rule = mapnik.Rule()
    rule.filter = mapnik.Filter(the_filter)
    symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(color))
    rule.symbols.append(symbolizer)
    precinct_style.rules.append(rule)

    symbolizer = mapnik.LineSymbolizer()
    symbolizer.stroke = mapnik.Stroke(mapnik.Color("#000000"), 1)
    rule.symbols.append(symbolizer)
    precinct_style.rules.append(rule)

layer1 = mapnik.Layer("Precinct Layer")
layer1.datasource = mapnik.Shapefile(file="data/Voter_Precinct.shp")
layer1.styles.append("Map Style")

columbia_pike_area = [201, 323, 324, 325, 326, 327, 331, 332, 334]
columbia_pike_area += [335, 338, 376, 457, 466, 467]

for roads in columbia_pike_area:
    the_filter = '[OBJECTID] = {0}'.format(roads)

    rule = mapnik.Rule()
    rule.filter = mapnik.Filter(the_filter)
Exemplo n.º 17
0
def tileMapConfig(map_id):

    map_selected = BasquiMap.objects.get(pk=map_id)
    layersMapOptions = LayerMapOptions.objects.filter(
        basqui_map=map_selected).order_by('-position')
    layers_used = Shapefile.objects.filter(
        Q(layermapoptions__basqui_map=map_selected),
        Q(layermapoptions__style_visible=True)
        | Q(layermapoptions__label_visible=True))

    mapXML = 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"
    )
    mapXML.buffer_size = 128

    if len(layers_used) > 0:
        query = """(SELECT shapefile_id, coalesce(geom_multipoint, geom_multilinestring, geom_multipolygon) as g
                    %s
                    FROM layers_feature WHERE shapefile_id IN (%s)
                    AND (geom_multipoint && !bbox! OR geom_multilinestring && !bbox! OR geom_multipolygon && !bbox! )
                    ) as geom""" % (''.join([
            ",attribute_value->'" + label.field.name + "' as " +
            str(label.field.name).lower() + "_" + str(label.pk)
            for x in layersMapOptions.filter(label_visible=True)
            for label in x.layerlabel_set.all()
        ]).replace(',None', ''), ','.join([str(x.pk) for x in layers_used]))

        #','.join(["attribute_value->'" + x.label.field.name +"'" if x.label is not None else 'None' for x in layersMapOptions ]).replace(',None',''),

        datasource = mapnik.PostGIS(
            host=dbSettings['HOST'],
            user=dbSettings['USER'],
            password=dbSettings['PASSWORD'],
            dbname=dbSettings['NAME'],
            port=dbSettings['PORT'],
            table=query,
            geometry_field='g',
            #extent_from_subquery=True,
            estimate_extent=False,
            srid=3857,
            extent='-20037508.34, -20037508.34, 20037508.34, 20037508.34',
            simplify_geometries=True,
            geometry_table='layers_feature')

        featureLayer = mapnik.Layer("tiled_layer")
        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.cache_features = True

        #defining the feature layer styles
        for layerMapOptions in layersMapOptions.filter(style_visible=True):
            layerStyles = layerMapOptions.layerstyle_set.all().order_by(
                '-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(
                str(layer.name) + '_Styles_' + str(layerMapOptions.pk))
            layer_style = mapnik.Style()
            for layerStyle in layerStyles:
                style_rule = mapnik.Rule()
                if layerStyle.filter:
                    style_rule.filter = mapnik.Filter(
                        "[shapefile_id] = %s and (%s)" %
                        (layer.pk, str(layerStyle.filter)))
                else:
                    style_rule.filter = mapnik.Filter("[shapefile_id] = %s" %
                                                      layer.pk)
                if layerStyle.minScale:
                    style_rule.min_scale = layerStyle.minScale
                if layerStyle.maxScale:
                    style_rule.max_scale = layerStyle.maxScale
                if layer.geom_type in ["Point", "MultiPoint"]:
                    m = mapnik.MarkersSymbolizer()
                    m.filename = os.path.abspath("../media/%s" %
                                                 layerStyle.marker.svg)
                    m.fill = mapnik.Color(str(layerStyle.fill))
                    m.fill_opacity = layerStyle.fill_opacity
                    s = mapnik.Stroke()
                    s.color = mapnik.Color(str(layerStyle.stroke_color))
                    s.width = layerStyle.stroke_width
                    s.opacity = layerStyle.stroke_opacity
                    m.stroke = s
                    if layerStyle.transform:
                        m.transform = str(layerStyle.transform)
                    m.allow_overlap = layerStyle.allow_overlap
                    m.spacing = layerStyle.spacing
                    m.max_error = layerStyle.max_error
                    #m.placement = mapnik.marker_placement(layerStyle.placement)
                    #m.ignore_placement = layerStyle.ignore_placement
                    style_rule.symbols.append(m)
                elif layer.geom_type in ["LineString", "MultiLineString"]:
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.width = layerStyle.stroke_width
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.line_join = mapnik.line_join(
                        layerStyle.stroke_linejoin)
                    l.stroke.line_cap = mapnik.line_cap(
                        layerStyle.stroke_linecap)
                    if layerStyle.dash_array:
                        dash_array = [
                            tuple(float(i) for i in el.strip('()').split(','))
                            for el in layerStyle.dash_array.split('),(')
                        ]
                        for d in dash_array:
                            l.stroke.add_dash(d[0], d[1])
                    l.stroke.gamma = layerStyle.gamma
                    l.stroke.gamma_method = mapnik.gamma_method(
                        layerStyle.gamma_method)
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.rasterizer = mapnik.line_rasterizer(
                        layerStyle.stroke_rasterizer)
                    style_rule.symbols.append(l)
                elif layer.geom_type in ["Polygon", "MultiPolygon"]:
                    p = mapnik.PolygonSymbolizer()
                    p.fill = mapnik.Color(str(layerStyle.fill))
                    p.fill_opacity = layerStyle.fill_opacity
                    p.clip = layerStyle.clip
                    p.gamma = layerStyle.gamma
                    p.gamme_method = mapnik.gamma_method(
                        layerStyle.gamma_method)
                    p.smooth = layerStyle.smooth
                    p.simplify_tolerance = layerStyle.simplify_tolerance
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.width = layerStyle.stroke_width
                    if layerStyle.dash_array:
                        dash_array = [
                            tuple(float(i) for i in el.strip('()').split(','))
                            for el in layerStyle.dash_array.split('),(')
                        ]
                        for d in dash_array:
                            l.stroke.add_dash(d[0], d[1])
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.stroke.gamma = layerStyle.gamma
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    style_rule.symbols.append(p)
                    style_rule.symbols.append(l)
                layer_style.rules.append(style_rule)
            mapXML.append_style(
                str(layer.name) + '_Styles_' + str(layerMapOptions.pk),
                layer_style)

            #defining label styles
        for layerMapOptions in layersMapOptions.filter(label_visible=True):
            layerLabels = layerMapOptions.layerlabel_set.all().order_by(
                '-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(
                str(layer.name) + '_Label_' + str(layerMapOptions.pk))
            label_style = mapnik.Style()
            for layerLabel in layerLabels:
                label_rule = mapnik.Rule()
                if layerLabel.filter:
                    label_rule.filter = mapnik.Filter(
                        "[shapefile_id] = %s and (%s)" %
                        (layer.pk, str(layerLabel.filter)))
                else:
                    label_rule.filter = mapnik.Filter("[shapefile_id] = %s" %
                                                      layer.pk)
                if layerLabel.minScale:
                    label_rule.min_scale = layerLabel.minScale
                if layerLabel.maxScale:
                    label_rule.max_scale = layerLabel.maxScale
                label_column = '[%s_%s]' % (str(
                    layerLabel.field).lower(), str(layerLabel.pk))
                t = mapnik.TextSymbolizer(mapnik.Expression(label_column),
                                          str(layerLabel.face_name),
                                          layerLabel.size,
                                          mapnik.Color(str(layerLabel.fill)))
                t.halo_fill = mapnik.Color(str(layerLabel.halo_fill))
                t.halo_radius = layerLabel.halo_radius
                t.halo_rasterizer = mapnik.halo_rasterizer(
                    layerLabel.halo_rasterizer)
                t.opacity = layerLabel.opacity
                t.character_spacing = layerLabel.character_spacing
                t.line_spacing = layerLabel.line_spacing
                t.text_ratio = layerLabel.text_ratio
                t.text_transform = mapnik.text_transform(
                    layerLabel.text_transform)
                t.clip = layerLabel.clip
                t.label_placement = mapnik.label_placement(
                    layerLabel.label_placement)
                t.vertical_alignment = mapnik.vertical_alignment(
                    layerLabel.vertical_alignment)
                t.horizontal_alignment = mapnik.horizontal_alignment(
                    layerLabel.horizontal_alignment)
                t.justify_alignment = mapnik.justify_alignment(
                    layerLabel.justify_alignment)
                t.displacement = (layerLabel.dx, layerLabel.dy)
                t.orientation = mapnik.Expression(str(layerLabel.orientation))
                t.rotate_displacement = layerLabel.rotate_displacement
                t.label_position_tolerance = layerLabel.label_position_tolerance
                t.avoid_edges = layerLabel.avoid_edges
                t.minimum_padding = layerLabel.minimum_padding
                t.allow_overlap = layerLabel.allow_overlap
                t.minimum_distance = layerLabel.minimum_distance
                t.repeat_distance = mapnik.Expression(
                    str(layerLabel.repeat_distance))
                t.minimum_path_length = layerLabel.minimum_path_length
                t.maximum_angle_char_delta = layerLabel.maximum_angle_char_delta
                t.wrap_width = layerLabel.wrap_width
                if layerLabel.wrap_character:
                    t.wrap_character = ord(layerLabel.wrap_character)
                t.wrap_before = layerLabel.wrap_before
                label_rule.symbols.append(t)
                label_style.rules.append(label_rule)
            mapXML.append_style(
                str(layer.name) + '_Label_' + str(layerMapOptions.pk),
                label_style)

        mapXML.layers.append(featureLayer)

    #saving the map mapnik xml
    mapnik_xml_path = "../tilestache/%s/maps/viewer/%s_%s.xml" % (str(
        map_selected.created_by.username), str(
            map_selected.name), str(map_selected.pk))
    mapnik.save_map(mapXML, mapnik_xml_path)
Exemplo n.º 18
0
 key = prop.replace('-', '_')
 if key == 'file':
     key = 'filename'
 if sym_name == 'Line' and 'stroke' in key:
     stroke_instance = instance_var.stroke
     if key == 'stroke':
         key = 'color'
     else:
         key = key.replace('stroke_', '')
     if not hasattr(stroke_instance, key):
         fails.append("'%s' not a valid property of %s" %
                      (key, 'Stroke'))
 elif sym_name == 'Markers' and 'stroke' in key:
     stroke_instance = instance_var.stroke
     if not stroke_instance:  # marker.stroke is boost::optional
         stroke_instance = mapnik.Stroke()
     if key == 'stroke':
         key = 'color'
     else:
         key = key.replace('stroke_', '')
     if not hasattr(stroke_instance, key):
         fails.append("'%s' not a valid property of %s" %
                      (key, 'Stroke'))
 else:
     # temporary hotfix until: https://github.com/mapnik/mapnik/issues/1427
     if sym_name in ['Text', 'Shield']:
         if key in text_fixups:
             key = text_fixups[key]
     if not hasattr(instance_var, key):
         fails.append("'%s' not a valid property of %s" %
                      (key, sym_name))
Exemplo n.º 19
0
ondrain_lyr = mapnik.Layer('Ontario Hydrography')
ondrain_lyr.srs = "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"
ondrain_lyr.datasource = mapnik.Shapefile(file='../data/ontdrainage')

ondrain_lyr.styles.append('drainage')
m.layers.append(ondrain_lyr)

# Provincial boundaries

provlines_lyr = mapnik.Layer('Provincial borders')
provlines_lyr.srs = "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs"
provlines_lyr.datasource = mapnik.Shapefile(file='../data/boundaries_l')

# Here we define a "dash dot dot dash" pattern for the provincial boundaries.

provlines_stk = mapnik.Stroke()
provlines_stk.add_dash(8, 4)
provlines_stk.add_dash(2, 2)
provlines_stk.add_dash(2, 2)
provlines_stk.color = mapnik.Color('black')
provlines_stk.width = 1.0

provlines_style = mapnik.Style()
provlines_rule = mapnik.Rule()
provlines_rule.symbols.append(mapnik.LineSymbolizer(provlines_stk))
provlines_style.rules.append(provlines_rule)

m.append_style('provlines', provlines_style)
provlines_lyr.styles.append('provlines')
m.layers.append(provlines_lyr)
Exemplo n.º 20
0
#water
s_water = mapnik.Style()
r_water = mapnik.Rule()
r_water.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('steelblue')))
#r_water.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
s_water.rules.append(r_water)
m.append_style('water', s_water)
l_water = mapnik.Layer('water', "+proj=latlong +datum=WGS84")
l_water.datasource = mapnik.Shapefile(file='target/export/natural-water')
l_water.styles.append('water')

#highways
s_highway = mapnik.Style()
r_highway = mapnik.Rule()
road_stroke = mapnik.Stroke()
road_stroke.width = 2.0
#dashed lines
#road_stroke.add_dash(8, 4)
#road_stroke.add_dash(2, 2)
#road_stroke.add_dash(2, 2)
road_stroke.color = mapnik.Color('yellow')
road_stroke.line_cap = mapnik.line_cap.ROUND_CAP
#r_highway.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('yellow')))
r_highway.symbols.append(mapnik.LineSymbolizer(road_stroke))
s_highway.rules.append(r_highway)
m.append_style('highway', s_highway)
l_highway = mapnik.Layer('highway', "+proj=latlong +datum=WGS84")
l_highway.datasource = mapnik.Shapefile(file='target/export/highway')
l_highway.styles.append('highway')
m.append_style('highway', s_highway)
Exemplo n.º 21
0
    def mapnik_output(self, min_x, min_y, max_x, max_y, epsg, multi_poly_proj, union_line, noConsultationDuTeleservice):
        """Fonction creer une sortie carto"""
        mapnik_x_y = self.mapnik_config(min_x, min_y, max_x, max_y)
        sizex = mapnik_x_y[0]
        sizey = mapnik_x_y[1]
        m = mapnik.Map(sizey, sizex, '+init=epsg:' + str(epsg))

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

        #si la couche du grid existe, on l'utilise
        if os.path.exists(os.path.join(os.path.abspath(os.path.dirname(__file__)), "temp" + os.sep + "grid.shp")):
            provpoly_lyr = mapnik.Layer('Atlas', '+init=epsg:' + str(epsg))
            path_temp = os.path.join(os.path.abspath(os.path.dirname(__file__)), "temp" + os.sep)
            provpoly_lyr.datasource = mapnik.Shapefile(file=path_temp + 'grid', encoding='latin1')
            provpoly_style = mapnik.Style()
            provpoly_rule_qc = mapnik.Rule()
            provpoly_rule_qc.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color(217, 235, 203)))
            provpoly_style.rules.append(provpoly_rule_qc)
            m.append_style('atlas', provpoly_style)
            provpoly_lyr.styles.append('atlas')
            m.layers.append(provpoly_lyr)

        s_wkt_poly = mapnik.Style()
        r_wkt_poly = mapnik.Rule()
        wkt_polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#FF3366'))
        r_wkt_poly.symbols.append(wkt_polygon_symbolizer)
        wkt_line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('#000'), 1.0)
        r_wkt_poly.symbols.append(wkt_line_symbolizer)
        s_wkt_poly.rules.append(r_wkt_poly)
        m.append_style('Travaux', s_wkt_poly)
        wkt_poly_geom = multi_poly_proj
        csv_string_wkt_poly = '''
                 wkt,Name
                "%s","test"
                ''' % wkt_poly_geom
        ds_wkt_poly = mapnik.Datasource(**{"type": "csv", "inline": csv_string_wkt_poly})
        layer_wkt_poly = mapnik.Layer('Travaux', '+init=epsg:' + str(epsg))
        layer_wkt_poly.datasource = ds_wkt_poly
        layer_wkt_poly.styles.append('Travaux')
        m.layers.append(layer_wkt_poly)

        wkt_line_geom = union_line
        csv_string_wkt_line_geom = '''
                 wkt,Name
                "%s","test"
                ''' % wkt_line_geom
        wkt_line_geom_ds = mapnik.Datasource(**{"type": "csv", "inline": csv_string_wkt_line_geom})
        wkt_line_layer = mapnik.Layer('Reseau', '+init=epsg:' + str(epsg))
        wkt_line_layer.datasource = wkt_line_geom_ds
        wkt_line_style = mapnik.Style()
        wkt_line_rule = mapnik.Rule()
        wkt_line = mapnik.Stroke()
        wkt_line.color = mapnik.Color(171, 158, 137)
        wkt_line.width = 2.0
        wkt_line_rule.symbols.append(mapnik.LineSymbolizer(wkt_line))
        wkt_line_style.rules.append(wkt_line_rule)
        m.append_style('reseau', wkt_line_style)
        wkt_line_layer.styles.append('reseau')
        m.layers.append(wkt_line_layer)

        #m.zoom_all()
        m.zoom_to_box(mapnik.Box2d(min_x, min_y, max_x, max_y))
        mapnik_output = mapnik.render_to_file(m, os.path.join(os.path.abspath(os.path.dirname(__file__)), "output" + os.sep + "plan_" + noConsultationDuTeleservice + ".png"), 'png')
        #mapnik_output = mapnik.render_to_file(m, 'plan_' + noConsultationDuTeleservice + '.png', 'png')
        return mapnik_output
Exemplo n.º 22
0
map_canvas.background = mapnik.Color('rgb(0,0,0,0)')  # transparent

# Create a symbolizer to draw the points
style = mapnik.Style()
rule = mapnik.Rule()
point_symbolizer = mapnik.MarkersSymbolizer()
point_symbolizer.allow_overlap = True
point_symbolizer.opacity = 0.5  # semi-transparent
rule.symbols.append(point_symbolizer)
style.rules.append(rule)
map_canvas.append_style('GPS_tracking_points', style)

# Create a symbolizer to draw the lines
style = mapnik.Style()
rule = mapnik.Rule()
track_stk = mapnik.Stroke()
track_stk.width = 5
line_symbolizer = mapnik.LineSymbolizer(track_stk)
line_symbolizer.smooth = 1
rule.symbols.append(line_symbolizer)
style.rules.append(rule)
map_canvas.append_style('GPS_tracking_line', style)

# Create a layer to hold the ponts
layer = mapnik.Layer('GPS_tracking_line')
layer.datasource = mapnik.Ogr(file="route.kml", layer_by_index=1)
layer.styles.append('GPS_tracking_line')
map_canvas.layers.append(layer)

# Create a layer to hold the ponts
layer = mapnik.Layer('GPS_tracking_points')
def generateMap(tableName,
                minX,
                minY,
                maxX,
                maxY,
                mapWidth,
                mapHeight,
                hiliteExpr=None,
                points=None):

    extent = "{},{},{},{}".format(minX, minY, maxX, maxY)

    layer = mapnik.Layer("Layer")
    layer.datasource = mapnik.PostGIS(dbname="distal",
                                      table=tableName,
                                      user="******",
                                      password="******",
                                      extent=extent,
                                      geometry_field="outline",
                                      srid=4326)

    map = mapnik.Map(mapWidth, mapHeight, '+proj=longlat +datum=WGS84')
    map.background = mapnik.Color("#8080a0")

    style = mapnik.Style()

    rule = mapnik.Rule()
    if hiliteExpr != None:
        rule.filter = mapnik.Filter(hiliteExpr)

    rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#408000")))
    rule.symbols.append(
        mapnik.LineSymbolizer(mapnik.Stroke(mapnik.Color("#000000"), 0.1)))

    style.rules.append(rule)

    rule = mapnik.Rule()
    rule.set_else(True)

    rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color("#a0a0a0")))
    rule.symbols.append(
        mapnik.LineSymbolizer(mapnik.Stroke(mapnik.Color("#404040"), 0.1)))

    style.rules.append(rule)

    map.append_style("Map Style", style)
    layer.styles.append("Map Style")
    map.layers.append(layer)

    if points != None:
        memoryDatasource = mapnik.MemoryDatasource()
        context = mapnik.Context()
        context.push("name")
        next_id = 1
        for long, lat, name in points:
            wkt = "POINT (%0.8f %0.8f)" % (long, lat)
            feature = mapnik.Feature(context, next_id)
            feature['name'] = name
            feature.add_geometries_from_wkt(wkt)
            next_id = next_id + 1
            memoryDatasource.add_feature(feature)

        layer = mapnik.Layer("Points")
        layer.datasource = memoryDatasource

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

        pointImgFile = os.path.join(os.path.dirname(__file__), "point.png")

        shield = mapnik.ShieldSymbolizer(mapnik.Expression('[name]'),
                                         "DejaVu Sans Bold", 10,
                                         mapnik.Color("#000000"),
                                         mapnik.PathExpression(pointImgFile))
        shield.displacement = (0, 7)
        shield.unlock_image = True
        rule.symbols.append(shield)

        style.rules.append(rule)

        map.append_style("Point Style", style)
        layer.styles.append("Point Style")

        map.layers.append(layer)

    map.zoom_to_box(mapnik.Envelope(minX, minY, maxX, maxY))

    scriptDir = os.path.dirname(__file__)
    cacheDir = os.path.join(scriptDir, "..", "mapCache")
    if not os.path.exists(cacheDir):
        os.mkdir(cacheDir)
    fd, filename = tempfile.mkstemp(".png", dir=cacheDir)
    os.close(fd)

    mapnik.render_to_file(map, filename, "png")

    return "../mapCache/" + os.path.basename(filename)
Exemplo n.º 24
0
shpStyle.rules.append(building203)

building204 = mapnik.Rule()
filter204 = mapnik.Filter("[DLBM]='204' or [DLBM]='205'")
building204.filter = filter204
building204.symbols.append(
    mapnik.PolygonSymbolizer(mapnik.Color("rgb(230,120,130)")))
shpStyle.rules.append(building204)

lineStyle = mapnik.Style()
lineStyle.filter_mode = mapnik.filter_mode.FIRST
line104 = mapnik.Rule()
lineFilter104 = mapnik.Filter("[DLBM]='104'")
line104.filter = lineFilter104
line104Symbo = mapnik.LineSymbolizer()
stroke104 = mapnik.Stroke(mapnik.Color("rgb(170,85,80)"), 0.2)
stroke104.add_dash(1.0, 3.0)
line104Symbo.stroke = stroke104
line104.symbols.append(line104Symbo)
lineStyle.rules.append(line104)

line117 = mapnik.Rule()
lineFilter117 = mapnik.Filter("[DLBM]='117'")
line117.filter = lineFilter117
line117Symbo = mapnik.LineSymbolizer()
stroke117 = mapnik.Stroke(mapnik.Color("rgb(0,120,200)"), 0.25)
line117Symbo.stroke = stroke117
line117.symbols.append(line117Symbo)
lineStyle.rules.append(line117)

line123 = mapnik.Rule()
precinct_style = mapnik.Style()
roads_style = mapnik.Style()

for precinct in range(1, 53):
    the_filter = '[PRECINCT] = {0}'.format(precinct)
    color = '#FFFFFF'
    outline_color = '#000000'

    rule = mapnik.Rule()
    rule.filter = mapnik.Filter(the_filter)
    symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(color))
    rule.symbols.append(symbolizer)
    precinct_style.rules.append(rule)

    symbolizer = mapnik.LineSymbolizer()
    symbolizer.stroke = mapnik.Stroke(mapnik.Color(outline_color), 1)
    rule.symbols.append(symbolizer)
    precinct_style.rules.append(rule)

layer1 = mapnik.Layer("Precinct Layer")
layer1.datasource = mapnik.Shapefile(file="data/Voter_Precinct.shp")
layer1.styles.append("Map Style")

columbia_pike_area = [201, 323, 324, 325, 326, 327, 331, 332, 334]
columbia_pike_area += [335, 338, 376, 457, 466, 467]

for roads in columbia_pike_area:
    the_filter = '[OBJECTID] = {0}'.format(roads)

    rule = mapnik.Rule()
    rule.filter = mapnik.Filter(the_filter)
Exemplo n.º 26
0
def map_image(zoom, left, bottom, right, top, line, orientation='n', highres=True):
    mapfile = settings.MAPNIK_STYLES + "mapnik2normal.xml"
    if orientation != 'n':
        mapfile = settings.MAPNIK_STYLES + "mapnik2orlice_%s.xml" % str(orientation)
    imgx, imgy = get_image_size(zoom, top, left, bottom, right)
    if orientation in ('w', 'e'):
        imgx, imgy = imgy, imgx
    if highres:
        mapfile = settings.MAPNIK_STYLES + "mapnik2print.xml"
        if orientation != 'n':
            mapfile = settings.MAPNIK_STYLES + "mapnik2print_orlice_%s.xml" % str(orientation)
        imgx = 2*imgx
        imgy = 2*imgy

    m = mapnik.Map(imgx, imgy)
    mapnik.load_map(m, mapfile)
    prj = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0'
                            ' +k=1.0 +units=m +nadgrids=@null +no_defs +over')
    # North on top
    n0 = prj.forward(mapnik.Coord(left, bottom))
    n1 = prj.forward(mapnik.Coord(right, top))
    # East on top
    e0 = mapnik.Coord(-n0.y, n0.x)
    e1 = mapnik.Coord(-n1.y, n1.x)
    # South on top
    s0 = mapnik.Coord(-n1.x, -n1.y)
    s1 = mapnik.Coord(-n0.x, -n0.y)
    # West on top
    w0 = mapnik.Coord(-e1.x, -e1.y)
    w1 = mapnik.Coord(-e0.x, -e0.y)
#    bottom_left = prj.forward(mapnik.Coord(left, bottom))
#    top_right = prj.forward(mapnik.Coord(right, top))
    boxes = {'n': mapnik.Box2d(n0.x, n0.y, n1.x, n1.y),
             'e': mapnik.Box2d(e0.x, e0.y, e1.x, e1.y),
             's': mapnik.Box2d(s0.x, s0.y, s1.x, s1.y),
             'w': mapnik.Box2d(w0.x, w0.y, w1.x, w1.y)
             }

    if line:
        gpxstyle = mapnik.Style()
        gpxrule = mapnik.Rule()
        lns = mapnik.LineSymbolizer()
        stroke = mapnik.Stroke()
        stroke.color = mapnik.Color('#FF6600')
        if highres:
            stroke.width = 10
        else:
            stroke.width = 5
        stroke.opacity = 0.9
        stroke.line_join = mapnik.line_join.names['round']
        stroke.line_cap = mapnik.line_cap.names['round']
        lns.stroke = stroke
        gpxrule.symbols.append(lns)
        gpxstyle.rules.append(gpxrule)
        m.append_style('gpxstyle', gpxstyle)
        gpxlayer = mapnik.Layer('gpx')
        gpxlayer.datasource = mapnik.Ogr(file=line, layer='OGRGeoJSON')
        gpxlayer.styles.append('gpxstyle')
        m.layers.append(gpxlayer)

    bbox = boxes[orientation]
    m.zoom_to_box(bbox)
    im = mapnik.Image(imgx, imgy)
    mapnik.render(m, im)
    return Image.open(StringIO(im.tostring('png')))
Exemplo n.º 27
0
def service_get_wms_of_shape(request, width, height, bbox,
                             presentationlayer_id, legend_id, timestep):
    """
    width = int
    height = int
    bbox = tuple
    """
    pl = get_object_or_404(PresentationLayer, pk=presentationlayer_id)
    if legend_id == -1:
        legend_id = pl.presentationtype.default_legend_id

    #presentation_dir = Setting.objects.get( key = 'presentation_dir' ).value

    #################### set up map ###################################
    log.debug('start setting up map ' + str(datetime.datetime.now()))

    m = mapnik.Map(width, height)
    spherical_mercator = (
        '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 '
        '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')

    m.srs = spherical_mercator
    m.background = mapnik.Color('transparent')
    #p = mapnik.Projection(spherical_mercator)

    log.debug('start setting up legend ' + str(datetime.datetime.now()))
    #################### set up legend ###################################

    mpl = cache.get('legend_' + str(legend_id))
    if mpl == None:
        sdl = get_object_or_404(ShapeDataLegend, pk=legend_id)
        if pl.presentationtype.geo_type in [
                PresentationType.GEO_TYPE_POLYGON,
                PresentationType.GEO_TYPE_LINE, PresentationType.GEO_TYPE_POINT
        ]:
            sm = SymbolManager('media/flooding_presentation/symbols/')
            mpl = MapnikPointLegend(sdl, sm)
            cache.set('legend_' + str(legend_id), mpl, 300)

    fields = mpl.get_presentationtype_fields()

    log.debug('start setting up lijntje ' + str(datetime.datetime.now()))
    #################### supportive layers ###################################
    if SupportLayers.objects.filter(
            presentationtype=pl.presentationtype).count() > 0:
        supportive_layers = (pl.presentationtype.supported_presentationtype.
                             supportive_presentationtype.all())

        sl = mapnik.Style()
        rule_l = mapnik.Rule()

        rule_stk = mapnik.Stroke()
        rule_stk.color = mapnik.Color(3, 158, 137)
        rule_stk.line_cap = mapnik.line_cap.ROUND_CAP
        rule_stk.width = 2.0
        rule_l.symbols.append(mapnik.LineSymbolizer(rule_stk))
        sl.rules.append(rule_l)
        m.append_style('Line Style', sl)

        for spt in supportive_layers:
            log.debug('supportive layer with id: ' + str(spt.id))

            # warning! works only for flooding scenarios
            if pl.scenario_set.count() > 0:
                scenario = pl.scenario_set.get()
                layers = PresentationLayer.objects.filter(presentationtype=spt,
                                                          scenario=scenario)

                if len(layers) > 0:
                    log.debug(
                        'supportive layer found for this presentationlayer')
                    layer = layers[0]

                    lyrl = mapnik.Layer('lines', spherical_mercator)
                    lyrl.datasource = mapnik.Shapefile(
                        file=external_file_location(
                            layer.presentationshape.geo_source.file_location))

                    lyrl.styles.append('Line Style')
                    m.layers.append(lyrl)

    #################### read data ###################################
    #read source and attach values
    log.debug('ready setting up map ' + str(datetime.datetime.now()))
    log.debug('start reading point cache ' + str(datetime.datetime.now()))
    points = cache.get('model_nodes_' + str(presentationlayer_id) + '_' +
                       str(timestep) + '_' + str(legend_id))
    log.debug('ready reading point cache ' + str(datetime.datetime.now()))

    if points is None:
        log.debug('start reading points from shape and his file ' +
                  str(datetime.datetime.now()))
        points = []

        drv = ogr.GetDriverByName('ESRI Shapefile')
        shapefile_name = external_file_location(
            pl.presentationshape.geo_source.file_location)
        ds = drv.Open(shapefile_name)
        layer = ds.GetLayer()

        has_his_file_field = False
        has_geo_file_field = False
        geo_fields = []
        log.debug('fields are: ' + str(fields))
        for nr in fields:
            field = fields[nr]
            if field.source_type == Field.SOURCE_TYPE_VALUE_SOURCE_PARAM:
                has_his_file_field = True
                his_field = field
                #only his files yet supported. read needed data
                log.debug('start reading hiscache' +
                          str(datetime.datetime.now()))
                his = cache.get('his_' + str(presentationlayer_id))
                log.debug('ready reading hiscache' +
                          str(datetime.datetime.now()))

                if his == None:
                    log.debug('read hisfile' + str(datetime.datetime.now()))
                    zip_name = external_file_location(
                        pl.presentationshape.value_source.file_location)
                    input_file = ZipFile(zip_name, "r")
                    if pl.presentationtype.geo_source_filter:
                        filename = pl.presentationtype.geo_source_filter
                    else:
                        filename = input_file.filelist[0].filename

                    his = HISFile(Stream(input_file.read(filename)))
                    input_file.close()
                    log.debug('ready reading hisfile' +
                              str(datetime.datetime.now()))
                    cache.set('his_' + str(presentationlayer_id), his, 3000)

                values = his.get_values_timestep_by_index(
                    his.get_parameter_index(his_field.name_in_source),
                    timestep)

            elif field.source_type == Field.SOURCE_TYPE_GEO_SOURCE_COL:
                has_geo_file_field = True
                geo_fields.append(field)
            else:
                log.debug('field source type ' + field.source_type +
                          ' not yet supported')

        if (layer.GetFeatureCount() > 0):
            feature = layer.next()
            id_index = feature.GetFieldIndex('id')

            for field in geo_fields:
                field.index_nr = feature.GetFieldIndex(
                    str(field.name_in_source))

            layer.ResetReading()
        ############################# place features in the right 'legend box'

        for feature in layer:
            point = feature.geometry()

            input_dict = {}

            if has_his_file_field:
                #get id form geosource, needed for reading hisfile
                id = (pl.presentationtype.value_source_id_prefix +
                      str(feature.GetField(id_index).strip()))
                if pl.presentationtype.absolute:
                    try:
                        input_dict[his_field.name_in_source] = abs(
                            values.get(id, None))
                        if values.get(id, None) > 1:
                            pass

                    except TypeError:
                        input_dict[his_field.name_in_source] = None
                else:
                    input_dict[his_field.name_in_source] = values.get(id, None)

            if has_geo_file_field:
                for field in geo_fields:
                    input_dict[field.name_in_source] = feature.GetField(
                        field.index_nr)

            rule_name = mpl.get_rule_name(input_dict)

            if pl.presentationtype.geo_type == 3:
                x = (point.GetX(0) + point.GetX(1)) / 2
                y = (point.GetY(0) + point.GetY(1)) / 2
            else:
                x = point.GetX()
                y = point.GetY()

            #rule_name = str('1_neerslag_64_0010000100_24x24_0_0')
            points.append((x, y, "NAME", rule_name))
    # Clean up
        ds.Destroy()
        log.debug('ready reading points form shape en his file ' +
                  str(datetime.datetime.now()))

        cache.set(
            'model_nodes_' + str(presentationlayer_id) + '_' + str(timestep) +
            '_' + str(legend_id), points, 300)

    log.debug('start making memory datasource ' + str(datetime.datetime.now()))

    lyr = mapnik.Layer('Points', spherical_mercator)
    m.append_style('Points legend', mpl.get_style())

    memory_ds = mapnik.MemoryDatasource()  #lyr.datasource
    context = mapnik.Context()
    context.push("name")
    next_id = 1
    for x, y, name, rule_name in points:
        wkt = "POINT(%0.1f %0.1f)" % (x, y)
        feature = mapnik.Feature(context, next_id)
        feature[name] = rule_name
        feature.add_geometries_from_wkt(wkt)
        memory_ds.add_feature(feature)
        next_id += 1
    lyr.datasource = memory_ds
    log.debug('finish making memory datasource ' +
              str(datetime.datetime.now()))
    lyr.styles.append('Points legend')
    m.layers.append(lyr)

    if presentationlayer_id in [62007, 62008]:
        m = mapnik.Map(width, height)
        spherical_mercator = mapnik.Projection(
            '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 '
            '+y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')

        m.srs = spherical_mercator
        m.background = mapnik.Color('transparent')

        sl = mapnik.Style()
        rule_l = mapnik.Rule()

        rule_stk = mapnik.Stroke()
        rule_stk.color = mapnik.Color(3, 158, 137)
        rule_stk.line_cap = mapnik.line_cap.ROUND_CAP
        rule_stk.width = 2.0
        rule_l.symbols.append(mapnik.LineSymbolizer(rule_stk))
        sl.rules.append(rule_l)
        m.append_style('Line Style2', sl)

        scenario = pl.scenario_set.get()
        layers = PresentationLayer.objects.filter(presentationtype=spt,
                                                  scenario=scenario)
        log.debug('supportive layer found for this presentationlayer')

        rds = mapnik.Projection(
            "+proj=sterea +lat_0=52.15616055555555 +lon_0=5.38763888888889 "
            "+k=0.999908 +x_0=155000 +y_0=463000 +ellps=bessel "
            "+towgs84=565.237,50.0087,465.658,-0.406857,0.350733,"
            "-1.87035,4.0812 +units=m +no_defs")
        lyrl = mapnik.Layer('lines', rds)
        # Commented out, variable 'presentation_dir' doesn't exist so this
        # cannot work. -- RG20120621
        #        lyrl.datasource = mapnik.Shapefile(
        #            file=external_file_location(
        #                str(presentation_dir + '\\' +
        #                    pl.presentationshape.geo_source.file_location)))
        lyrl.styles.append('Line Style2')
        m.layers.append(lyrl)

    ##################### render map #############################
    m.zoom_to_box(mapnik.Envelope(*bbox))  # lyrl.envelope

    log.debug('start render map ' + str(datetime.datetime.now()))
    img = mapnik.Image(width, height)
    mapnik.render(m, img)
    log.debug('ready render map ' + str(datetime.datetime.now()))

    log.debug('start PIL ' + str(datetime.datetime.now()))
    # you can use this if you want te modify image with PIL
    imgPIL = Image.fromstring('RGBA', (width, height), img.tostring())
    #imgPIL = imgPIL.convert('RGB')
    buffer = StringIO.StringIO()
    imgPIL.save(buffer, 'png')  # ,transparency = 10
    buffer.seek(0)

    response = HttpResponse(buffer.read())
    log.debug('end PIL ' + str(datetime.datetime.now()))
    response['Content-type'] = 'image/png'
    log.debug('ready sending map ' + str(datetime.datetime.now()))
    return response
Exemplo n.º 28
0
layer_air.styles.append(
    'Layer2a')  #menerapkan lapisan yang barusan dibuat dengan nama Layer2a
m.layers.append(layer_air)
#-------------------------End Layer2 Belanda----------------------------------#

#------------------------Layer3 Belanda----------------------#

#Membuat lapisan
layer_adm2 = mapnik.Layer('BelandaLayer3')
layer_adm2.datasource = mapnik.Shapefile(
    file='shapefiles/NLD_adm2.shp')  #mengambil lapisan dari sumber data
#Membuat Style
style_adm2 = mapnik.Style()
rule_adm2 = mapnik.Rule()
#Menggambar garis tepi
line_adm2 = mapnik.Stroke()
line_adm2.add_dash(2, 2)
#line_adm2.add_dash(2,2)
line_adm2.color = mapnik.Color('black')
line_adm2.width = 1.0
rule_adm2.symbols.append(
    mapnik.LineSymbolizer(line_adm2))  #menerapkan garis tepi ke rule map

#Menerapkan rule-rule yang ada ke style yang telah dibuat
style_adm2.rules.append(rule_adm2)

#Menandai ibukota
rule_ibukota = mapnik.Rule()
rule_ibukota.filter = mapnik.Expression("[NAME_2]='Amsterdam'")
rule_ibukota.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('yellow')))
style_adm2.rules.append(rule_ibukota)
Exemplo n.º 29
0

precinct_style = mapnik.Style()
roads_style = mapnik.Style()

for roads in range(1, 884):
    the_filter = '[OBJECTID] = {0}'.format(roads)

    rule = mapnik.Rule()
    rule.filter = mapnik.Filter(the_filter)
    symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#FF7700'))
    rule.symbols.append(symbolizer)
    roads_style.rules.append(rule)

    symbolizer = mapnik.LineSymbolizer()
    symbolizer.stroke = mapnik.Stroke(mapnik.Color('#FF7700'), 1)
    rule.symbols.append(symbolizer)
    roads_style.rules.append(rule)

layer = mapnik.Layer("Roads Layer")
layer.datasource = mapnik.Shapefile(file="data/Roads.shp")
layer.styles.append("Roads Style")

map1 = mapnik.Map(1024, 1024)
map1.background = mapnik.Color("#EEEEEE")
map1.append_style("Roads Style", roads_style)
map1.layers.append(layer)

map1.zoom_all()
mapnik.render_to_file(map1, "arl_roads.png", "png")
Exemplo n.º 30
0
def getMapImage(osmFile, map_output):
    '''Uses the data from the osmFile to out a .png image
       of the area depicted by the input file'''

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

    print('Has Mapnik.')

    if osmFile == '':
        print 'Error: getMapImage::No File Recieved'
        return -1
    else:
        print('OSM File: ' + osmFile)

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

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

    for highwayType in highwayList.keys():
        styleType = mapnik.Style()
        print(styleType)
        rule = mapnik.Rule()

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

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

        line_symbolizer = mapnik.LineSymbolizer(stk)

        rule.symbols.append(line_symbolizer)

        rule2 = mapnik.Rule()

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

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

        rule2.symbols.append(text_symbolizer)

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

        m.append_style(highwayType, styleType)

    ds = mapnik.Osm(file=osmFile)

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

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

    return os.system('xdg-open ' + map_output)