Ejemplo n.º 1
0
    def __call__(self, feature_layers):
        # take the feature_layers dict and generate a gif response

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

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

        layer.datasource = memds

        m = mapnik.Map(256, 256)

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

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

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

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

        return png_contents
Ejemplo n.º 2
0
def qickTest():
    
    m = mapnik.Map(600,300)
    m.background = mapnik.Color('steelblue')
    s = mapnik.Style()
    r = mapnik.Rule()
    #polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#ff00ff'))
    #r.symbols.append(polygon_symbolizer)
    
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(100%,100%,100%)'),0.1)
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My Style',s)
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(100%,0%,100%)'),0.5)
    r.symbols.append(line_symbolizer)
    s.rules.append(r)
    m.append_style('My New Style',s)
    ds = mapnik.Shapefile(file = '/home/klammer/Software/Quickly/tilegen/data/media/testdaten/mercator_polygon/lines-vgtl-27-01-12.shp')
    layer = mapnik.Layer('world')
    layer.datasource = ds
    layer.styles.append('My Style')
    m.layers.append(layer)
    
    lyr = mapnik.Layer('Generalized geometry from PostGIS')
    lyr.datasource = mapnik.PostGIS(host='localhost',user='******',password='******',dbname='meingis',table='generalized_line_cache')
    lyr.srs = layer.srs
    lyr.styles.append('My New Style')
    m.layers.append(lyr)

    
    m.zoom_all()
    mapnik.render_to_file(m,'world.png', 'png')
    print "rendered image to 'world.png'"
Ejemplo n.º 3
0
def render(qs,options):
    kwargs = {}
    if options:
        if ';' in options:
            for item in options.split(';'):
                if ':' in item:
                    k,v = item.split(':')
                    kwargs[k] = v

    width = int(kwargs.get('width',600))
    height = int(kwargs.get('height',600))
    #field = kwargs.get('field',None)
    if hasattr(qs,'_meta'):
        # it looks like a model
        qs = qs.objects.all()
    m = mapnik.Map(width,height)
    m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_CANVAS
    adapter = PostgisLayer(qs)
    lyr = adapter.to_mapnik()
    sty = adapter.get_default_style()
    lyr.styles.append('style')
    m.append_style('style',sty)
    #m.background = mapnik.Color('green')
    m.srs = lyr.srs
    m.layers.append(lyr)
    m.zoom_all()
    #print mapnik.save_map_to_string(m)
    mod = qs.query.get_meta().module_name
    # TODO - need way to properly cache vs. always overwriting...
    name = '%s_%s_%s_%s.png' % (mod,width,height,random())
    map_graphic = os.path.join(graphics,name)
    mapnik.render_to_file(m,str(map_graphic))
    url = os.path.join(settings.MEDIA_URL,'mapgraphics',name)
    return mark_safe(force_unicode('<img src="%s" />' % smart_str(url)))
    def drawSHPFile(self):
        #Loop thru related files list.
        for fileName in self.relatedFiles:
            self.downloadFile(self.confSHPDownloadsLoc, fileName)
        #Create a map with a given width and height in pixels.
        # Map
        m = mapnik.Map(600,300,'+proj=latlong +datum=WGS84')
        m.background = mapnik.Color('steelblue')

        # Styles
        poly = mapnik.PolygonSymbolizer(mapnik.Color('lavender'))
        line = mapnik.LineSymbolizer(mapnik.Color('slategray'),.3)
        s,r = mapnik.Style(),mapnik.Rule()
        r.symbols.extend([poly,line])
        s.rules.append(r)
        m.append_style('My Style',s)

        # Layer
        lyr = mapnik.Layer('world')
        lyr.datasource = mapnik.Shapefile(file=self.confSHPDownloadsLoc+'ne_110m_admin_0_countries')
        lyr.srs = '+proj=latlong +datum=WGS84'
        lyr.styles.append('My Style')
        m.layers.append(lyr)

        # Render
        m.zoom_to_box(lyr.envelope())
        mapnik.render_to_file(m, 'hello_world_in_pure_python.png')
Ejemplo n.º 5
0
 def test_mapnik(self):
     m = mapnik.Map(600, 300)
     mapnik.load_map(m, 'style_sheet.xml')
     m.zoom_all()
     mapnik.render_to_file(m, actual_image)
     with open(actual_image) as actual, open(expected_image) as expected:
         self.assertEquals(actual.read(), expected.read())
