def test_text_symbolizer(): s = mapnik.TextSymbolizer() eq_(s.comp_op, mapnik.CompositeOp.src_over) eq_(s.clip, True) eq_(s.halo_rasterizer, mapnik.halo_rasterizer.FULL) # https://github.com/mapnik/mapnik/issues/1420 eq_(s.text_transform, mapnik.text_transform.NONE) # https://github.com/mapnik/mapnik/issues/1427 eq_(s.wrap_char, ord(' ')) eq_(s.wrap_character, ord(' ')) s.wrap_char = ord('\n') eq_(s.wrap_char, ord('\n')) eq_(s.wrap_character, ord('\n')) eq_(s.format.wrap_character, ord('\n')) s.wrap_character = ord('\r') eq_(s.wrap_char, ord('\r')) eq_(s.wrap_character, ord('\r')) eq_(s.format.wrap_character, ord('\r')) s.format.wrap_character = ord(' ') eq_(s.wrap_char, ord(' ')) eq_(s.wrap_character, ord(' ')) eq_(s.format.wrap_character, ord(' ')) # old args required method ts = mapnik.TextSymbolizer(mapnik.Expression('[Field_Name]'), 'Font Name', 8, mapnik.Color('black')) # eq_(str(ts.name), str(mapnik2.Expression('[Field_Name]'))) name field is no longer supported eq_(ts.format.face_name, 'Font Name') eq_(ts.format.text_size, 8) eq_(ts.format.fill, mapnik.Color('black')) eq_(ts.properties.label_placement, mapnik.label_placement.POINT_PLACEMENT) eq_(ts.properties.horizontal_alignment, mapnik.horizontal_alignment.AUTO)
def labStyle(self, field, font="DejaVu Sans Book", size=10, clr="#000000"): labelStyle = mapnik.Style() rule = mapnik.Rule() symbol = mapnik.TextSymbolizer(field, font, size, mapnik.Color(clr)) rule.symbols.append(symbol) labelStyle.rules.append(rule) return labelStyle
def text(expression, size, color, fontVariant=None, haloRadius=None, halo=mapnik.Color(255, 255, 200), transform=None, placement=None, minPathLength=None): font = 'DejaVu Sans Book' if fontVariant is not None and fontVariant == 'bold': font = 'DejaVu Sans Bold' symbolizer = mapnik.TextSymbolizer(expression, font, size, color) symbolizer.label_placement = mapnik.label_placement.POINT_PLACEMENT if placement is not None and placement == 'line': symbolizer.label_placement = mapnik.label_placement.LINE_PLACEMENT if halo is not None: symbolizer.halo_fill = halo if haloRadius is not None: symbolizer.halo_radius = haloRadius symbolizer.placement_type = 'simple' symbolizer.avoid_edges = True symbolizer.allow_overlap = False if transform is not None: symbolizer.text_transform = transform if minPathLength is not None: symbolizer.minimum_distance = minPathLength symbolizer.minimum_path_length = minPathLength return symbolizer
def getTextStyle(fieldname): style = mapnik.Style() # style object to hold rules rule = mapnik.Rule() # rule object to hold symbolizers # print(help(mapnik.TextSymbolizer)) print(mapnik.mapnik_version()) symbolizer = mapnik.TextSymbolizer( mapnik.Expression('[' + fieldname + ']'), 'DejaVu Sans Book', 10, mapnik.Color('black')) # symbolizer = mapnik.TextSymbolizer() # print(symbolizer, dir(symbolizer)) # print(symbolizer.properties.format_tree.text) # symbolizer.face_name = mapnik.FormattingText('DejaVu Sans Book') # symbolizer.face_name = 'DejaVu Sans Book' # symbolizer.properties.format_tree = mapnik.FormattingText('DejaVu Sans Book') # symbolizer.name = mapnik.Expression('['+fieldname+']') symbolizer.halo_fill = mapnik.Color('white') symbolizer.halo_radius = 1 symbolizer.label_placement = label_placement.LINE_PLACEMENT # POINT_PLACEMENT is default symbolizer.allow_overlap = False symbolizer.avoid_edges = True rule.symbols.append(symbolizer) style.rules.append(rule) return style
def __add_manholes(self, layers, styles): "Add manhole layer and styles." # Select the manholes that are part of this sewerage. manholes = Manhole.objects.filter(sewerage__pk=self.id) # Define a style. style = mapnik.Style() # Style the `normal` manholes. rule = mapnik.Rule() rule.filter = mapnik.Filter("[sink] != 1") symbol = mapnik.PointSymbolizer() symbol.allow_overlap = True rule.symbols.append(symbol) style.rules.append(rule) # Style the sink. rule = mapnik.Rule() rule.filter = mapnik.Filter("[sink] = 1") symbol = mapnik.PointSymbolizer( str(finders.find("lizard_riool/sink.png")), "png", 8, 8 ) symbol.allow_overlap = True rule.symbols.append(symbol) style.rules.append(rule) # Add labels. rule = mapnik.Rule() rule.max_scale = 1700 symbol = mapnik.TextSymbolizer( 'code', 'DejaVu Sans Book', 10, mapnik.Color('black') ) symbol.allow_overlap = True symbol.label_placement = mapnik.label_placement.POINT_PLACEMENT symbol.vertical_alignment = mapnik.vertical_alignment.TOP symbol.displacement(0, -5) # slightly above rule.symbols.append(symbol) style.rules.append(rule) # Setup datasource. params = default_database_params() params['table'] = "({}) data".format(manholes.query) datasource = mapnik.PostGIS(**params) # Define layer. layer = mapnik.Layer('manholeLayer') layer.datasource = datasource layer.maxzoom = 35000 layer.styles.append('manholeStyle') layers.append(layer) styles['manholeStyle'] = style
def create_grid_map(width,height): places_ds = mapnik.PointDatasource() places_ds.add_point(143.10,-38.60,'Name','South East') places_ds.add_point(142.48,-38.60,'Name','South West') places_ds.add_point(142.48,-38.38,'Name','North West') places_ds.add_point(143.10,-38.38,'Name','North East') s = mapnik.Style() r = mapnik.Rule() #symb = mapnik.PointSymbolizer() symb = mapnik.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) label = mapnik.TextSymbolizer(mapnik.Expression('[Name]'), 'DejaVu Sans Book', 10, mapnik.Color('black') ) label.allow_overlap = True label.displacement = (0,-10) #r.symbols.append(label) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = places_ds lyr.styles.append('places_labels') m = mapnik.Map(width,height) m.append_style('places_labels',s) m.layers.append(lyr) return m
def create_map_and_append_symbolyzer(sym): srs = '+init=epsg:32630' lyr = mapnik.Layer('arrows') try: lyr.datasource = mapnik.Shapefile(file='../data/shp/arrows.shp', ) lyr.srs = srs _map = mapnik.Map(256, 256, srs) style = mapnik.Style() rule = mapnik.Rule() rule.symbols.append(sym) # put a test symbolizer to see what is the azimuth being read ts = mapnik.TextSymbolizer(mapnik.Expression('[azimuth]'), "DejaVu Sans Book", 10, mapnik.Color("black")) ts.allow_overlap = True rule.symbols.append(ts) style.rules.append(rule) _map.append_style('foo', style) lyr.styles.append('foo') _map.layers.append(lyr) _map.zoom_to_box(mapnik.Box2d(0, 0, 8, 8)) return _map except RuntimeError, e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(e)
def test_render_grid(): places_ds = mapnik.PointDatasource() places_ds.add_point(143.10,-38.60,'Name','South East') places_ds.add_point(142.48,-38.60,'Name','South West') places_ds.add_point(142.48,-38.38,'Name','North West') places_ds.add_point(143.10,-38.38,'Name','North East') s = mapnik.Style() r = mapnik.Rule() #symb = mapnik.PointSymbolizer() symb = mapnik.MarkersSymbolizer() symb.allow_overlap = True r.symbols.append(symb) label = mapnik.TextSymbolizer(mapnik.Expression('[Name]'), 'DejaVu Sans Book', 10, mapnik.Color('black') ) label.allow_overlap = True label.displacement = (0,-10) #r.symbols.append(label) s.rules.append(r) lyr = mapnik.Layer('Places') lyr.datasource = places_ds lyr.styles.append('places_labels') m = mapnik.Map(256,256) m.append_style('places_labels',s) m.layers.append(lyr) ul_lonlat = mapnik.Coord(142.30,-38.20) lr_lonlat = mapnik.Coord(143.40,-38.80) m.zoom_to_box(mapnik.Box2d(ul_lonlat,lr_lonlat)) grid = mapnik.render_grid(m,0,key='Name',resolution=4,fields=['Name']) eq_(grid,grid_correct) eq_(resolve(grid,0,0),None) # check every pixel of the nw symbol expected = {"Name": "North West"} # top row eq_(resolve(grid,23,9),expected) eq_(resolve(grid,23,10),expected) eq_(resolve(grid,23,11),expected) # core eq_(resolve(grid,24,8),expected) eq_(resolve(grid,24,9),expected) eq_(resolve(grid,24,10),expected) eq_(resolve(grid,24,11),expected) eq_(resolve(grid,24,12),expected) eq_(resolve(grid,25,8),expected) eq_(resolve(grid,25,9),expected) eq_(resolve(grid,25,10),expected) eq_(resolve(grid,25,11),expected) eq_(resolve(grid,25,12),expected) # bottom row eq_(resolve(grid,26,9),expected) eq_(resolve(grid,26,10),expected) eq_(resolve(grid,26,11),expected)
def test_textsymbolizer_init(): ts = mapnik.TextSymbolizer(mapnik.Expression('[Field_Name]'), 'Font Name', 8, mapnik.Color('black')) eq_(str(ts.name), str(mapnik.Expression('[Field_Name]'))) eq_(ts.face_name, 'Font Name') eq_(ts.text_size, 8) eq_(ts.fill, mapnik.Color('black')) eq_(ts.label_placement, mapnik.label_placement.POINT_PLACEMENT)
def test_textsymbolizer_init(): ts = mapnik.TextSymbolizer(mapnik.Expression('[Field_Name]'), 'Font Name', 8, mapnik.Color('black')) # eq_(str(ts.name), str(mapnik2.Expression('[Field_Name]'))) name field is no longer supported eq_(ts.format.face_name, 'Font Name') eq_(ts.format.text_size, 8) eq_(ts.format.fill, mapnik.Color('black')) eq_(ts.properties.label_placement, mapnik.label_placement.POINT_PLACEMENT) eq_(ts.properties.horizontal_alignment, mapnik.horizontal_alignment.AUTO)
def render_tile(layer, z, x, y): """ Render the tile using mapnik. """ m = mapnik.Map(TILE_WIDTH, TILE_WIDTH) s = mapnik.Style() r = mapnik.Rule() #line_symbolizer = mapnik.PointSymbolizer() line_symbolizer = mapnik.PolygonSymbolizer() line_symbolizer.fill = mapnik.Color('yellow') line_symbolizer.fill_opacity = 0.7 #line_symbolizer.allow_overlap = True #line_symbolizer.transform="scale(5,5)" r.symbols.append(line_symbolizer) label = mapnik.TextSymbolizer(mapnik.Expression('[nama]'), 'DejaVu Sans Book', 24, mapnik.Color('red')) label.halo_radius = 1 label.avoid_edges = False r.symbols.append(label) s.rules.append(r) m.append_style('My Style', s) # Initialize layer from PostGIS table ds = mapnik.PostGIS(**POSTGIS_TABLE) layer2 = mapnik.Layer(LAYER_NAME) layer2.datasource = ds layer2.styles.append('My Style') m.layers.append(layer2) m.zoom_all() # ds = mapnik.Shapefile(file='C:\Users\ICS\Documents\kuliah\gis\gis mapnik\pantai indonesia\IND_PNT_polyline.shp') # layer = mapnik.Layer(LAYER_NAME) # layer.datasource = ds # layer.styles.append('My Style') # m.layers.append(layer) # m.zoom_all() renderer = TiledMapRenderer(m) im = renderer.render_tile(z, x, y) # im = mapnik.Image(TILE_WIDTH, TILE_WIDTH) # mapnik.render(m, im, 13, 0, 0) # im.save('tmp/bla.png') # mapnik.render_to_file(m,'aaa.png', 'png') return im.tostring('png'), 200, {'Content-type': 'image/png'}
def test_textsymbolizer_pickle(): ts = mapnik.TextSymbolizer(mapnik.Expression('[Field_Name]'), 'Font Name', 8, mapnik.Color('black')) eq_(str(ts.name), str(mapnik.Expression('[Field_Name]'))) eq_(ts.face_name, 'Font Name') eq_(ts.text_size, 8) eq_(ts.fill, mapnik.Color('black')) raise Todo("text_symbolizer pickling currently disabled") ts2 = pickle.loads(pickle.dumps(ts, pickle.HIGHEST_PROTOCOL)) eq_(ts.name, ts2.name) eq_(ts.face_name, ts2.face_name) eq_(ts.allow_overlap, ts2.allow_overlap) eq_(ts.displacement, ts2.displacement) eq_(ts.anchor, ts2.anchor) eq_(ts.fill, ts2.fill) eq_(ts.force_odd_labels, ts2.force_odd_labels) eq_(ts.halo_fill, ts2.halo_fill) eq_(ts.halo_radius, ts2.halo_radius) eq_(ts.label_placement, ts2.label_placement) eq_(ts.minimum_distance, ts2.minimum_distance) eq_(ts.text_ratio, ts2.text_ratio) eq_(ts.text_size, ts2.text_size) eq_(ts.wrap_width, ts2.wrap_width) eq_(ts.vertical_alignment, ts2.vertical_alignment) eq_(ts.label_spacing, ts2.label_spacing) eq_(ts.label_position_tolerance, ts2.label_position_tolerance) # 22.5 * M_PI/180.0 initialized by default assert_almost_equal(s.max_char_angle_delta, 0.39269908169872414) eq_(ts.wrap_character, ts2.wrap_character) eq_(ts.text_transform, ts2.text_transform) eq_(ts.line_spacing, ts2.line_spacing) eq_(ts.character_spacing, ts2.character_spacing) # r1341 eq_(ts.wrap_before, ts2.wrap_before) eq_(ts.horizontal_alignment, ts2.horizontal_alignment) eq_(ts.justify_alignment, ts2.justify_alignment) eq_(ts.opacity, ts2.opacity) # r2300 eq_(s.minimum_padding, 0.0) raise Todo( "FontSet pickling support needed: http://trac.mapnik.org/ticket/348") eq_(ts.fontset, ts2.fontset)
def to_mapnik(self): # note: these match css in Mapnik2 convert_enums = {'uppercase': mapnik.text_convert.TOUPPER, 'lowercase': mapnik.text_convert.TOLOWER } sym = mapnik.TextSymbolizer(self.name, self.face_name, self.size, mapnik.Color(str(self.color))) sym.wrap_width = self.wrap_width or sym.wrap_width sym.label_spacing = self.label_spacing or sym.label_spacing sym.label_position_tolerance = self.label_position_tolerance or sym.label_position_tolerance sym.max_char_angle_delta = self.max_char_angle_delta or sym.max_char_angle_delta sym.halo_fill = mapnik.Color(str(self.halo_color)) if self.halo_color else sym.halo_fill sym.halo_radius = self.halo_radius or sym.halo_radius sym.character_spacing = self.character_spacing or sym.character_spacing sym.line_spacing = self.line_spacing or sym.line_spacing sym.avoid_edges = self.avoid_edges.value if self.avoid_edges else sym.avoid_edges sym.force_odd_labels = self.force_odd_labels.value if self.force_odd_labels else sym.force_odd_labels sym.minimum_distance = self.minimum_distance or sym.minimum_distance sym.allow_overlap = self.allow_overlap.value if self.allow_overlap else sym.allow_overlap if self.label_placement: sym.label_placement = mapnik.label_placement.names.get(self.label_placement,mapnik.label_placement.POINT_PLACEMENT) # note-renamed in Mapnik2 to 'text_transform' if self.text_transform: sym.text_convert = convert_enums.get(self.text_transform,mapnik.text_convert.NONE) if self.vertical_alignment: # match the logic in load_map.cpp for conditionally applying vertical_alignment default default_vertical_alignment = mapnik.vertical_alignment.MIDDLE if self.dx > 0.0: default_vertical_alignment = mapnik.vertical_alignment.BOTTOM elif self.dy < 0.0: default_vertical_alignment = mapnik.vertical_alignment.TOP sym.vertical_alignment = mapnik.vertical_alignment.names.get(self.vertical_alignment, default_vertical_alignment) if self.justify_alignment: sym.justify_alignment = mapnik.justify_alignment.names.get(self.justify_alignment, mapnik.justify_alignment.MIDDLE) if self.fontset: # sym.fontset = str(self.fontset) # not viable via python sys.stderr.write('\nCascadenik debug: Warning, FontSets will be ignored as they are not yet supported in Mapnik via Python...\n') sym.displacement(self.dx or 0.0, self.dy or 0.0) return sym
def to_mapnik(self): sym = mapnik.TextSymbolizer(self.name, self.face_name, self.size, mapnik.Color(str(self.color))) sym.wrap_width = self.wrap_width or sym.wrap_width sym.label_spacing = self.spacing or sym.label_spacing sym.label_position_tolerance = self.label_position_tolerance or sym.label_position_tolerance sym.max_char_angle_delta = self.max_char_angle_delta or sym.max_char_angle_delta sym.halo_fill = self.halo_color or sym.halo_fill sym.halo_radius = self.halo_radius or sym.halo_radius sym.avoid_edges = self.avoid_edges or sym.avoid_edges sym.minimum_distance = self.min_distance or sym.minimum_distance sym.allow_overlap = self.allow_overlap or sym.allow_overlap sym.displacement(self.dx or 0, self.dy or 0) return sym
def mapnik_style(self): import mapnik polygon_style = mapnik.Style() ps = mapnik.PolygonSymbolizer(mapnik.Color('#551A8B')) ps.fill_opacity = 0.9 ls = mapnik.LineSymbolizer(mapnik.Color('#ffffff'),0.75) ls.stroke_opacity = 0.9 ts = mapnik.TextSymbolizer('name','DejaVu Sans Bold',11,mapnik.Color('#555555')) ts.displacement(15,15) ts.halo_fill = mapnik.Color('white') ts.halo_radius = 1 ts.opacity = 0.5 r = mapnik.Rule() r.symbols.append(ps) r.symbols.append(ls) r.symbols.append(ts) polygon_style.rules.append(r) return polygon_style
def test_loading_fontset_from_python(): m = mapnik.Map(256, 256) fset = mapnik.FontSet('foo') fset.add_face_name('Comic Sans') fset.add_face_name('Papyrus') eq_(fset.name, 'foo') fset.name = 'my-set' eq_(fset.name, 'my-set') m.append_fontset('my-set', fset) sty = mapnik.Style() rule = mapnik.Rule() tsym = mapnik.TextSymbolizer() eq_(tsym.fontset, None) tsym.fontset = fset rule.symbols.append(tsym) sty.rules.append(rule) m.append_style('Style', sty) serialized_map = mapnik.save_map_to_string(m) eq_('fontset-name="my-set"' in serialized_map, True)
m = mapnik.Map(600, 300) m.background = mapnik.Color('steelblue') s = mapnik.Style() r = mapnik.Rule() polygon_symbolizer = mapnik.PolygonSymbolizer() polygon_symbolizer.fill = mapnik.Color('#fdf704') r.symbols.append(polygon_symbolizer) line_symbolizer = mapnik.LineSymbolizer() line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('white'), 1) line_symbolizer.stroke_width = 10.0 r.symbols.append(line_symbolizer) basinsLabels = mapnik.TextSymbolizer(mapnik.Expression('[NAME]'), 'DejaVu Sans Bold', 5, mapnik.Color('black')) basinsLabels.halo_fill = mapnik.Color('yellow') basinsLabels.halo_radius = 2 r.symbols.append(basinsLabels) point_sym = mapnik.PointSysmbolyzer() point_sym.allow_overlap = TRUE r.symbols.append(point_sym) s.rules.append(r) m.append_style('Yogi', s) ds = mapnik.Shapefile(file="provinsiindonesia/INDONESIA_PROP.shp") layer = mapnik.Layer('world') layer.datasource = ds
def draw_district_outline(statefp, state, district, shpfeature, map_size, contextmap) : # Create an image with district outlines and shading over the parts of the map # in other districts or other states. Also compute our desired bounding box. # Get bounding box of this map, which will be a little larger than the boudning box of the district. long_min, long_max, lat_min, lat_max = shpfeature.GetGeometryRef().GetEnvelope() margin = 0.06 if contextmap : margin = 1.5 d_long = long_max-long_min d_lat = lat_max-lat_min long_min -= d_long*margin long_max += d_long*margin lat_min -= d_lat*margin lat_max += d_lat*margin # Choose an aspect ratio for the final image that is a good match for # the shape of the district. We have two choices. We could use nice-looking # aspect ratios or we could use aspect ratios that match common sizes of # paper so that the map can be printed nicely. good_aspect_ratios = [ (3.0, 3.0/1.0), # 8.5x17 tabloid landscape (1.5, 16.0/9.0), # HD widescreen (1.25, 11.0/8.5), # 8.5x11 letter landscape (1/1.25, 1.0/1.0), # square (1/1.5, 8.5/11.0), # 8.5x11 letter portrait (0, 8.5/17.0), # 8.5x17 tabloid portrait ] for threshold, ratio in good_aspect_ratios: if d_long/d_lat > threshold: if ratio > 1.0: map_width = int(ratio * map_size) map_height = map_size else: map_width = map_size map_height = int(map_size / ratio) break # Create a map. m = mapnik.Map(map_width, map_height, output_projection) # Center to the projected coordinates. bounds = (mapnik.Projection(output_projection).forward( mapnik.Projection(census_shapefile_projection).inverse(mapnik.Coord(long_min, lat_min)) ), mapnik.Projection(output_projection).forward( mapnik.Projection(census_shapefile_projection).inverse(mapnik.Coord(long_max, lat_max)) )) m.zoom_to_box(mapnik.Envelope(bounds[0].x, bounds[0].y, bounds[1].x, bounds[1].y)) if not contextmap : # Add a layer for counties and ZCTAs. # TODO: These should really be generated with the map tile layer # so that the labels don't hit each other. for layer, featurename, labelfontsize, labelcolor, border in ( ("county", "NAME", map_size/40, mapnik.Color('rgb(70%,20%,20%)'), True), ("zcta510", "ZCTA5CE10", map_size/60, mapnik.Color('rgb(40%,40%,80%)'), False), ): s = mapnik.Style() r = mapnik.Rule() if border: p = mapnik.LineSymbolizer(labelcolor, map_size/300) p.stroke.opacity = .3 p.stroke.add_dash(.1, .1) r.symbols.append(p) r.symbols.append(mapnik.TextSymbolizer(mapnik.Expression('[%s]' % featurename), mapnik_label_font, labelfontsize, labelcolor)) s.rules.append(r) m.append_style('%s Style' % layer, s) lyr = mapnik.Layer('world', census_shapefile_projection) lyr.datasource = mapnik.Shapefile(file=sys.argv[1] + "/tl_2013_us_%s.shp" % layer) lyr.styles.append('%s Style' % layer) m.layers.append(lyr) # Draw shading and numbering for the other districts. district_outline_color = mapnik.Color('rgb(100%,75%,25%)') s = mapnik.Style() r = mapnik.Rule() p = mapnik.PolygonSymbolizer(mapnik.Color('rgb(70%,70%,70%)')) p.fill_opacity = .55 r.symbols.append(p) r.filter = mapnik.Filter("([CD113FP] <> '" + district + "' || [STATEFP] <> '" + statefp + "') && [CD113FP] != 'ZZ'") t = mapnik.TextSymbolizer(mapnik.Expression('[CD113FP]'), mapnik_label_font, map_size/15, district_outline_color) t.halo_radius = map_size/120 r.symbols.append(t) s.rules.append(r) # Draw the outlines of districts. Use a hard thin outline to be exact plus # a faded wider outline for strength. r = mapnik.Rule() p = mapnik.LineSymbolizer(district_outline_color, 2) r.symbols.append(p) p = mapnik.LineSymbolizer(district_outline_color, map_size/140) p.stroke.opacity = .35 r.symbols.append(p) s.rules.append(r) m.append_style('Other Districts Style',s) lyr = mapnik.Layer('world', census_shapefile_projection) lyr.datasource = mapnik.Shapefile(file=sys.argv[1] + "/tl_2013_us_cd113.shp") lyr.styles.append('Other Districts Style') m.layers.append(lyr) im = mapnik.Image(map_width, map_height) mapnik.render(m, im) env = m.envelope() env = ( mapnik.Projection(output_projection).inverse(mapnik.Coord(env[0], env[1])), mapnik.Projection(output_projection).inverse(mapnik.Coord(env[2], env[3])) ) return im, env
def xml_map_config(request, zoom, x, y, basqui_map, layersMapOptions): basqui_map.changed = False basqui_map.save() 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" ) for layer in layersMapOptions.all(): try: layerLabel = LayerLabel.objects.get(layerMapOptions=layer) except ObjectDoesNotExist: layerLabel = None for layerStyle in layer.styles.all(): shapefile = layer.layer geometryField = utils.calcGeometryField(shapefile.geom_type) if layerLabel: query = '(select ' + geometryField + ', attribute_value->\'' + layerLabel.field.name + '\' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' else: query = '(select ' + geometryField + ', id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' datasource = mapnik.PostGIS(user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], port=5433, table=query, srid=3857, geometry_field=geometryField, geometry_table='"shapefile_feature"') featureLayer = mapnik.Layer( str(shapefile.filename) + str(layerStyle.id)) 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( str(shapefile.filename) + '_Style' + str(layerStyle.id)) #defining the feature layer styles style_rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: s = mapnik.PointSymbolizer( mapnik.PathExpression(str(layerStyle.iconName))) s.allow_overlap = True style_rule.symbols.append(s) elif shapefile.geom_type in ["LineString", "MultiLineString"]: style_rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: p = mapnik.PolygonSymbolizer( mapnik.Color(str((layerStyle.fillColor)))) p.fill_opacity = layerStyle.fillOpacity style_rule.symbols.append(p) style_rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) layer_style = mapnik.Style() layer_style.rules.append(style_rule) #defining label styles if layerLabel: label_rule = mapnik.Rule() label = mapnik.TextSymbolizer( mapnik.Expression('[label]'), 'DejaVu Sans Book', layerLabel.font_size, mapnik.Color(str(layerLabel.font_color))) label.halo_fill = mapnik.Color(str(layerLabel.halo_color)) label.halo_radius = int(layerLabel.halo_radius) #label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT label.allow_overlap = False label.avoid_edges = True label_rule.symbols.append(label) label_style = mapnik.Style() label_style.rules.append(label_rule) featureLayer.styles.append( str(shapefile.filename) + '_label' + str(layerStyle.id)) #add label to the map map.append_style( str(shapefile.filename) + '_label' + str(layerStyle.id), label_style) #add new feature to the map map.append_style( str(shapefile.filename) + '_Style' + str(layerStyle.id), layer_style) map.layers.append(featureLayer) #saving the map mapnik xml mapnik.save_map( map, "c:\\basqui\\tilestache\\%s\\%s.xml" % (str(request.user), str(basqui_map.map_name)))
def __add_sewers(self, layers, styles): "Add sewer layer and styles." # Get all sewer pipes that constitute to this sewerage. sewers = Sewer.objects.filter(sewerage__pk=self.id) # Define a style. style = mapnik.Style() # QUALITY_UNKNOWN rule = mapnik.Rule() rule.filter = mapnik.Filter( "[quality] = {}".format(Sewer.QUALITY_UNKNOWN) ) rule.max_scale = 1700 symbol = mapnik.TextSymbolizer( 'code', 'DejaVu Sans Book', 10, mapnik.Color('blue') ) symbol.allow_overlap = True # symbol.label_placement = mapnik.label_placement.LINE_PLACEMENT rule.symbols.append(symbol) style.rules.append(rule) # QUALITY_RELIABLE rule = mapnik.Rule() rule.filter = mapnik.Filter( "[quality] = {}".format(Sewer.QUALITY_RELIABLE) ) rule.max_scale = 1700 symbol = mapnik.TextSymbolizer( 'code', 'DejaVu Sans Book', 10, mapnik.Color('green') ) symbol.allow_overlap = True # symbol.label_placement = mapnik.label_placement.LINE_PLACEMENT symbol.allow_overlap = True symbol.opacity = 1.0 rule.symbols.append(symbol) style.rules.append(rule) # QUALITY_UNRELIABLE rule = mapnik.Rule() rule.filter = mapnik.Filter( "[quality] = {}".format(Sewer.QUALITY_UNRELIABLE) ) rule.max_scale = 1700 symbol = mapnik.TextSymbolizer( 'code', 'DejaVu Sans Book', 10, mapnik.Color('red') ) symbol.allow_overlap = True # symbol.label_placement = mapnik.label_placement.LINE_PLACEMENT # symbol.displacement(16, 16) # slightly above rule.symbols.append(symbol) style.rules.append(rule) # Setup datasource. params = default_database_params() params['table'] = "({}) data".format(sewers.query) datasource = mapnik.PostGIS(**params) # Define layer. layer = mapnik.Layer('sewerLayer') layer.datasource = datasource layer.maxzoom = 35000 layer.styles.append('sewerStyle') layers.append(layer) styles['sewerStyle'] = style
# center of the image label_x = xmin + ((xmax - xmin) / 2) # bottom of the image label_y = ymin + ((ymax - ymin) / 30) # create PointDatasource pds = mapnik.PointDatasource() # place scale at the bottom-center of the map pds.add_point(label_x, label_y, 'Name', "Scale: 1:" + str(m.scale_denominator())) # create label symbolizers if mapnik.mapnik_version() >= 800: text = mapnik.TextSymbolizer(mapnik.Expression('[Name]'),'DejaVu Sans Bold',12,mapnik.Color('black')) else: text = mapnik.TextSymbolizer('Name','DejaVu Sans Bold',12,mapnik.Color('black')) s3 = mapnik.Style() r3 = mapnik.Rule() r3.symbols.append(text) s3.rules.append(r3) lyr3 = mapnik.Layer('Memory Datasource') lyr3.datasource = pds lyr3.styles.append('Style') m.layers.append(lyr3) m.append_style('Style',s3) ###
criteria = mapnik.Filter("[POP2005] > 100000000") # get features that pass criteria queryset = [f for f in featureset if criteria.passes(f)] for feature in queryset: m.zoom_to_box(feature.envelope()) m.zoom(1.05) name = str(feature.attributes['NAME']) print 'Matched %s...' % name feature_filter = mapnik.Filter("[NAME] = '%s'" % name) # selected/highlighted style s, r = mapnik.Style(), mapnik.Rule() r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('darkorange'), 3)) r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('yellow'), 2)) t = mapnik.TextSymbolizer('NAME', 'DejaVu Sans Book', 30, mapnik.Color('rgba(0,0,0,.8)')) t.avoid_edges = True t.halo_fill = mapnik.Color('rgba(255,255,255,.2)') t.halo_radius = 2 r.symbols.append(t) r.filter = feature_filter s.rules.append(r) m.remove_style('selected') m.append_style('selected', s) im = mapnik.Image(m.width, m.height) mapnik.render(m, im) file = name + '.png' print 'Rendering %s...' % file im.save(file) os.system('open *.png')
# Populated Places popplaces_lyr = mapnik.Layer('Populated Places') popplaces_lyr.srs = "+proj=lcc +ellps=GRS80 +lat_0=49 +lon_0=-95 +lat+1=49 +lat_2=77 +datum=NAD83 +units=m +no_defs" popplaces_lyr.datasource = mapnik.Shapefile(file='../data/popplaces', encoding='latin1') popplaces_style = mapnik.Style() popplaces_rule = mapnik.Rule() # And here we have a TextSymbolizer, used for labeling. # The first parameter is the name of the attribute to use as the source of the # text to label with. Then there is font size in points (I think?), and colour. popplaces_text_symbolizer = mapnik.TextSymbolizer( mapnik.Expression("[GEONAME]"), 'DejaVu Sans Book', 10, mapnik.Color('black')) # We set a "halo" around the text, which looks like an outline if thin enough, # or an outright background if large enough. popplaces_text_symbolizer.label_placement = mapnik.label_placement.POINT_PLACEMENT popplaces_text_symbolizer.halo_fill = mapnik.Color(255, 255, 200) popplaces_text_symbolizer.halo_radius = 1 popplaces_text_symbolizer.avoid_edges = True #popplaces_text_symbolizer.minimum_padding = 30 popplaces_rule.symbols.append(popplaces_text_symbolizer) popplaces_style.rules.append(popplaces_rule) m.append_style('popplaces', popplaces_style)
def tileMap(request, version, ezmap_id, zoom, x, y): try: if version != "1.0": raise Http404 try: ezmap = EzMap.objects.get(id=ezmap_id) layersMapOptions = LayerMapOptions.objects.filter( ezmap=ezmap, visible=True).order_by('-position') except Shapefile.DoesNotExist or Feature.DoesNotExist: 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 if ezmap.changed: #create de mapnik.map object ezmap.changed = False ezmap.save() 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" ) #map.background = mapnik.Color("#ffffff") #defining the feature layer for layer in layersMapOptions.all(): label = LayerLabel.objects.get(layerMapOptions=layer) for layerStyle in layer.styles.all(): shapefile = layer.layer geometryField = utils.calcGeometryField( shapefile.geom_type) query = '(select ' + geometryField + ', attribute_value->\'' + label.field.name + '\' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str( shapefile.id) + ')) as geom' ## datasource = mapnik.SQLite(file='C:\mygeosite\sqlite3\sql3.db', ## table=query, ## srid=3857, ## geometry_field=geometryField, ## use_spatial_index=False) datasource = mapnik.PostGIS( user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], table=query, srid=3857, geometry_field=geometryField, geometry_table='"shapefile_feature"') featureLayer = mapnik.Layer( str(shapefile.filename) + str(layerStyle.id)) 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( str(shapefile.filename) + '_Style' + str(layerStyle.id)) #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in ["Point", "MultiPoint"]: s = mapnik.PointSymbolizer( mapnik.PathExpression(str(layerStyle.iconName))) s.allow_overlap = True rule.symbols.append(s) elif shapefile.geom_type in [ "LineString", "MultiLineString" ]: rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) elif shapefile.geom_type in ["Polygon", "MultiPolygon"]: p = mapnik.PolygonSymbolizer( mapnik.Color(str((layerStyle.fillColor)))) p.fill_opacity = layerStyle.fillOpacity rule.symbols.append(p) rule.symbols.append( mapnik.LineSymbolizer( mapnik.Color(str(layerStyle.strokeColor)), layerStyle.strokeWeight)) label = mapnik.TextSymbolizer( mapnik.Expression('[label]'), 'DejaVu Sans Book', label.font_size, mapnik.Color(str(label.font_color))) label.halo_fill = mapnik.Color(str(label.halo_color)) label.halo_radius = int(label.halo_radius) label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT label.allow_overlap = False label.avoid_edges = True rule.symbols.append(label) style = mapnik.Style() style.rules.append(rule) #add new feature to the map map.append_style( str(shapefile.filename) + '_Style' + str(layerStyle.id), style) map.layers.append(featureLayer) #saving the map mapnik xml mapnik.save_map( map, "c:\\mygeosite\\tilestache\\%s\\%s.xml" % (str(request.user), str(ezmap.map_name))) config = { "cache": { "name": "test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { ezmap.map_name: { "provider": { "name": "mapnik", "mapfile": "../tilestache/%s/%s.xml" % (request.user, ezmap.map_name) }, "projection": "spherical mercator" } } } # like http://tile.openstreetmap.org/1/0/0.png #coord = ModestMaps.Core.Coordinate(y, x, zoom) path = "/%s/%s/%s/%s.png" % (ezmap.map_name, 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, mimetype="image/png") except: traceback.print_exc() return HttpResponse("")
def tileFeature(request, version, shapefile_id, feature_id, zoom, x, y): try: if version != "1.0": raise Http404 try: shapefile = Shapefile.objects.get(id=shapefile_id, created_by=request.user) except Shapefile.DoesNotExist: 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 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" ) map.background = mapnik.Color("#fff") #defining the feature layer geometryField = utils.calcGeometryField(shapefile.geom_type) query = '(select ' + geometryField + ', id, id_relat as label from "layers_feature" WHERE shapefile_id = ' + str( shapefile.id) + ' AND id = ' + str(feature_id) + ') as geom' datasource = mapnik.PostGIS(host=dbSettings['HOST'], user=dbSettings['USER'], password=dbSettings['PASSWORD'], dbname=dbSettings['NAME'], port=dbSettings['PORT'], table=query, srid=3857, geometry_field=geometryField, simplify_geometries=True, geometry_table='"layers_feature"') featureLayer = mapnik.Layer("featureLayer") 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("featureLayerStyle") #defining the feature layer styles rule = mapnik.Rule() if shapefile.geom_type in [ "Point", "3D Point", "MultiPoint", "3D MultiPoint" ]: rule.symbols.append(mapnik.PointSymbolizer()) elif shapefile.geom_type in [ "LineString", "3D LineString", "MultiLineString", "3D MultiLineString" ]: rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) elif shapefile.geom_type in [ "Polygon", "3D Polygon", "MultiPolygon", "3D MultiPolygon" ]: rule.symbols.append( mapnik.PolygonSymbolizer(mapnik.Color("#f7edee"))) rule.symbols.append( mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5)) style = mapnik.Style() style.rules.append(rule) map.append_style("featureLayerStyle", style) label_rule = mapnik.Rule() label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black')) label.halo_radius = 4 label.allow_overlap = False label.avoid_edges = True label_rule.symbols.append(label) label_style = mapnik.Style() label_style.rules.append(label_rule) featureLayer.styles.append("featureLayerStyle_label") #add label to the map map.append_style("featureLayerStyle_label", label_style) #add new feature to the map map.layers.append(featureLayer) #rendering the map tile mapnik_xml_path = "../tilestache/%s/layers/vector/lightViewer/%s.xml" % ( str(request.user), str(shapefile.name)) mapnik.save_map(map, mapnik_xml_path) config = { "cache": { "name": "Test", "path": "../tilestache/%s" % (request.user), "umask": "0000", "dirs": "portable" }, "layers": { shapefile.name: { "provider": { "name": "mapnik", "mapfile": mapnik_xml_path }, "metatile": { "rows": 2, "columns": 2, "buffer": 64 }, "projection": "spherical mercator", "write cache": False } } } path = "/%s/%s/%s/%s.png" % (shapefile.name, zoom, x, y) config = TileStache.Config.buildConfiguration(config) type, bytes = TileStache.requestHandler(config, path) return HttpResponse(bytes, content_type="image/png") except: traceback.print_exc() return HttpResponse("")
studySiteDS = mapnik.Shapefile(file='StudySiteRegion.shp') studySiteLyr = mapnik.Layer('Study Site', '+init=epsg:4326') studySiteLyr.datasource = studySiteDS peruDS = mapnik.Shapefile(file='GRC_adm1.shp') peruLyr = mapnik.Layer('Peru', '+init=epsg:4326') peruLyr.datasource = peruDS cityNames = mapnik.Shapefile(file='places.shp') citiesLyr = mapnik.Layer('Cities', '+init=epsg:4326') citiesLyr.datasource = cityNames #point_symbolizer_cities = mapnik.PointSymbolizer()#mapnik.Color('#000000')) #citiesRules.symbols.append(point_symbolizer_cities) t = mapnik.TextSymbolizer(mapnik.Expression('[name]'), 'DejaVu Sans Book', 12, mapnik.Color('#000000')) #t.halo_fill = mapnik.Color('#FFFFFF') t.fill = mapnik.Color('#000000') t.avoid_edges = True #t.halo_radius = 0.5 t.label_placement = mapnik.label_placement.POINT_PLACEMENT #is default #dir(t) citiesRules.symbols.append(t) citiesStyles.rules.append(citiesRules) # to fill a polygon we create a PolygonSymbolizer polygon_symbolizer_peru = mapnik.PolygonSymbolizer(mapnik.Color('#F0FFF0')) pRules.symbols.append( polygon_symbolizer_peru) # add the symbolizer to the rule object # to add outlines to a polygon we create a LineSymbolizer
# s = mapnik.Style() # r = mapnik.Rule() # line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('red'),1) # r.symbols.append(line_symbolizer) # s.rules.append(r) # point_sym = mapnik.PointSymbolizer() # point_sym.allow_overlap = True # point_sym = mapnik.MarkersSymbolizer() # r.symbols.append(point_sym) # s.rules.append(r) basinsLabels = mapnik.TextSymbolizer(mapnik.Expression('[qgis]'), 'DejaVu Sans Bold', 3, mapnik.Color('yellow')) basinsLabels.halo_fill = mapnik.Color('Purple') basinsLabels.halo_radius = 1 r.symbols.append(basinsLabels) # point_sym = mapnik.PointSymbolizer() # point_sym.allow_overlap = True # point_sym = mapnik.MarkersSymbolizer() # r.symbols.append(point_sym) # s.rules.append(r) s.rules.append(r) m.append_style('Mellyn2', s) ds = mapnik.Shapefile(file="titik.shp") layer = mapnik.Layer('indonesia2')
r.symbols.append(polygon_symbolizer) s.rules.append(r) m.append_style('Sancaka1', s) ds = mapnik.Shapefile(file="propinsi/INDONESIA_PROP.shp") layer = mapnik.Layer('indonesia') layer.datasource = ds layer.styles.append('Sancaka1') m.layers.append(layer) #test s = mapnik.Style() r = mapnik.Rule() basinsLabels = mapnik.TextSymbolizer(mapnik.Expression('[nama]'), 'DejaVu Sans Bold', 3, mapnik.Color('red')) basinsLabels.halo_fill = mapnik.Color('yellow') basinsLabels.halo_radius = 1 r.symbols.append(basinsLabels) point_sym = mapnik.PointSymbolizer() point_sym.allow_overlap = True point_sym.opacity = 0.5 point_sym.file = () r.symbols.append(point_sym) point = mapnik.PointSymbolizer() r.symbols.append(point) s.rules.append(r)
def school_sheds_results(request=None, school_id=None, bbox=None, width=816, height=1056, srid=3857, format='png'): ''' Default height and width are 'Letter' ratio ''' format = format.encode('ascii') school = School.objects.get(pk=school_id) point = school.geometry circle = point.buffer(3400.0) m = mapnik.Map(int(width), int(height), "+init=epsg:" + str(srid)) mapnik.load_map(m, os.path.dirname(__file__) + "/basemap/basemap.xml") if bbox is None: circle.transform(srid) bbox = mapnik.Box2d(*circle.extent) m.zoom_to_box(bbox) #m.background = mapnik.Color('steelblue') # styles for sheds s = mapnik.Style() for name, color in (('0.5', VIOLET), ('1.0', PURPLE), ('1.5', LAVENDER), ('2.0', LIGHTCYAN)): r = mapnik.Rule() r.filter = mapnik.Expression("[name] = " + name) c = mapnik.Color(color) c.a = 80 line_symbolizer = mapnik.LineSymbolizer(mapnik.Color("gray"), 1) poly_symbolizer = mapnik.PolygonSymbolizer(c) r.symbols.append(line_symbolizer) r.symbols.append(poly_symbolizer) s.rules.append(r) # styles for schools school_colors = SCHOOL_COLORS for name, color in school_colors: r = mapnik.Rule() r.filter = mapnik.Expression("[name] = '" + name + "'") line_symbolizer = mapnik.LineSymbolizer() poly_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(color)) r.symbols.append(line_symbolizer) r.symbols.append(poly_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression( "[name] != 'map_title' and [name] != 'map_subtitle' and [name] != 'legend_title' and [name] != 'school'" ) text_symbolizer = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 9, mapnik.Color('black')) text_symbolizer.halo_fill = mapnik.Color('white') text_symbolizer.halo_radius = 1 text_symbolizer.horizontal_alignment = mapnik.horizontal_alignment.RIGHT #text_symbolizer.label_placement = mapnik.label_placement.VERTEX_PLACEMENT text_symbolizer.allow_overlap = True text_symbolizer.displacement = (12, 0) r.symbols.append(text_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression("[name] = 'map_title'") text_symbolizer = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 15, mapnik.Color('black')) text_symbolizer.horizontal_alignment = mapnik.horizontal_alignment.RIGHT text_symbolizer.halo_fill = mapnik.Color('white') text_symbolizer.allow_overlap = True r.symbols.append(text_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression("[name] = 'map_subtitle'") text_symbolizer = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 12, mapnik.Color('black')) text_symbolizer.horizontal_alignment = mapnik.horizontal_alignment.RIGHT text_symbolizer.halo_fill = mapnik.Color('white') text_symbolizer.allow_overlap = True r.symbols.append(text_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression("[name] = 'legend_title'") text_symbolizer = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Condensed Bold', 11, mapnik.Color('black')) text_symbolizer.horizontal_alignment = mapnik.horizontal_alignment.RIGHT text_symbolizer.halo_fill = mapnik.Color('white') text_symbolizer.halo_radius = 1 text_symbolizer.allow_overlap = True r.symbols.append(text_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression("[name] = 'legend_box'") poly_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color("white")) line_symbolizer = mapnik.LineSymbolizer(mapnik.Color("black"), 0.5) poly_symbolizer.fill_opacity = 0.8 r.symbols.append(line_symbolizer) r.symbols.append(poly_symbolizer) s.rules.append(r) r = mapnik.Rule() r.filter = mapnik.Expression("[name] = 'school'") ps = mapnik.PointSymbolizer( mapnik.PathExpression( os.path.dirname(__file__) + '/static/img/School.svg')) ps.transform = 'scale(0.06)' ps.allow_overlap = True #shield.label_placement = mapnik.label_placement.POINT_PLACEMENT r.symbols.append(ps) s.rules.append(r) m.append_style("surveys", s) def p2l(pct_x, pct_y): loc_x = bbox.minx + (bbox.maxx - bbox.minx) * pct_x / 100.0 loc_y = bbox.miny + (bbox.maxy - bbox.miny) * pct_y / 100.0 return (loc_x, loc_y) sheds = { 0.5: school.shed_05, 1.0: school.shed_10, 1.5: school.shed_15, 2.0: school.shed_20 } csv_string = 'wkt,name,label\n' for key, g in reversed(sorted(sheds.items(), key=lambda a: a[0])): if g is None: continue g.srid = 26986 g.transform(srid) csv_string += '"%s","%s",""\n' % (g.wkt, str(key)) surveys = Survey.objects.filter(school=school) for survey in surveys: survey.location.transform(srid) children = list(survey.child_set.all()) if len(children) > 0: for c in children: name = str(c.to_school) point = survey.location point.x += random.randint(-50, 50) point.y += random.randint(-50, 50) school_circle = point.buffer(50) csv_string += '"%s","%s",""\n' % (school_circle.wkt, name) else: name = "o" point = survey.location point.x += random.randint(-50, 50) point.y += random.randint(-50, 50) school_circle = point.buffer(50) csv_string += '"%s","%s",""\n' % (school_circle.wkt, name) #Add School geometry school.geometry.transform(srid) csv_string += '"%s","school","%s"\n' % (school.geometry.wkt, school.name) def box(minx, miny, maxx, maxy): lmin = Point(p2l(minx, miny)) lmax = Point(p2l(maxx, maxy)) lr = LinearRing((lmin.x, lmin.y), (lmax.x, lmin.y), (lmax.x, lmax.y), (lmin.x, lmax.y), (lmin.x, lmin.y)) poly = Polygon(lr) return poly legend = box(2, 108, 50, 113.5) csv_string += '"%s","%s","%s"\n' % (legend.wkt, "legend_box", "") xy = p2l(3.5, 112) point = Point(*xy) csv_string += '"%s","%s","School Commute Survey Results"\n' % (point.wkt, "map_title") xy = p2l(3.5, 109.5) point = Point(*xy) csv_string += '"%s","%s","%s, %s"\n' % (point.wkt, "map_subtitle", school, school.districtid) legend_x = 53 legend = box(legend_x, 97, 97.5, 113.5) csv_string += '"%s","%s","%s"\n' % (legend.wkt, "legend_box", "") xy = p2l(legend_x + 1.5, 112) point = Point(*xy) csv_string += '"%s","legend_title","Approx. home locations and travel to school mode"\n' % ( point.wkt, ) walksheds_x = 88 xy = p2l(walksheds_x, 112) point = Point(*xy) csv_string += '"%s","legend_title","Walksheds"\n' % (point.wkt, ) y = 111.5 for name, label in school_colors: y -= 1.8 xy = p2l(legend_x + 2, y) point = Point(*xy) circle = point.buffer(50) csv_string += '"%s","%s","%s"\n' % (circle.wkt, name, MODE_DICT[name]) y = 110 for name in ( '0.5', '1.0', '1.5', '2.0', ): y -= 2.4 ws = box(walksheds_x, y, walksheds_x + 2, y + 1.5) csv_string += '"%s","%s","%s Mile"\n' % (ws.wkt, name, name) layer = mapnik.Layer('surveys', "+init=epsg:" + str(srid)) ds = mapnik.Datasource(type="csv", inline=csv_string.encode('ascii')) layer.datasource = ds layer.styles.append('surveys') m.layers.append(layer) # Render to image if format == 'pdf': tmp_file = tempfile.NamedTemporaryFile() surface = cairo.PDFSurface(tmp_file.name, m.width, m.height) mapnik.render(m, surface) surface.finish() tmp_file.seek(0) im = tmp_file.read() else: im = mapnik.Image(m.width, m.height) mapnik.render(m, im) im = im.tostring(format) response = HttpResponse() response['Content-length'] = str(len(im)) response['Content-Type'] = mimetypes.types_map['.' + format] response.write(im) return response
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)