Ejemplo n.º 6
0
    def render(self, fmt, width, height, bbox, srs, styles, layers, **kwargs):
        """Render a WMS request or a tile.  TODO - create an SQLite cache for this as well, based on hashed filename."""

        _log.debug('render called for {0}'.format(layers))
        if srs.lower().startswith('epsg'):
            if srs.endswith("900913") or srs.endswith("3857"):
                srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null"
            else:
                srs = "+init=" + srs.lower()

        name = self.prepare_wms(layers, srs, styles, **kwargs)
        filename = "{name}.{bbox}.{width}x{height}.{fmt}".format(
            name=name,
            bbox='_'.join(str(b) for b in bbox),
            width=width,
            height=height,
            fmt=fmt
        )

        _log.debug('waiting on lock')
        while os.path.exists(name + ".lock"):
            time.sleep(0.05)

        _log.debug('rendering {0}x{1} tile'.format(width, height))
        m = mapnik.Map(width, height)
        mapnik.load_map(m, (name + '.xml').encode('ascii'))
        m.zoom_to_box(mapnik.Box2d(*bbox))
        mapnik.render_to_file(m, filename, fmt)

        with open(filename) as tiledata:
            tile = buffer(tiledata.read())
        os.unlink(filename)

        return filename, tile
Ejemplo n.º 7
0
def make_map(shpfile, img_name):
  lyr = mapnik.Layer('world', "+proj=latlong +datum=NAD83")
  lyr.datasource = mapnik.Shapefile(file=shpfile)
  lyr.styles.append('My Style')
  m.layers.append(lyr)
  m.zoom_to_box(lyr.envelope())
  mapnik.render_to_file(m, img_name, 'png')
Ejemplo n.º 8
0
 def render_to_file(self,*args):
     """
     Routine to render the requested AGG format.
     """
     format = args[2]
     if format in ('tif','tiff'):
         self.timer()
         (handle, png_tmp) = tempfile.mkstemp('.png', 'nik2img-tmp')
         os.close(handle)
         self.world_file_ext = 'wld'
         self.write_wld(png_tmp)
         im = mapnik.Image(args[0].width,self.m.height)
         if self.scale_factor:
             mapnik.render(args[0],im,self.scale_factor)
         else:
             mapnik.render(args[0],im)
         im.save(png_tmp,'png')
         # todo - figure out more reasonable defaults
         opts = ' -ot Byte -co COMPRESS=JPEG -co JPEG_QUALITY=100'
         base_cmd = 'gdal_translate %s %s -a_srs "%s" %s'
         cmd = base_cmd % (png_tmp,args[1],args[0].srs,opts)
         #print call(cmd,fail=True)
         os.system(cmd)
         self.stop()
     else:
         self.timer()
         if self.scale_factor:
             args = args + (self.scale_factor,)
         mapnik.render_to_file(*args)
         if self.world_file_ext:
             self.write_wld(args[1])
         self.stop()
     if self.zip_compress:
         self.zip_up(args[1])
Ejemplo n.º 9
0
 def render_agg(self, *args):
     """
     Routine to render the requested AGG format.
     """
     mapnik.render_to_file(*args)
     if self.world_file_ext:
         self.write_wld(args[1])
Ejemplo n.º 10
0
 def generate_img(self):
     print "\n- Render image"
     m = mapnik.Map(600, 300)
     mapnik.load_map(m, self.stylesheet)
     m.zoom_all()
     mapnik.render_to_file(m, self.image)
     print "rendered image to '{0}'".format(self.image)
Ejemplo n.º 11
0
    def render_png(self, show=True):
        import mapnik
        #TODO scale dimensions to aspect ratio of data
        m = mapnik.Map(800, 400)
        m.background = mapnik.Color('white')
        s = mapnik.Style()
        r = mapnik.Rule()

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

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

        s.rules.append(r)
        m.append_style('My Style', s)
        ds = mapnik.Shapefile(file=self.path)
        layer = mapnik.Layer('world')
        layer.datasource = ds
        layer.styles.append('My Style')
        m.layers.append(layer)
        m.zoom_all()
        outfile = '/tmp/world.png'
        mapnik.render_to_file(m, outfile, 'png')
        if show:
            im = Image.open(outfile)
            im.show()
        return outfile
Ejemplo n.º 12
0
def render(input_file, output_file, width=800, height=800, bbox=None):
    m = mapnik.Map(width, height)
    mapnik.load_map(m, input_file, False)
    if bbox is not None:
        m.zoom_to_box(bbox)
    else:
        m.zoom_all()
    mapnik.render_to_file(m, output_file)
Ejemplo n.º 13
0
    def export(self, mapnik_xml, output_file):
        self.log.info("Exporting %s to %s. Mapnik version %s", mapnik_xml, output_file,
                      mapnik.mapnik_version_string())

        mapnik_map = mapnik.Map(2000, 2000)
        mapnik.load_map(mapnik_map, mapnik_xml.encode('utf-8'))
        mapnik_map.zoom_all()
        mapnik.render_to_file(mapnik_map, output_file, b"pdf")
Ejemplo n.º 14
0
def render(filename, width):
    print 'Rendering style "%s" with width %d' % (filename, width)
    m = mapnik.Map(width, 100)
    mapnik.load_map(m, os.path.join(dirname, "%s.xml" % filename), False)
    bbox = mapnik.Box2d(-0.05, -0.01, 0.95, 0.01)
    m.zoom_to_box(bbox)
    mapnik.render_to_file(m, "%s-%d-agg.png" % (filename, width))
    return m
Ejemplo n.º 15
0
 def saveImage(self, mapFilename, imgFilename):
     if self.m is None:
         self.m = mapnik.Map(self.width, self.height)
     mapnik.load_map(self.m, mapFilename)
     # extent = mapnik.Box2d(-300, -180.0, 90.0, 90.0)
     # self.m.zoom_to_box(self.extents)
     self.m.zoom_all()
     mapnik.render_to_file(self.m, imgFilename)
Ejemplo n.º 16
0
 def render_to_file(self,*args):
     """
     Routine to render the requested AGG format.
     """
     self.timer()
     mapnik.render_to_file(*args)
     self.stop()
     if self.world_file_ext:
         self.write_wld(args[1])
Ejemplo n.º 17
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik.Map(800, 600)
    mapnik.load_map(m, mapxmlfile)
    mapnik.save_map(m, mapxmloutputfile)
    m.zoom_all()
    mapnik.render_to_file(m, outputfile)
Ejemplo n.º 18
0
	def renderImage(self, map_output, mapfile, imgx, imgy, bbox):
		print "renderImage"
		m = mapnik.Map(imgx, imgy)
		mapnik.load_map(m, mapfile)
		#ll = (1321613.269848, 6475998.706584, 1674460.199655, 6743324.6719772)
		ll = (1321613.269848, 6475998.706584, 1674460.199655, 6743324.671977)
		ll = bbox
		bbox = mapnik.Box2d(mapnik.Coord(ll[0], ll[3]), mapnik.Coord(ll[2], ll[1]))
		m.zoom_to_box(bbox)
		mapnik.render_to_file(m, map_output)
Ejemplo n.º 19
0
    def test_psql_error_should_give_back_connections_opened_for_lower_layers_to_the_pool():
        map1 = mapnik.Map(600,300)
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9')))
        s.rules.append(r)
        map1.append_style('style',s)

        # This layer will fail after a while
        buggy_s = mapnik.Style()
        buggy_r = mapnik.Rule()
        buggy_r.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('#ff0000')))
        buggy_r.filter = mapnik.Filter("[fips] = 'FR'")
        buggy_s.rules.append(buggy_r)
        map1.append_style('style for buggy layer',buggy_s)
        buggy_layer = mapnik.Layer('this layer is buggy at runtime')
        # We ensure the query wille be long enough
        buggy_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='(SELECT geom as geom, pg_sleep(0.1), fips::int from world_merc) as failure_tabl',
            max_async_connection=2, max_size=2,asynchronous_request = True, geometry_field='geom')
        buggy_layer.styles.append('style for buggy layer')

        # The query for this layer will be sent, then the previous layer will raise an exception before results are read
        forced_canceled_layer = mapnik.Layer('this layer will be canceled when an exception stops map rendering')
        forced_canceled_layer.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        forced_canceled_layer.styles.append('style')

        map1.layers.append(buggy_layer)
        map1.layers.append(forced_canceled_layer)
        map1.zoom_all()
        map2 = mapnik.Map(600,300)
        map2.background = mapnik.Color('steelblue')
        s = mapnik.Style()
        r = mapnik.Rule()
        r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
        r.symbols.append(mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1))
        s.rules.append(r)
        map2.append_style('style',s)
        layer1 = mapnik.Layer('layer1')
        layer1.datasource = mapnik.PostGIS(dbname=MAPNIK_TEST_DBNAME,table='world_merc',
            max_async_connection=2, max_size=2, asynchronous_request = True, geometry_field='geom')
        layer1.styles.append('style')
        map2.layers.append(layer1)
        map2.zoom_all()

        # We expect this to trigger a PSQL error
        try:
            mapnik.render_to_file(map1,'world.png', 'png')
            # Test must fail if error was not raised just above
            eq_(False,True)
        except RuntimeError:
            pass
        # This used to raise an exception before correction of issue 2042
        mapnik.render_to_file(map2,'world2.png', 'png')
Ejemplo n.º 20
0
def test_render_points():

    if not mapnik.has_cairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    f = mapnik.Feature(context,1)
    f['Name'] = 'Westernmost Point'
    f.add_geometries_from_wkt('POINT (142.48 -38.38)')
    ds.add_feature(f)

    f = mapnik.Feature(context,2)
    f['Name'] = 'Southernmost Point'
    f.add_geometries_from_wkt('POINT (143.10 -38.60)')
    ds.add_feature(f)

    # create layer/rule/style
    s = mapnik.Style()
    r = mapnik.Rule()
    symb = mapnik.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik.Layer('Places','+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    lyr.datasource = ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik.Coord(142.30,-38.20)
    lr_lonlat = mapnik.Coord(143.40,-38.80)
    # render for different projections 
    projs = { 
        'google': '+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 +wktext +no_defs +over',
        'latlon': '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
        }
    for projdescr in projs.iterkeys():
        m = mapnik.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels',s)
        m.layers.append(lyr)
        dest_proj = mapnik.Projection(projs[projdescr])
        src_proj = mapnik.Projection('+init=epsg:4326')
        tr = mapnik.ProjTransform(src_proj,dest_proj)
        m.zoom_to_box(tr.forward(mapnik.Box2d(ul_lonlat,lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        svg_file = os.path.join(tempfile.gettempdir(), 'mapnik-render-points-%s.svg' % projdescr)
        mapnik.render_to_file(m, svg_file)
        num_points_present = len(ds.all_features())
        svg = open(svg_file,'r').read()
        num_points_rendered = svg.count('<image ')
        eq_(num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr)) 
Ejemplo n.º 21
0
def show(lyr,sty,width=400,height=300,filename=None,app=None):
    m = mapnik.Map(width,height,lyr.srs)
    m.background = mapnik.Color('transparent')
    lyr.styles.append('style')
    m.append_style('style',sty)
    m.layers.append(lyr)
    m.zoom_all()
    if not filename:
        (handle, filename) = tempfile.mkstemp('.png', 'django-map-')
        os.close(handle)
    mapnik.render_to_file(m,str(filename))
    open_image(str(filename))
    return m
Ejemplo n.º 22
0
def toMapnik(shapefile, destfile):
    symbolizer = mapnik.PolygonSymbolizer(mapnik.Color("darkgreen"))
    rule = mapnik.Rule()
    rule.symbols.append(symbolizer)
    style = mapnik.Style()
    style.rules.append(rule)
    layer = mapnik.Layer("mapLayer")
    layer.datasource = mapnik.Shapefile(file=shapefile)
    layer.styles.append("mapStyle")
    mapk = mapnik.Map(800, 400)
    mapk.background = mapnik.Color("steelblue")
    mapk.append_style("mapStyle", style)
    mapk.layers.append(layer)
    mapk.zoom_all()
    mapnik.render_to_file(mapk, destfile, "png")
Ejemplo n.º 23
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik.Map(800, 600)
    try:
        mapnik.load_map(m, mapxmlfile)
        mapnik.save_map(m, mapxmloutputfile)
        m.zoom_all()
        mapnik.render_to_file(m, outputfile)
    except RuntimeError,e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
Ejemplo n.º 24
0
def render(filename, width, height, bbox):
    print "-"*80
    print "Rendering style \"%s\" with size %dx%d ... " % (filename, width, height)
    print "-"*80
    m = mapnik.Map(width, height)
    mapnik.load_map(m, os.path.join(dirname, "styles", "%s.xml" % filename), False)
    if bbox is not None:
        m.zoom_to_box(bbox)
    else:
        m.zoom_all()
    basefn = os.path.join(dirname, "images", '%s-%d' % (filename, width))
    mapnik.render_to_file(m, basefn+'-agg.png')
    diff = compare(basefn + '-agg.png', basefn + '-reference.png')
    if diff > 0:
        print "-"*80
        print 'Error: %u different pixels' % diff
        print "-"*80

    return m
Ejemplo n.º 25
0
def basemap(dateval):
	import sys
	import datetime
	import mapnik
	d0 = datetime.date(2008,2,1)
	f = open('dateinc.inc', 'w')
	ddif = dateval - d0
	f.write(str(ddif.days))
	f.close()
	f = open('texte_date.inc', 'w')
	td = datetime.date.today()
	if ((dateval - td).days > 0):
		f.write(td.strftime('\'%Y-%m-%d\''))
	else:
		f.write(dateval.strftime('\'%Y-%m-%d\''))
	f.close()	
#	bbox = mapnik.Envelope(mapnik.Coord(80000,6000000), mapnik.Coord(1250000,7150000))
#	proportions 4x3
	xmin = -49000
	xmax = 1391000
	ymin = 6040000
	ymax = 7120000
#	proportions 16x9
	xmin = -289000
	xmax = 1631000
	ymin = 6040000
	ymax = 7120000
	e = open('extent.inc', 'w')
	e.write(str(xmin) + ',' + str(ymin) +',' + str(xmax) + ',' + str(ymax))
	e.close()
	bbox = mapnik.Envelope(mapnik.Coord(xmin,ymin), mapnik.Coord(xmax,ymax))
	mapfile = "animfla.xml"
#	m = mapnik.Map(640, 480)
#	m = mapnik.Map(800, 600)
	m = mapnik.Map(1280, 720)
#	m = mapnik.Map(960, 540)
	mapnik.load_map(m, mapfile)
	m.zoom_to_box(bbox) 
	mapnik.render_to_file(m, 'png\\'+dateval.strftime('%Y%m%d')+'.png', 'png')

	
Ejemplo n.º 26
0
def test_render_points():

    if not mapnik.has_cairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik.PointDatasource()
    places_ds.add_point(142.48,-38.38,'Name','Westernmost Point') # westernmost
    places_ds.add_point(143.10,-38.60,'Name','Southernmost Point') # southernmost
    # create layer/rule/style
    s = mapnik.Style()
    r = mapnik.Rule()
    symb = mapnik.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik.Layer('Places','+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik.Coord(142.30,-38.20)
    lr_lonlat = mapnik.Coord(143.40,-38.80)
    # render for different projections 
    projs = { 
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
        }
    for projdescr in projs.iterkeys():
        m = mapnik.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels',s)
        m.layers.append(lyr)
        p = mapnik.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik.Box2d(ul_lonlat,lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        svg_file = '/tmp/%s.svg'
        mapnik.render_to_file(m, svg_file)
        num_points_present = len(places_ds.all_features())
        svg = open(svg_file,'r').read()
        num_points_rendered = svg.count('<image ')
        eq_(num_points_present, num_points_rendered, "Not all points were rendered (%d instead of %d) at projection %s" % (num_points_rendered, num_points_present, projdescr)) 
Ejemplo n.º 27
0
def render(input_file, output_file, width=800, height=800, bounds=None):
    m = mk.Map(width, height)
    mk.load_map(m, input_file, False)
    if bounds is not None:
        bbox = m.Envelope(*bounds)
        m.zoom_to_box(bbox)
    else:
        m.zoom_all()
    
    if output_file[-4:] in ['.png','.tif','.jpg']:
        mk.render_to_file(m, output_file)
    elif output_file[-4:] == '.pdf':
        s = cairo.PDFSurface(output_file, width, height)
        mk.render(m, s)
        s.finish()
    elif output_file[-4:] == '.svg':
        s = cairo.SVGSurface(output_file, width, height)
        mk.render(m, s)
        s.finish()
    else:
        print "Error: output file extension '{}' not understood".format(output_file)
Ejemplo n.º 28
0
 def render(self, **kwargs):
     m = mapnik.Map(kwargs['width'], kwargs['height'], '+init=epsg:' + str(kwargs['epsg']))
     s = mapnik.Style()
     r = mapnik.Rule()
     polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color(str(kwargs['color'])))
     polygon_symbolizer.fill_opacity = kwargs['opacity']
     r.symbols.append(polygon_symbolizer)
     line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'), 1.0)
     r.symbols.append(line_symbolizer)
     point_symbolizer = mapnik.PointSymbolizer()
     r.symbols.append(point_symbolizer)
     s.rules.append(r)
     m.append_style('My Style', s)
     ds = mapnik.Ogr(string=json.dumps(kwargs['geojson']), layer='OGRGeoJSON')
     layer = mapnik.Layer('wkt', '+init=epsg:' + str(kwargs['epsg']))
     layer.datasource = ds
     layer.styles.append('My Style')
     m.layers.append(layer)
     extent = mapnik.Box2d(kwargs['bbox'][0], kwargs['bbox'][1], kwargs['bbox'][2], kwargs['bbox'][3])
     m.zoom_to_box(extent)
     mapnik.render_to_file(m, str(kwargs['filename']), str(kwargs['filetype']))
Ejemplo n.º 29
0
def render(filename, width, height, bbox, quiet=False):
    if not quiet:
        print "Rendering style \"%s\" with size %dx%d ... \x1b[1;32m✓ \x1b[0m" % (filename, width, height)
        print "-"*80
    m = mapnik.Map(width, height)
    mapnik.load_map(m, os.path.join(dirname, "styles", "%s.xml" % filename), False)
    if bbox is not None:
        m.zoom_to_box(bbox)
    else:
        m.zoom_all()
    expected = os.path.join(dirname, "images", '%s-%d-reference.png' % (filename, width))
    if not os.path.exists('/tmp/mapnik-visual-images'):
        os.makedirs('/tmp/mapnik-visual-images')
    actual = os.path.join("/tmp/mapnik-visual-images", '%s-%d-agg.png' % (filename, width))
    mapnik.render_to_file(m, actual)
    diff = compare(actual, expected)
    if diff > 0:
        print "-"*80
        print '\x1b[33mError:\x1b[0m %u different pixels' % diff
        print "-"*80

    return m
Ejemplo n.º 30
0
def main():
    # creates the map 
    m = mapnik.Map(1200,600)

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

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

    # Styles - If style is not defined, then it's not drawed
    # Polygon style (countries)
    polygon_symbolizer = mapnik.PolygonSymbolizer(mapnik.Color('#f2eff9'))
    r.symbols.append(polygon_symbolizer)

    # Line style
    line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('rgb(50%,50%,50%)'),0.1)
    r.symbols.append(line_symbolizer)

    # Point style (default)
    point_symbolizer = mapnik.PointSymbolizer()
    r.symbols.append(point_symbolizer)

    s.rules.append(r)
    m.append_style('My Style',s)

    # World Map Layer
    layer = create_layer('world','resources/ne_110m_admin_0_countries.shp','My Style')
    m.layers.append(layer)
    # Ivory Coast Layer
    layer2 = create_layer('points','resources/antennas.shp','My Style')
    m.layers.append(layer2)

    # Zoom to layer 2 boundaries
    m.zoom_to_box(layer2.envelope())

    mapnik.render_to_file(m,'ivory.png', 'png')
labelStyle.rules.append(rule)

# Setup our datasource:

datasource = mapnik.Shapefile(file="TM_WORLD_BORDERS-0.3/" +
                              "TM_WORLD_BORDERS-0.3.shp")

# Define our map layers:

polygonLayer = mapnik.Layer("Polygons")
polygonLayer.datasource = datasource
polygonLayer.styles.append("PolygonStyle")

labelLayer = mapnik.Layer("Labels")
labelLayer.datasource = datasource
labelLayer.styles.append("LabelStyle")

# Setup our Map object:

map = mapnik.Map(MAP_WIDTH, MAP_HEIGHT, "+proj=longlat +datum=WGS84")
map.background = mapnik.Color("#8080a0")

map.append_style("PolygonStyle", polygonStyle)
map.append_style("LabelStyle", labelStyle)

map.layers.append(polygonLayer)
map.layers.append(labelLayer)

map.zoom_to_box(mapnik.Box2d(MIN_LONG, MIN_LAT, MAX_LONG, MAX_LAT))
mapnik.render_to_file(map, "map.png")
Ejemplo n.º 32
0
#! /usr/bin/env /usr/bin/python3

import mapnik

map = mapnik.Map(600,300)

mapnik.load_map(map, 'gamma.xml')

map.zoom_all()
map.zoom(-1.1)

mapnik.render_to_file(map, 'gamma.png', 'png')

Ejemplo n.º 33
0
def createisomap(iso, mapscale, name, name_en):

    map_width = int(mapscale[0])
    map_height = int(mapscale[1])

    map_minx = float(mapscale[2])
    map_maxx = float(mapscale[3])
    map_miny = float(mapscale[4])
    map_maxy = float(mapscale[5])

    print("mapdata:", map_width, map_height, map_maxx, map_maxy, map_minx,
          map_miny)

    geojsonfile = '/osm/service/' + CONTINENT + '/' + iso + '/poly/osm.geojson'

    m = mapnik.Map(
        map_width,
        map_height)  # create a map with a given width and height in pixels
    # note: m.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    # the 'map.srs' is the target projection of the map and can be whatever you wish
    m.background = mapnik.Color(
        '#000000')  # set background colour to 'steelblue'.

    s = mapnik.Style()  # style object to hold rules
    r = mapnik.Rule()  # rule object to hold symbolizers
    # to fill a polygon we create a PolygonSymbolizer

    psymbolizer = mapnik.PolygonSymbolizer()
    #psymbolizer.fill = mapnik.Color('#f2eff9')
    psymbolizer.fill = mapnik.Color('#000000')
    r.symbols.append(psymbolizer)

    lsymbolizer = mapnik.LineSymbolizer()
    #lsymbolizer.stroke = mapnik.Color('rgb(50%,50%,50%)')
    lsymbolizer.stroke = mapnik.Color('#FFA500')
    lsymbolizer.stroke_width = 0.8
    r.symbols.append(lsymbolizer)

    s.rules.append(r)  # now add the rule to the style and we're done

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

    ds = mapnik.Ogr(file=geojsonfile, layer_by_index=0)
    print(ds)

    ds.envelope()

    layer = mapnik.Layer(
        'world')  # new layer called 'world' (we could name it anything)
    # note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'

    layer.datasource = ds
    layer.styles.append('My Style')

    m.layers.append(layer)

    bbox = mapnik.Box2d(map_maxx, map_maxy, map_minx, map_miny)
    m.zoom_to_box(bbox)

    # Write the data to a png image called world.png the current directory

    img_directory = '/osm/service/' + CONTINENT + '/' + iso + '/img/'
    if not os.path.exists(img_directory):
        os.makedirs(img_directory)

    os.system("rm -f " + img_directory + "*")

    mapnik.render_to_file(m, img_directory + 'dbackground0.png', 'png')

    gdalw1 = 'gdalwarp    -te {} {} {} {}  -ts {} {} '.format(
        map_minx, map_miny, map_maxx, map_maxy, map_width, map_height)
    # NE1_HR_LC_SR_W_DR.tif
    gdalw2 = ' -of GTiff   /osm/ne/ne.tif {}  '.format(img_directory +
                                                       'nebackground.geotif')

    print("gdalw:", gdalw1, gdalw2)

    os.system(gdalw1 + gdalw2)

    os.system('gdal_translate -of PNG  {} {} '.format(
        img_directory + 'nebackground.geotif',
        img_directory + 'nebackground.png'))

    os.system('convert   {} -transparent Black {} '.format(
        img_directory + 'dbackground0.png',
        img_directory + 'tdbackground.png'))
    os.system('composite {} -compose over   {} {} '.format(
        img_directory + 'tdbackground.png', img_directory + 'nebackground.png',
        img_directory + 'dbackground.png'))

    ######################  flag ##################################

    im_cmd1 = r'convert /osm/setup/osmlogo.png -font DejaVu-Serif -fill darkblue  -pointsize 34 -gravity center -draw "text 16,-18'
    im_cmd2 = r" '." + iso[:2] + "' "
    im_cmd3 = r'"  ' + img_directory + 'dflag.png'

    os.system(im_cmd1 + im_cmd2 + im_cmd3)

    ####################  Logo #####################################

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 448, 98)
    ctx = cairo.Context(surface)
    ctx.select_font_face("Courier", cairo.FONT_SLANT_NORMAL,
                         cairo.FONT_WEIGHT_BOLD)

    ctx.set_font_size(42)
    ctx.move_to(2, 50)
    ctx.set_source_rgb(0.0, 0.0, 0.15)
    ctx.show_text('Taginfo-' + CONTINENT + '-' + iso)

    ctx.select_font_face('Sans')
    if len(name_en) > 26:
        ctx.set_font_size(20)
    elif len(name_en) > 18:
        ctx.set_font_size(26)
    else:
        ctx.set_font_size(30)

    ctx.move_to(1, 90)
    ctx.set_source_rgb(0.0, 0.0, 0.35)
    ctx.show_text(name_en)

    # finish up
    ctx.stroke()
    surface.write_to_png(img_directory + 'dlogo.png')
Ejemplo n.º 34
0
import os
import mapnik
from helper.textool import get_tmp_file

stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '.xml'

# image = 'xx_world_style_from_xml.png'
m = mapnik.Map(600, 150)
mapnik.load_map(m, stylesheet)
m.zoom_all()
# m.background = mapnik.Color('steelblue')

# bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
bbox = mapnik.Box2d(-1, -1, 8, 1)
m.zoom_to_box(bbox)
mapnik.render_to_file(m, get_tmp_file(__file__, 1))
mapnik.render_to_file(m, get_tmp_file(__file__, 1, file_ext='pdf'))

# stylesheet = os.path.splitext(os.path.realpath(__file__))[0] + '1.xml'
#
# # image = 'xx_world_style_from_xml.png'
# m = mapnik.Map(600, 300)
# mapnik.load_map(m, stylesheet)
# m.zoom_all()
# # m.background = mapnik.Color('steelblue')
#
# # bbox = mapnik.Box2d(118, 36.6, 124.6, 40.7)
#
# m.zoom_to_box(bbox)
# mapnik.render_to_file(m, get_tmp_file(__file__, 2), 'png')
Ejemplo n.º 35
0
#!/usr/bin/env python3

import mapnik

mapfile = 'ready_style.xml'
map_output = 'mymap.png'
ll = (55.8851814, 37.6125984)

merc = 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'
)
longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')

m = mapnik.Map(800, 600)
mapnik.load_map(m, mapfile)
#bbox=mapnik.Box2d(37.1,55.45,38,56.05)
#bbox=mapnik.Box2d(37.6020,55.7107,37.6087,55.7137365)
bbox = mapnik.Box2d(ll[1] - 0.0033, ll[0] - 0.00151825, ll[1] + 0.0033,
                    ll[0] + 0.00151825)
transform = mapnik.ProjTransform(longlat, merc)
merc_bbox = transform.forward(bbox)

m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_BBOX

m.zoom_to_box(merc_bbox)
print("Scale = ", m.scale())
print(mapnik.mapnik_version())
mapnik.render_to_file(m, map_output)
Ejemplo n.º 36
0
point_sym = mapnik.MarkersSymbolizer()
point_sym.filename = 'D:/Tugas 2/gambar.png'
point_sym.width = mapnik.Expression("10")
point_sym.height = mapnik.Expression("10")
point_sym.allow_overlap = True
r.symbols.append(point_sym)

text_sym = mapnik.TextSymbolizer(mapnik.Expression('[Propinsi]'),'DejaVu Sans Bold',5,mapnik.Color('black'))
text_sym.halo_radius = 1
text_sym.allow_overlap = True
text_sym.avoid_edges = False
r.symbols.append(text_sym)

s.rules.append(r)
m.append_style('bonbin',s)

ds = mapnik.MemoryDatasource()
f = mapnik.Feature(mapnik.Context(),1)
f['Propinsi'] = 'Kebun Binatang Surabaya'
f.add_geometries_from_wkt("POINT(112.736111 -7.295833)")
ds.add_feature(f)

player = mapnik.Layer('bonbin_layer')
player.datasource = ds
player.styles.append('bonbin')
m.layers.append(player)

m.zoom_all()
mapnik.render_to_file(m,'world.pdf','pdf')
print "rendered image to 'world.pdf"
    m = mapnik.Map(width, height)
    mapnik.load_map(m, mapfile)

    # ensure the target map projection is mercator
    m.srs = merc.params()

    # transform the centre point into the target coord sys
    centre = mapnik.Coord(centrex, centrey)
    transform = mapnik.ProjTransform(longlat, merc)
    merc_centre = transform.forward(centre)

    # 360/(2**zoom) degrees = 256 px
    # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
    # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
    dx = ((20037508.34 * 2 * (width / 2))) / (256 * (2**(zoom)))
    minx = merc_centre.x - dx
    maxx = merc_centre.x + dx

    # grow the height bbox, as we only accurately set the width bbox
    m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

    bounds = mapnik.Box2d(
        minx, merc_centre.y - 10, maxx, merc_centre.y +
        10)  # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT
    m.zoom_to_box(bounds)

    # render the map image to a file
    mapnik.render_to_file(m, output, formt, scale_factor)

    sys.stdout.write('output image to %s!\n' % output)
Ejemplo n.º 38
0
import mapnik
m = mapnik.Map(700,400)
m.background = mapnik.Color('steelblue')
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer()
polygon_symbolizer.fill = mapnik.Color('#000000')
r.symbols.append(polygon_symbolizer)

line_symbolizer = mapnik.LineSymbolizer()
line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('Yello'),1)
line_symbolizer.stroke_width = 10.0

r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style('Yoesril',s)
ds = mapnik.Shapefile(file="ne_110m_admin_0_countries.shp")
layer = mapnik.Layer('world')
layer.datasource = ds
layer.styles.append('Yoesril')
m.layers.append(layer)
m.zoom_all()
mapnik.render_to_file(m,'world3.JPEG', 'JPEG')
print "rendered image to 'world3.JEPG' "
Ejemplo n.º 39
0
ds = mapnik.Shapefile(file="mapecuador/map.shp")
layer = mapnik.Layer('provinsiecuador')
layer.datasource = ds
layer.styles.append('Sancaka4')
m.layers.append(layer)
# BATAS MAP 4 EKUADOR

# MAP 5 Australia
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer()
polygon_symbolizer.fill = mapnik.Color('#FF00FF')
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)
s.rules.append(r)
m.append_style('Sancaka5', s)
ds = mapnik.Shapefile(file="mapaustralia/map.shp")
layer = mapnik.Layer('provinsiaustralia')
layer.datasource = ds
layer.styles.append('Sancaka5')
m.layers.append(layer)
# BATAS MAP 5 Australia

m.zoom_all()
mapnik.render_to_file(m, 'world.jpeg', 'jpeg')
print "rendered image to 'world.jpeg'"
Ejemplo n.º 40
0
def render_agg(m, output, scale_factor):
    mapnik.render_to_file(m, output, 'png8:m=h', scale_factor),
Ejemplo n.º 41
0
            qs = urllib.parse.parse_qs(parsed.query)
            box, = qs['box']
            return box

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('partyexport', help='directory where extracted '\
                                            'terarain.party map lives')
    parser.add_argument('waterways', help='path to "waterways" .shp file')
    parser.add_argument('water', help='path to "water" .shp file')
    args = parser.parse_args()

    exportdir = os.listdir(args.partyexport)
    backgrounds = filter(lambda s: s.endswith('png'), exportdir)
    # make sure if the script is run twice we ignore files we've
    # generated
    backgrounds = filter(lambda s: not s.startswith(PREFIX), backgrounds)
    readme, = filter(lambda s: s.endswith('README.txt'), exportdir)

    with open(os.path.join(args.partyexport, readme), 'r') as fp:
        boxstr = coordinates_from_readme(fp)

    box = map(float, boxstr.split(','))
    m = getmap(args.waterways, args.water, box)


    for background in backgrounds:
        m.background_image = os.path.join(args.partyexport, background)
        newfile = ''.join([PREFIX, background])
        mapnik.render_to_file(m, os.path.join(args.partyexport, newfile), 'png')
Ejemplo n.º 42
0
import mapnik
m = mapnik.Map(1080, 720)
m.background = mapnik.Color('steelblue')
s = mapnik.Style()
r = mapnik.Rule()
polygon_symbolizer = mapnik.PolygonSymbolizer()
polygon_symbolizer.fill = mapnik.Color('#f2eff9')
r.symbols.append(polygon_symbolizer)

line_symbolizer = mapnik.LineSymbolizer()
line_symbolizer = mapnik.LineSymbolizer(mapnik.Color('green'), 1)
line_symbolizer.stroke_width = 20.0

r.symbols.append(line_symbolizer)
s.rules.append(r)
m.append_style('My Style', s)
ds = mapnik.Shapefile(file="D:\cp1\airterjun.shp")
layer = mapnik.Layer('world')
layer.datasource = ds
layer.styles.append('My Style')
m.layers.append(layer)
m.zoom_all()
mapnik.render_to_file(m, 'wp1.pdf', 'pdf')
print "rendered image to 'cp1.pdf'"
Ejemplo n.º 43
0
def render_cairo(m, output, scale_factor):
    mapnik.render_to_file(m, output, 'ARGB32', scale_factor)
    # open and re-save as png8 to save space
    new_im = mapnik.Image.open(output)
    new_im.save(output, 'png8:m=h')