Ejemplo n.º 1
1
def test_render_mvt_merc_nested_layers():
    m = mapnik.Map(512, 512)
    mapnik.load_map(m, '../data-visual/styles/nested-layers-1.xml')
    mvt = mapnik.VectorTileMerc(0, 0, 0)

    im2 = mapnik.Image(m.width, m.height)
    m.zoom_to_box(mvt.extent)
    mapnik.render(m, im2)
    actual2 = 'images/mvt/nested_layers.classic.actual.png'
    expected2 = 'images/mvt/nested_layers.classic.expected.png'
    im2.save(actual2, 'png32')
    eq_(compare_file_size(actual2, expected2, 100), True)

    mvt_buffer = mapnik.create_mvt_merc(m,
        mvt.x, mvt.y, mvt.z)

    # Check number of layers of the MVT
    vti = mapnik.VectorTileInfo()
    vti.parse_from_string(mvt_buffer)
    eq_(vti.layers_size(), 2);

    mapnik.merge_compressed_buffer(mvt, mvt_buffer)

    m = mapnik.Map(512, 512)
    # Load a version of the style with no datasources
    mapnik.load_map(m, 'styles/nested-layers-1.xml')
    im = mapnik.Image(m.width, m.height)
    mapnik.render_mvt_merc(mvt, m, im)

    actual = 'images/mvt/nested_layers.mvt.actual.png'
    im.save(actual, 'png32')
    expected = 'images/mvt/nested_layers.mvt.expected.png'
    eq_(compare_file_size(actual, expected, 100), True)
Ejemplo n.º 2
0
 def test_zoom_all_will_work_with_max_extent():
     m = mapnik.Map(512, 512)
     mapnik.load_map(m, '../data/good_maps/wgs842merc_reprojection.xml')
     merc_bounds = mapnik.Box2d(-20037508.34, -20037508.34, 20037508.34,
                                20037508.34)
     m.maximum_extent = merc_bounds
     m.zoom_all()
Ejemplo n.º 3
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.º 4
0
def test_style_level_comp_op():
    m = mapnik.Map(256, 256)
    mapnik.load_map(m, '../data/good_maps/style_level_comp_op.xml')
    m.zoom_all()
    successes = []
    fails = []
    for name in mapnik.CompositeOp.names:
        # find_style returns a copy of the style object
        style_markers = m.find_style("markers")
        style_markers.comp_op = getattr(mapnik.CompositeOp, name)
        # replace the original style with the modified one
        replace_style(m, "markers", style_markers)
        im = mapnik.Image(m.width, m.height)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-style-comp-op-' + name + '.png'
        expected = 'images/style-comp-op/' + name + '.png'
        im.save(actual)
        if not os.path.exists(expected):
            print 'generating expected test image: %s' % expected
            im.save(expected)
        expected_im = mapnik.Image.open(expected)
        # compare them
        if im.tostring() == expected_im.tostring():
            successes.append(name)
        else:
            fails.append('failed comparing actual (%s) and expected(%s)' % (actual,'tests/python_tests/'+ expected))
            fail_im = side_by_side_image(expected_im, im)
            fail_im.save('/tmp/mapnik-style-comp-op-' + name + '.fail.png')
    eq_(len(fails), 0, '\n'+'\n'.join(fails))
Ejemplo n.º 5
0
 def test_style_level_comp_op():
     m = mapnik.Map(256, 256)
     mapnik.load_map(m, "../data/good_maps/style_level_comp_op.xml")
     m.zoom_all()
     successes = []
     fails = []
     for name in mapnik.CompositeOp.names:
         # find_style returns a copy of the style object
         style_markers = m.find_style("markers")
         style_markers.comp_op = getattr(mapnik.CompositeOp, name)
         # replace the original style with the modified one
         replace_style(m, "markers", style_markers)
         im = mapnik.Image(m.width, m.height)
         mapnik.render(m, im)
         actual = "/tmp/mapnik-style-comp-op-" + name + ".png"
         expected = "images/style-comp-op/" + name + ".png"
         im.save(actual, "png32")
         if not os.path.exists(expected) or os.environ.get("UPDATE"):
             print "generating expected test image: %s" % expected
             im.save(expected, "png32")
         expected_im = mapnik.Image.open(expected)
         # compare them
         if im.tostring("png32") == expected_im.tostring("png32"):
             successes.append(name)
         else:
             fails.append(
                 "failed comparing actual (%s) and expected(%s)" % (actual, "tests/python_tests/" + expected)
             )
             fail_im = side_by_side_image(expected_im, im)
             fail_im.save("/tmp/mapnik-style-comp-op-" + name + ".fail.png", "png32")
     eq_(len(fails), 0, "\n" + "\n".join(fails))
Ejemplo n.º 6
0
    def renderTile(self, width, height, srs, coord):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            mapnik.load_map(self.mapnik, str(self.mapfile))

        nw = self.layer.projection.coordinateLocation(coord)
        se = self.layer.projection.coordinateLocation(coord.right().down())
        ul = self.mercator.locationProj(nw)
        lr = self.mercator.locationProj(se)


        self.mapnik.width = width
        self.mapnik.height = height
        self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y))

        # create grid as same size as map/image
        grid = mapnik.Grid(width, height)
        # render a layer to that grid array
        mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields)
        # then encode the grid array as utf, resample to 1/scale the size, and dump features
        grid_utf = grid.encode('utf', resolution=self.scale, features=True)

        if self.wrapper is None:
            return SaveableResponse(json.dumps(grid_utf))
        else:
            return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) + ')')
Ejemplo n.º 7
0
def test_can_parse_xml_with_deprecated_properties():
    default_logging_severity = mapnik.logger.get_severity()
    mapnik.logger.set_severity(getattr(mapnik.severity_type, "None"))
    files_with_deprecated_props = glob.glob("../data/deprecated_maps/*.xml")

    failures = []
    for filename in files_with_deprecated_props:
        try:
            m = mapnik.Map(512, 512)
            strict = True
            mapnik.load_map(m, filename, strict)
            base_path = os.path.dirname(filename)
            mapnik.load_map_from_string(
                m,
                open(
                    filename,
                    'rb').read(),
                strict,
                base_path)
        except RuntimeError as e:
            # only test datasources that we have installed
            if not 'Could not create datasource' in str(e) \
               and not 'could not connect' in str(e):
                failures.append(
                    'Failed to load valid map %s (%s)' %
                    (filename, e))
    eq_(len(failures), 0, '\n' + '\n'.join(failures))
    mapnik.logger.set_severity(default_logging_severity)
Ejemplo n.º 8
0
 def test_zoom_all_will_work_with_max_extent():
     m = mapnik.Map(512, 512)
     mapnik.load_map(m, '../data/good_maps/wgs842merc_reprojection.xml')
     merc_bounds = mapnik.Box2d(-20037508.34, -
                                20037508.34, 20037508.34, 20037508.34)
     m.maximum_extent = merc_bounds
     m.zoom_all()
Ejemplo n.º 9
0
    def __init__(self, name, style_sheets, commands,
                 buffer_size=0,
                 base_path=None,
                 default_scale=None):
        TermNode.__init__(self, name)
        assert isinstance(style_sheets, list)
        assert isinstance(commands, list)

        if len(commands) != len(style_sheets) - 1:
            raise InvalidCommandNumber(
                'len(commands) should be len(style_sheets) - 1')

        self._default_scale = default_scale
        self._commands = commands

        self._maps = list()
        for style_sheet in style_sheets:
            map = mapnik.Map(32, 32)

            filename = os.path.abspath(style_sheet)
            if base_path is None:
                base_path = os.path.dirname(filename)

            mapnik.load_map(map, filename, True, base_path)
            map.buffer_size = buffer_size
            self._maps.append(map)
Ejemplo n.º 10
0
def test_hit_grid():
    import os
    from itertools import groupby

    def rle_encode(l):
        """ encode a list of strings with run-length compression """
        return ["%d:%s" % (len(list(group)), name) for name, group in groupby(l)]

    m = mapnik.Map(256,256);
    mapnik.load_map(m,'../data/good_maps/agg_poly_gamma_map.xml');
    m.zoom_all()
    join_field = 'NAME'
    fg = [] # feature grid
    for y in range(0, 256, 4):
        for x in range(0, 256, 4):
            featureset = m.query_map_point(0,x,y)
            added = False
            for feature in featureset.features:
                fg.append(feature[join_field])
                added = True
            if not added:
                fg.append('')
    hit_list = '|'.join(rle_encode(fg))
    eq_(hit_list[:16],'730:|2:Greenland')
    eq_(hit_list[-12:],'1:Chile|812:')
Ejemplo n.º 11
0
 def _init_mapnik(self, projection):
     projection = '+init=%s' % projection.lower()
     mapper = mapnik.Map(32, 32, projection)
     mapnik.load_map(mapper, self._theme)
     self._proj = mapnik.Projection(projection)
     mapper.buffer_size = self._buffer_size
     return mapper
Ejemplo n.º 12
0
    def run(self):
        self.mapnik_map = mapnik.Map(self.width, self.height)
        mapnik.load_map(self.mapnik_map, self.config, True)

        self.map_projection = mapnik.Projection(self.mapnik_map.srs)
        self.tile_projection = projections.GoogleProjection()  

        while True:
            tile_parameters = None

            # Try to fetch a tile from any queue
            for tile_queue in self.tile_queues:
                try:
                    tile_parameters = tile_queue.get_nowait()
                    break 
                except Queue.Empty:
                    pass

            # Couldn't get tile parameters from any queue--all done
            if not tile_parameters:
                return

            # Skip rendering existing tiles
            if self.skip_existing:
                filename = tile_parameters[0]

                if os.path.exists(filename):
                    print 'Skipping %s' % (filename)
                    tile_queue.task_done()

                    continue

            self.render(*tile_parameters)
            tile_queue.task_done()
Ejemplo n.º 13
0
def test_non_member_known_attributes():
    m = mapnik.Map(256,256)
    mapnik.load_map(m,'../data/good_maps/extra_known_map_attributes.xml')
    attr = m.extra_attributes
    eq_(len(attr),2)
    eq_(attr['font-directory'],'.')
    eq_(attr['minimum-version'],'0.0.0')
Ejemplo n.º 14
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.º 15
0
 def watcher(self):
     failed = 0
     while 1:
         if not self.modified == os.path.getmtime(self._mapfile):
             self._locked = True
             time.sleep(self.watch_interval/2.0)
             self._log.info('Mapfile **changed**, reloading... ')
             try:
                 self._mapnik_map = mapnik.Map(self.size,self.size)
                 if self._mapfile.endswith('.xml'):
                     mapnik.load_map(self._mapnik_map, self._mapfile)
                 elif self._mapfile.endswith('.mml'):
                     from cascadenik import load_map as load_mml
                     load_mml(self._mapnik_map, self._mapfile)
                 self.msg('Mapfile successfully reloaded from %s' % self._mapfile)
                 if not is_merc(self._mapnik_map.srs):
                     self._mapnik_map.srs = MERC_PROJ4
                     self.msg('Map is not in spherical mercator, so setting that projection....')
                 failed = 0
             except Exception, E:
                 failed += 1
                 again = self.watch_interval*2
                 self.msg('Failed to reload mapfile, will try again in %s seconds:\n%s' % (again,E))
                 time.sleep(again)
             self.modified = os.path.getmtime(self._mapfile)
             self._locked = False
         else:
             time.sleep(self.watch_interval)
         if failed > self.max_failures:
             self.msg('Giving up on mapfile change watching thread...')
             break
Ejemplo n.º 16
0
    def renderTile(self, width, height, srs, coord):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            mapnik.load_map(self.mapnik, str(self.mapfile))

        # buffer as fraction of tile size
        buffer = float(self.buffer) / 256

        nw = self.layer.projection.coordinateLocation(coord.left(buffer).up(buffer))
        se = self.layer.projection.coordinateLocation(coord.right(1 + buffer).down(1 + buffer))
        ul = self.mercator.locationProj(nw)
        lr = self.mercator.locationProj(se)

        self.mapnik.width = width + 2 * self.buffer
        self.mapnik.height = height + 2 * self.buffer
        self.mapnik.zoom_to_box(mapnik.Box2d(ul.x, ul.y, lr.x, lr.y))

        # create grid as same size as map/image
        grid = mapnik.Grid(width + 2 * self.buffer, height + 2 * self.buffer)
        # render a layer to that grid array
        mapnik.render_layer(self.mapnik, grid, layer=self.layer_index, fields=self.fields)
        # extract a gridview excluding the buffer
        grid_view = grid.view(self.buffer, self.buffer, width, height)
        # then encode the grid array as utf, resample to 1/scale the size, and dump features
        grid_utf = grid_view.encode('utf', resolution=self.scale, add_features=True)

        if self.wrapper is None:
            return SaveableResponse(json.dumps(grid_utf))
        else:
            return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) + ')')
Ejemplo n.º 17
0
    def test_render_with_palette():
        m = mapnik.Map(600, 400)
        mapnik.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml')
        m.zoom_all()
        im = mapnik.Image(m.width, m.height)
        mapnik.render(m, im)
        with open('../data/palettes/palette256.act', 'rb') as act:
            palette = mapnik.Palette(act.read(), 'act')
        # test saving directly to filesystem
        im.save('/tmp/mapnik-palette-test.png', 'png', palette)
        expected = './images/support/mapnik-palette-test.png'
        if os.environ.get('UPDATE'):
            im.save(expected, "png", palette)

        # test saving to a string
        with open('/tmp/mapnik-palette-test2.png', 'wb') as f:
            f.write(im.tostring('png', palette))
        # compare the two methods
        eq_(mapnik.Image.open('/tmp/mapnik-palette-test.png').tostring('png32'),
            mapnik.Image.open(
                '/tmp/mapnik-palette-test2.png').tostring('png32'),
            '%s not eq to %s' % ('/tmp/mapnik-palette-test.png',
                                 '/tmp/mapnik-palette-test2.png'))
        # compare to expected
        eq_(mapnik.Image.open('/tmp/mapnik-palette-test.png').tostring('png32'),
            mapnik.Image.open(expected).tostring('png32'),
            '%s not eq to %s' % ('/tmp/mapnik-palette-test.png',
                                 expected))
def test_datasource_template_is_working():
    m = mapnik.Map(256,256)
    try:
        mapnik.load_map(m,'../data/good_maps/datasource.xml')
    except RuntimeError as e:
        if "Required parameter 'type'" in str(e):
            raise RuntimeError(e)
Ejemplo n.º 19
0
def test_render_mvt_with_optional_arguments():
    # A dubious test ported from node-mapnik.
    # TODO: make these optional arguments to have actual effect.
    mvt = mapnik.VectorTileMerc(28, 12, 5)

    with open('data/tile3.mvt', 'rb') as f:
        buf = f.read();
        eq_(isinstance(buf, bytes), True)
        mapnik.merge_compressed_buffer(mvt, buf)

    eq_(len(mvt.get_buffer()), 987)
    eq_(mvt.is_painted, True)
    eq_(mvt.is_empty, False)

    m = mapnik.Map(256, 256)
    m.maximum_extent = mapnik.Box2d(-20037508.34, -20037508.34, 20037508.34, 20037508.34)
    mapnik.load_map(m, 'styles/mvt_render_test.xml')

    im = mapnik.Image(m.width, m.height)
    mapnik.render_mvt_merc(mvt, m, im,
        scale_factor=1.2, scale_denom=1.5,
        variables={ 'pizza': 'pie' })

    expected = 'images/mvt/tile3.expected.png'
    actual = 'images/mvt/tile3-2.actual.png'
    im.save(actual, 'png32')
    eq_(compare_file_size(actual, expected, 100), True)
Ejemplo n.º 20
0
 def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
     """
     """
     if self.mapnik is None:
         self.mapnik = mapnik.Map(0, 0)
         
         if exists(self.mapfile):
             mapnik.load_map(self.mapnik, str(self.mapfile))
         
         else:
             handle, filename = mkstemp()
             os.write(handle, urlopen(self.mapfile).read())
             os.close(handle)
 
             mapnik.load_map(self.mapnik, filename)
             os.unlink(filename)
     
     self.mapnik.width = width
     self.mapnik.height = height
     self.mapnik.zoom_to_box(mapnik.Envelope(xmin, ymin, xmax, ymax))
     
     img = mapnik.Image(width, height)
     mapnik.render(self.mapnik, img)
     
     img = Image.fromstring('RGBA', (width, height), img.tostring())
     
     return img
Ejemplo n.º 21
0
def renderPage(ll,file):

        z = 2
        #imgx = 987 * z
        #imgy = 801 * z
        imgx = int(987 * z )
        imgy = int(987 * z *0.77 )
        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")
        c0 = prj.forward(mapnik.Coord(ll[0],ll[1]))
        c1 = prj.forward(mapnik.Coord(ll[2],ll[3]))
        if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 800:
            bbox = mapnik.Box2d(c0.x,c0.y,c1.x,c1.y)
        else:
            bbox = mapnik.Envelope(c0.x,c0.y,c1.x,c1.y)
            m.zoom_to_box(bbox)
            im = mapnik.Image(imgx,imgy)
            mapnik.render(m, im)
            view = im.view(0,0,imgx,imgy) # x,y,width,height
            map_uri=file + '.png'
            view.save(map_uri,'png')
        
        
            file=open(file+'.svg' ,'w')
            surface=cairo.SVGSurface(file.name,imgx,imgy)
            mapnik.render(m,surface)
            #c = cairo.Context(surface)
            #c.move_to(50,50)
            #c.show_text('testing')

            surface.finish();
Ejemplo n.º 22
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.º 23
0
def test_render_mvt_raster_with_large_overzoom():
    mvt = mapnik.VectorTileMerc(2788, 6533, 14);

    with open('images/mvt/14_2788_6533.webp', 'rb') as f:
        mapnik.add_image_layer(mvt, '_image', f.read())

    # Look into the tile if there is the image
    vti = mapnik.VectorTileInfo()
    vti.parse_from_string(mvt.get_buffer())
    eq_(vti.layers_size(), 1);
    layer = vti.layers(0)
    eq_(layer.features_size(), 1)
    feature = layer.features(0)
    raster = feature.raster()
    eq_(len(raster), 98618)
    img = mapnik.Image.frombuffer(raster)
    eq_(img.width(), 512)
    eq_(img.height(), 512)

    m = mapnik.Map(256, 256)
    mapnik.load_map(m, 'styles/large_overzoom.xml')

    im = mapnik.Image(m.width, m.height)
    mapnik.render_mvt_merc(mvt, m, im,
        x=2855279, y=6690105, z=24,
        scale_factor=1, buffer_size=256)

    expected = 'images/mvt/large_overzoom.expected.png'
    actual = 'images/mvt/large_overzoom.actual.png'
    im.save(actual, 'png32')
    eq_(compare_file_size(actual, expected, 100), True)
Ejemplo n.º 24
0
def test_arbitrary_parameters_attached_to_map():
    m = mapnik.Map(256,256)
    mapnik.load_map(m,'../data/good_maps/extra_arbitary_map_parameters.xml')
    eq_(len(m.parameters),5)
    eq_(m.parameters['key'],'value2')
    eq_(m.parameters['key3'],'value3')
    eq_(m.parameters['unicode'],u'iván')
    eq_(m.parameters['integer'],10)
    eq_(m.parameters['decimal'],.999)
    m2 = mapnik.Map(256,256)
    for k,v in m.parameters:
        m2.parameters.append(mapnik.Parameter(k,v))
    eq_(len(m2.parameters),5)
    eq_(m2.parameters['key'],'value2')
    eq_(m2.parameters['key3'],'value3')
    eq_(m2.parameters['unicode'],u'iván')
    eq_(m2.parameters['integer'],10)
    eq_(m2.parameters['decimal'],.999)
    map_string = mapnik.save_map_to_string(m)
    m3 = mapnik.Map(256,256)
    mapnik.load_map_from_string(m3,map_string)
    eq_(len(m3.parameters),5)
    eq_(m3.parameters['key'],'value2')
    eq_(m3.parameters['key3'],'value3')
    eq_(m3.parameters['unicode'],u'iván')
    eq_(m3.parameters['integer'],10)
    eq_(m3.parameters['decimal'],.999)
def main(args=None):
  args = parser().parse_args(args)

  m = mapnik.Map(args.size[0],args.size[0])
  mapnik.load_map(m,args.map)

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

  if hasattr(mapnik,'Box2d'):
    bbox = mapnik.Box2d(*args.bbox)
  else:
    bbox = mapnik.Envelope(*args.bbox)

  # Our bounds above are in long/lat, but our map
  # is in spherical mercator, so we need to transform
  # the bounding box to mercator to properly position
  # the Map when we call `zoom_to_box()`
  transform = mapnik.ProjTransform(longlat,merc)
  merc_bbox = transform.forward(bbox)

  # Mapnik internally will fix the aspect ratio of the bounding box
  # to match the aspect ratio of the target image width and height
  # This behavior is controlled by setting the `m.aspect_fix_mode`
  # and defaults to GROW_BBOX, but you can also change it to alter
  # the target image size by setting aspect_fix_mode to GROW_CANVAS
  #m.aspect_fix_mode = mapnik.GROW_CANVAS
  # Note: aspect_fix_mode is only available in Mapnik >= 0.6.0
  m.zoom_to_box(merc_bbox)

  # render the map to an image
  im = mapnik.Image(args.size[0], args.size[1])
  mapnik.render(m, im)
  im.save(args.output,'png')
Ejemplo n.º 26
0
def test_arbitrary_parameters_attached_to_map():
    m = mapnik.Map(256, 256)
    mapnik.load_map(m, "../data/good_maps/extra_arbitary_map_parameters.xml")
    eq_(len(m.parameters), 5)
    eq_(m.parameters["key"], "value2")
    eq_(m.parameters["key3"], "value3")
    eq_(m.parameters["unicode"], u"iván")
    eq_(m.parameters["integer"], 10)
    eq_(m.parameters["decimal"], 0.999)
    m2 = mapnik.Map(256, 256)
    for k, v in m.parameters:
        m2.parameters.append(mapnik.Parameter(k, v))
    eq_(len(m2.parameters), 5)
    eq_(m2.parameters["key"], "value2")
    eq_(m2.parameters["key3"], "value3")
    eq_(m2.parameters["unicode"], u"iván")
    eq_(m2.parameters["integer"], 10)
    eq_(m2.parameters["decimal"], 0.999)
    map_string = mapnik.save_map_to_string(m)
    m3 = mapnik.Map(256, 256)
    mapnik.load_map_from_string(m3, map_string)
    eq_(len(m3.parameters), 5)
    eq_(m3.parameters["key"], "value2")
    eq_(m3.parameters["key3"], "value3")
    eq_(m3.parameters["unicode"], u"iván")
    eq_(m3.parameters["integer"], 10)
    eq_(m3.parameters["decimal"], 0.999)
Ejemplo n.º 27
0
def render(data_dir, filename, config, scale_factor, reporting):
    m = mapnik.Map(*config['sizes'][0])

    try:
        mapnik.load_map(m, os.path.join(data_dir, "styles", filename), True)

        if not (m.parameters['status'] if (
                'status' in m.parameters) else config['status']):
            return
    except Exception as e:
        if 'Could not create datasource' in str(e) \
           or 'Bad connection' in str(e) \
           or 'Postgis Plugin: could not connect to server' in str(e):
            return m
        reporting.other_error(filename, repr(e))
        return m

    sizes = config['sizes']
    if 'sizes' in m.parameters:
        sizes = [[int(i) for i in size.split(',')]
                 for size in m.parameters['sizes'].split(';')]

    ignored_renderers = config['ignored_renderers']
    if 'ignored_renderers' in m.parameters:
        ignored_renderers = m.parameters['ignored_renderers'].split(',')

    for size in sizes:
        m.width, m.height = size

        if 'bbox' in m.parameters:
            bbox = mapnik.Box2d.from_string(str(m.parameters['bbox']))
            m.zoom_to_box(bbox)
        else:
            m.zoom_all()

        name = filename[0:-4]
        postfix = "%s-%d-%d-%s" % (name, m.width, m.height, scale_factor)
        for renderer in renderers:
            if renderer['name'] in ignored_renderers:
                continue
            if config.get(renderer['name'], True):
                expected = os.path.join(data_dir, renderer['dir'], '%s-%s-reference.%s' %
                                        (postfix, renderer['name'], renderer['filetype']))
                actual = os.path.join(visual_output_dir, '%s-%s.%s' %
                                      (postfix, renderer['name'], renderer['filetype']))
                if not reporting.quiet:
                    print("\"%s\" with %s..." % (postfix, renderer['name']))
                try:
                    renderer['render'](m, actual, scale_factor)
                    if not os.path.exists(expected):
                        reporting.not_found(actual, expected)
                    else:
                        diff = renderer['compare'](actual, expected)
                        if diff > renderer['threshold']:
                            reporting.result_fail(actual, expected, diff)
                        else:
                            reporting.result_pass(actual, expected, diff)
                except Exception as e:
                    reporting.other_error(expected, repr(e))
    return m
Ejemplo n.º 28
0
def test_hit_grid():

    def rle_encode(l):
        """ encode a list of strings with run-length compression """
        return ["%d:%s" % (len(list(group)), name) for name, group in groupby(l)]

    m = mapnik.Map(256,256);
    try:
        mapnik.load_map(m,'../data/good_maps/agg_poly_gamma_map.xml');
        m.zoom_all()
        join_field = 'NAME'
        fg = [] # feature grid
        for y in range(0, 256, 4):
            for x in range(0, 256, 4):
                featureset = m.query_map_point(0,x,y)
                added = False
                for feature in featureset.features:
                    fg.append(feature[join_field])
                    added = True
                if not added:
                    fg.append('')
        hit_list = '|'.join(rle_encode(fg))
        eq_(hit_list[:16],'730:|2:Greenland')
        eq_(hit_list[-12:],'1:Chile|812:')
    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.º 29
0
 def test_map_query_throw6():
     m = mapnik.Map(256, 256)
     mapnik.load_map(m, "../data/good_maps/merc2wgs84_reprojection.xml")
     wgs84_bounds = mapnik.Box2d(-180, -90, 180, 90)
     m.maximum_extent = wgs84_bounds
     m.zoom_all()
     m.query_point(0, -180, -90)
Ejemplo n.º 30
0
def render_tile(mapfile, tile_uri, x, y, z):
	m = mapnik.Map(256, 256)

	# Load style XML
	mapnik.load_map(m, mapfile, True)

	# Obtain <Map> projection
	prj = mapnik.Projection(m.srs)

	# Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
	tileproj = GoogleProjection(z+1)

	# Calculate pixel positions of bottom-left & top-right
	p0 = (x * 256, (y + 1) * 256)
	p1 = ((x + 1) * 256, y * 256)

	# Convert to LatLong (EPSG:4326)
	l0 = tileproj.fromPixelToLL(p0, z);
	l1 = tileproj.fromPixelToLL(p1, z);

	# Convert to map projection (e.g. mercator co-ords EPSG:900913)
	c0 = prj.forward(mapnik.Coord(l0[0],l0[1]))
	c1 = prj.forward(mapnik.Coord(l1[0],l1[1]))

	# Bounding box for the tile
	bbox = mapnik.Envelope(c0.x,c0.y, c1.x,c1.y)
	render_size = 256
	m.resize(render_size, render_size)
	m.zoom_to_box(bbox)
	m.buffer_size = 128

	# Render image with default Agg renderer
	im = mapnik.Image(render_size, render_size)
	mapnik.render(m, im)
	im.save(tile_uri, 'png256')
    def loop(self):
        
        self.m = mapnik.Map(256, 256)
        # Load style XML
        mapnik.load_map(self.m, self.mapfile, True)
        # Obtain <Map> projection
        self.prj = mapnik.Projection(self.m.srs)
        # Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
        self.tileproj = GoogleProjection(self.maxZoom+1)
                
        while True:
            #Fetch a tile from the queue and render it
            r = self.q.get()
            if (r == None):
                self.q.task_done()
                break
            else:
                (name, tile_uri, x, y, z) = r

            exists= ""
            if os.path.isfile(tile_uri):
                exists= "exists"
            else:
                self.render_tile(tile_uri, x, y, z)
            bytes=os.stat(tile_uri)[6]
            empty= ''
            if bytes == 103:
                empty = " Empty Tile "
            self.printLock.acquire()
            print(name, ":", z, x, y, exists, empty)
            self.printLock.release()
            self.q.task_done()
Ejemplo n.º 32
0
    def __init__(self, style, empty=None, maxzoom=18):
        models.Manager.__init__(self)
        self.emptytile = empty

        self.map = mapnik.Map(256, 256)
        mapnik.load_map(self.map, style)
        self.mproj = mapnik.Projection(self.map.srs)
        self.gproj = GoogleProjection(maxzoom)
Ejemplo n.º 33
0
    def load_map(self):
        self.mapnik_map = mapnik.Map(self.width, self.height)
        mapnik.load_map(self.mapnik_map, self.mapfile)

        if self.srs:
            proj_init = str('+init=%s' % self.srs).lower()
            self.projection = mapnik.Projection(proj_init)
            self.mapnik_map.srs = self.projection.params()
Ejemplo n.º 34
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.º 35
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.º 36
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.º 37
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.º 38
0
 def test_map_query_works1():
     m = mapnik.Map(256,256)
     mapnik.load_map(m,'../data/good_maps/wgs842merc_reprojection.xml')
     merc_bounds = mapnik.Box2d(-20037508.34,-20037508.34,20037508.34,20037508.34)
     m.maximum_extent = merc_bounds
     m.zoom_all()
     fs = m.query_point(0,-11012435.5376, 4599674.6134) # somewhere in kansas
     feat = fs.next()
     eq_(feat.attributes['NAME_FORMA'],u'United States of America')
Ejemplo n.º 39
0
 def __init__(self, tile_dir, mapfile, maxZoom):
     self.tile_dir = tile_dir
     self.m = mapnik.Map(256, 256)
     # Load style XML
     mapnik.load_map(self.m, mapfile, True)
     # Obtain <Map> projection
     self.prj = mapnik.Projection(self.m.srs)
     # Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
     self.tileproj = GoogleProjection(maxZoom + 1)
Ejemplo n.º 40
0
    def renderTile(self, tile):
        import mapnik, StringIO
        import PIL.Image

        if self.mapnik:
            m = self.mapnik
        else:
            if self.fonts:
                engine = mapnik.FontEngine.instance()
                for font in self.fonts:
                    engine.register_font(font)

            # Init it as 0,0
            m = mapnik.Map(0, 0)
            mapnik.load_map(m, self.mapfile)

            if self.projection:
                m.srs = self.projection

            # Restrict layer list, if requested
            if self.layers and self.layers != self.name:
                layers = self.layers.split(",")
                for layer_num in range(len(m.layers) - 1, -1, -1):
                    l = m.layers[layer_num]
                    if l.name not in layers:
                        del m.layers[layer_num]
                    if self.debug:
                        print >> sys.stderr, "Removed layer %s loaded from %s, not in list: %s" % (
                            l.name, self.mapfile, layers)

            # this will insure that it gets cached in mod_python
            self.mapnik = m

        # Set the mapnik size to match the size of the current tile
        m.width = tile.size()[0]
        m.height = tile.size()[1]

        bbox = tile.bounds()
        bbox = mapnik.Envelope(bbox[0], bbox[1], bbox[2], bbox[3])
        m.zoom_to_box(bbox)

        im = mapnik.Image(*tile.size())
        mapnik.render(m, im)
        if hasattr(im, 'tostring'):
            data = im.tostring()
        elif hasattr(mapnik, 'rawdata'):
            data = mapnik.rawdata(im)
        else:
            raise Exception(
                "Something is wrong: your version of Mapnik can't create a string from an image."
            )
        im = PIL.Image.fromstring('RGBA', tile.size(), data)
        buffer = StringIO.StringIO()
        im.save(buffer, self.extension)
        buffer.seek(0)
        tile.data = buffer.read()
        return tile.data
Ejemplo n.º 41
0
 def run(self):
     map = mapnik.Map(self.sizex, self.sizey)
     mapnik.load_map(map, self.mapname + ".xml")
     result = renderLayerLL(self.mapname, self.envLL, self.sizex,
                            self.sizey, map)
     console.debugMessage(' Rendered layer: ' + self.mapname)
     self.imagesLock.acquire()
     self.images[self.mapname] = result
     self.imagesLock.release()
Ejemplo n.º 42
0
 def test_map_query_in_pixels_works1():
     m = mapnik.Map(256,256)
     mapnik.load_map(m,'../data/good_maps/wgs842merc_reprojection.xml')
     merc_bounds = mapnik.Box2d(-20037508.34,-20037508.34,20037508.34,20037508.34)
     m.maximum_extent = merc_bounds
     m.zoom_all()
     fs = m.query_map_point(0,55,100) # somewhere in middle of us
     feat = fs.next()
     eq_(feat.attributes['NAME_FORMA'],u'United States of America')
Ejemplo n.º 43
0
def tms(z, x, y, service):
    # (4370311.220000, 4911352.860000) - (4403732.650000, 4958349.910000)
    # Extent: (4370177.610000, 4908530.650000) - (4411390.670000, 4958581.500000)
    bbox = dict(minx=4370177, miny=4908530, maxx=4411390, maxy=4958581)

    step = max(bbox['maxx'] - bbox['minx'], bbox['maxy'] - bbox['miny']) / 2**z

    extents = dict()

    extents['tms'] = (bbox['minx'] + x * step, bbox['miny'] + y * step,
                      bbox['minx'] + (x + 1) * step,
                      bbox['miny'] + (y + 1) * step)

    extents['xyz'] = (bbox['minx'] + x * step, bbox['maxy'] - (y + 1) * step,
                      bbox['minx'] + (x + 1) * step, bbox['maxy'] - y * step)

    tile = dict(width=256, height=256)
    map = mapnik.Map(tile['width'], tile['height'])
    map.background = mapnik.Color('steelblue')
    mapnik.load_map(map, 'tile_server/style/styles.xml')
    layer = mapnik.Layer('point')
    ds = mapnik.PostGIS(host='127.0.0.1',
                        dbname='isogd_sevastopol',
                        user='******',
                        password='******',
                        table='tableapi.table_test_2_points_2')
    layer.datasource = ds
    pdb.set_trace()
    style = mapnik.Style()
    rule = mapnik.Rule()
    point_symbolizer = mapnik.PointSymbolizer()
    point_symbolizer.file = "/style/point_style.png"
    # pdb.set_trace()

    rule.symbols.append(point_symbolizer)
    style.rules.append(rule)
    map.append_style('My Style', style)

    map.zoom_all()
    mapnik.render_to_file(map, 'altay.png', 'png')

    box = mapnik.Box2d(*extents.get(service))
    # map.zoom_all()
    map.zoom_to_box(box)
    mapnik.render_to_file(map, 'world.png', 'png')
    im = mapnik.Image(map.width, map.height)
    mapnik.render(map, im)
    output = im.tostring('png')

    # box = mapnik.Box2d(*extents.get(service))
    # map.zoom_to_box(box)
    # mapnik.render_to_file(map, 'world.png', 'png')
    # im = mapnik.Image(map.width, map.height)
    # mapnik.render(map, im)
    # output = im.tostring('png')
    # # Передаём ответ клиенту
    return output
def application(env, start_response):
  global stylename
  global map_template
  
  status = '200 OK'
  
  pathinfo=env['PATH_INFO']

  # read configuration file  
  config = ConfigParser.ConfigParser()
  cfgfile="tileserver.conf"
  config.read(cfgfile)
  stylename = config_get(config,"global","stylename","osm.xml")
  styledir = config_get(config,"global","styledir","../mapnik-stylesheets")
  map_template = config_get(config,"global","map_template","map_template_leaflet.html")
  
  # show static content when URL starts with '/static/'
  m = re.match(r"^/static/(.+)$", pathinfo)
  if m:
    return showStaticContent(start_response, m.group(1))

  # mod-wsgi gives control to our script only for /name and /name/...
  # thus any length <2 should show the overview page
  if len(pathinfo) < 2:
    return genSlippyMap(start_response)
  
  m = re.match(r"^/tiles/([0-9]+)/+([0-9]+)/+([0-9]+).png$", pathinfo)
  if m is None:
    msg="Invalid URL: %s<br />should be /tiles/&lt;z&gt;/&lt;x&gt;/&lt;y&gt;.png" % pathinfo
    return InvalidURL(start_response,msg,'404 Invalid URL')
    
  z=int(m.group(1))
  x=int(m.group(2))
  y=int(m.group(3))
  
  # check for mapnik style file in requested sandbox
  import os.path
  mapfile=os.path.join(styledir,stylename)
  if not os.path.exists(mapfile):
    msg="ERROR: stylename &gt;%s&lt; does not exist!!!" % stylename
    return InvalidURL(start_response,msg,'404 Invalid sandbox')
  
  # we have a valid Tile-URL request so just render the tile now
  m = mapnik.Map(256, 256)
  mapnik.load_map(m, mapfile)
  bba=TileToBBox(x,y,z)
  bbox=mapnik.Box2d(bba[0],bba[1],bba[2],bba[3])
  m.zoom_to_box(bbox)
  im = mapnik.Image(256, 256)
  mapnik.render(m, im)
  
  output = im.tostring('png')
  
  response_headers = [('Content-type', 'image/png'),
                      ('Content-Length', str(len(output)))]
  start_response(status, response_headers)
  return [output]
Ejemplo n.º 45
0
def render_map(_map, mimetype='application/pdf'):
    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')
    transform = mapnik.ProjTransform(longlat, merc)

    bbox = mapnik.Box2d(*_map.bbox)
    merc_bbox = transform.forward(bbox)

    mapnik_map = mapnik.Map(int(merc_bbox.width()), int(merc_bbox.height()))
    mapnik_map.zoom_to_box(merc_bbox)
    mapnik_map.buffer_size = 5

    # add osm data
    mapnik.load_map(mapnik_map, current_app.config['MAPNIK_OSM_XML'])

    # add grid
    data = _map.grid
    path = os.path.join(SRC_PATH, "maps-xml/grid.xml")
    xml_str = get_xml(path).format(json.dumps(data)).encode()
    mapnik.load_map_from_string(mapnik_map, xml_str)

    # add all features
    features = FeatureCollection([f.to_dict() for f in _map.features])
    path = os.path.join(SRC_PATH, "maps-xml/features.xml")
    xml_str = get_xml(path).format(json.dumps(features)).encode()
    mapnik.load_map_from_string(mapnik_map, xml_str)

    # add legend
    add_legend(mapnik_map, _map.legend)

    # export as in-memory file
    f = io.BytesIO()

    if mimetype == 'image/svg+xml':
        surface = cairo.SVGSurface(f, mapnik_map.width, mapnik_map.height)
    elif mimetype == 'image/png':
        ratio = float(mapnik_map.height) / mapnik_map.width
        mapnik.height = 800
        mapnik.width = int(600 * ratio)
        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, mapnik_map.width,
                                     mapnik_map.height)
    else:
        surface = cairo.PDFSurface(f, mapnik_map.width, mapnik_map.height)

    mapnik.render(mapnik_map, surface)

    if mimetype == 'image/png':
        surface.write_to_png(f)

    surface.finish()
    f.seek(0)

    return f
Ejemplo n.º 46
0
    def __init__(self,
                 stylesheet,
                 bounding_box,
                 _width,
                 _height,
                 dpi=72.0,
                 extend_bbox_to_ratio=True):
        """Initialize the map canvas for rendering.

        Args:
            stylesheet (Stylesheet): map stylesheet.
            bounding_box (coords.BoundingBox): geographic bounding box.
            graphical_ratio (float): ratio of the map area (width/height).
            dpi (float): map resolution (default: 72dpi)
            extend_bbox_to_ratio (boolean): allow MapCanvas to extend
            the bounding box to make it match the ratio of the
            provided rendering area. Needed by SinglePageRenderer.
        """

        self._proj = mapnik.Projection(_MAPNIK_PROJECTION)
        self._dpi = dpi

        # This is where the magic of the map canvas happens. Given an original
        # bounding box and a graphical ratio for the output, the bounding box
        # is adjusted (extended) to fill the destination zone. See
        # _fix_bbox_ratio for more details on how this is done.
        orig_envelope = self._project_envelope(bounding_box)
        graphical_ratio = _width / _height

        if extend_bbox_to_ratio:
            off_x, off_y, width, height = self._fix_bbox_ratio(
                orig_envelope.minx, orig_envelope.miny, orig_envelope.width(),
                orig_envelope.height(), graphical_ratio)

            envelope = mapnik.Box2d(off_x, off_y, off_x + width,
                                    off_y + height)
            self._geo_bbox = self._inverse_envelope(envelope)
            LOG.debug('Corrected bounding box from %s to %s, ratio: %.2f.' %
                      (bounding_box, self._geo_bbox, graphical_ratio))
        else:
            envelope = orig_envelope
            self._geo_bbox = bounding_box

        g_width = int(convert_pt_to_dots(_width, dpi))
        g_height = int(convert_pt_to_dots(_height, dpi))

        # Create the Mapnik map with the corrected width and height and zoom to
        # the corrected bounding box ('envelope' in the Mapnik jargon)
        self._map = mapnik.Map(g_width, g_height, _MAPNIK_PROJECTION)
        mapnik.load_map(self._map, stylesheet.path)
        self._map.zoom_to_box(envelope)

        # Added shapes to render
        self._shapes = []

        LOG.debug('MapCanvas rendering map on %dx%dpx.' % (g_width, g_height))
Ejemplo n.º 47
0
    def render(self, input_file, extent, lyr_style):
        proj4lyr = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
        county_file = '../datas/county.shp'
        # river_file = '../datas/river.shp'
        # capital_file ='Capital3.json'
        filename = os.path.split(input_file)[1]
        areaCode = os.path.splitext(filename)[0]
        output_file = input_file.split('.')[0] + '.png'
        print areaCode

        # ----------create map---------------------
        m = mapnik.Map(extent.xsize, extent.ysize)
        mapnik.load_map(m, 'cg_config.xml')
        # ----------create layer 1-----------------
        layer = mapnik.Layer('dataraster', proj4lyr)
        # ----------create layer 1 datasource------
        layer.datasource = mapnik.Gdal(file=input_file, band=1, nodata=-999)
        layer.styles.append(lyr_style)
        # ----------append layer 1 to map----------
        m.layers.append(layer)

        # ----------create layer 2-----------------
        layer2 = mapnik.Layer('county', proj4lyr)
        # Create new styles and add the rules.
        s_county = m.find_style('county')
        r_county = s_county.rules[0]
        r_county.filter = mapnik.Filter('[CITY]=' + areaCode)
        m.append_style(areaCode, s_county)
        # ----------create layer 2 datasource------
        layer2.datasource = mapnik.Shapefile(file=county_file)
        layer2.styles.append(areaCode)
        # ----------append layer 2 to map----------
        m.layers.append(layer2)

        # ----------create layer 3-----------------
        layer3 = mapnik.Layer('capital', proj4lyr)
        # Create new styles and add the rules.
        s_capital = m.find_style('capital')
        r_capital = s_capital.rules[0]
        r_capital.filter = mapnik.Filter('[CITY]=' + areaCode)
        m.append_style('symbol', s_capital)
        # ----------create layer 3 datasource------
        layer3.datasource = mapnik.Shapefile(file=county_file)
        layer3.styles.append('symbol')
        # ----------append layer 3 to map----------
        m.layers.append(layer3)

        ll = mapnik.Coord(extent.xmax, extent.ymax)
        tr = mapnik.Coord(extent.xmin, extent.ymin)
        map_bbox = mapnik.Box2d(tr, ll)  # mapnik.Envelope(tr, ll)

        m.zoom_to_box(map_bbox)
        print m.envelope(), m.scale()
        mapnik.render_to_file(m, output_file, 'png')

        return 'true'
Ejemplo n.º 48
0
def compare_map(xml):
    m = mapnik.Map(256, 256)
    absolute_base = os.path.abspath(os.path.dirname(xml))
    try:
        mapnik.load_map(m, xml, False, absolute_base)
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
        return
Ejemplo n.º 49
0
def test_buffer_size_from_style_overriden_by_parameter():
    m = mapnik.Map(256, 256)
    mapnik.load_map(m, 'styles/map_buffer_size.xml')
    mvt_buffer = mapnik.create_mvt_merc(m, 2048, 2047, 12, buffer_size=0)

    tile = mapnik.VectorTileInfo()
    tile.parse_from_string(mvt_buffer)

    eq_(tile.layers_size(), 1)
    eq_(tile.layers(0).features_size(), 1)
Ejemplo n.º 50
0
 def __init__(self, request):
     self.map = mapnik.Map(1, 1)
     mapfile = request.GET['LAYERS'].split(',')[0] + '.xml'
     mapfile_path = os.path.join(settings.MAPFILES, mapfile)
     mapnik.load_map(self.map, str(mapfile_path))
     try:
         p = mapnik.Projection('+init=%s' % str(request.GET['SRS']))
     except:
         p = mapnik.Projection(MERC_PROJ4)
     self.map.srs = p.params()
Ejemplo n.º 51
0
def test_arbitrary_parameters_attached_to_map():
    m = mapnik.Map(256, 256)
    mapnik.load_map(m, '../data/good_maps/extra_arbitary_map_parameters.xml')
    eq_(len(m.parameters), 6)
    eq_(m.parameters['key'], 'value2')
    eq_(m.parameters['key3'], 'value3')
    eq_(m.parameters['unicode'], u'iván')
    eq_(m.parameters['integer'], 10)
    eq_(m.parameters['decimal'], .999)
    eq_(m.parameters['number-as-string'], u'.9998')
Ejemplo n.º 52
0
def render(filename, config, scale_factor, reporting):
    m = mapnik.Map(*config['sizes'][0])

    try:
        mapnik.load_map(m, os.path.join(dirname, "styles", filename), True)

        if not (m.parameters['status'] if
                ('status' in m.parameters) else config['status']):
            return
    except Exception as e:
        if 'Could not create datasource' in str(e) \
           or 'Bad connection' in str(e):
            return m
        reporting.other_error(filename, repr(e))
        return m

    sizes = config['sizes']
    if 'sizes' in m.parameters:
        sizes = [[int(i) for i in size.split(',')]
                 for size in m.parameters['sizes'].split(';')]

    for size in sizes:
        m.width, m.height = size

        if 'bbox' in m.parameters:
            bbox = mapnik.Box2d.from_string(str(m.parameters['bbox']))
            m.zoom_to_box(bbox)
        else:
            m.zoom_all()

        name = filename[0:-4]
        postfix = "%s-%d-%d-%s" % (name, m.width, m.height, scale_factor)
        for renderer in renderers:
            if config.get(renderer['name'], True):
                expected = os.path.join(
                    dirname, renderer['dir'], '%s-%s-reference.%s' %
                    (postfix, renderer['name'], renderer['filetype']))
                actual = os.path.join(
                    visual_output_dir, '%s-%s.%s' %
                    (postfix, renderer['name'], renderer['filetype']))
                if not quiet:
                    print("\"%s\" with %s..." % (postfix, renderer['name']))
                try:
                    renderer['render'](m, actual, scale_factor)
                    if not os.path.exists(expected):
                        reporting.not_found(actual, expected)
                    else:
                        diff = renderer['compare'](actual, expected)
                        if diff > renderer['threshold']:
                            reporting.result_fail(actual, expected, diff)
                        else:
                            reporting.result_pass(actual, expected, diff)
                except Exception as e:
                    reporting.other_error(expected, repr(e))
    return m
Ejemplo n.º 53
0
def test_layer_sublayers():
    m = mapnik.Map(512, 512)
    strict = True
    filename = "../data/good_maps/nested-layers-1.xml"
    mapnik.load_map(m, filename, strict)

    eq_(len(m.layers), 1)
    eq_(len(m.layers[0].layers), 1)

    sublayer = m.layers[0].layers[0]
    eq_(sublayer.name, "text")
Ejemplo n.º 54
0
 def test_tif_rendering_nodata():
     m = mapnik.Map(512,512)
     mapnik.load_map(m,'../data/good_maps/tiff_colortable.xml')
     m.zoom_all()
     im = mapnik.Image(512,512)
     mapnik.render(m,im)
     actual = '/tmp/tif_colortable.png'
     expected = 'images/support/tif_colortable.png'
     im.save(actual)
     expected_im = mapnik.Image.open(expected)
     eq_(im.tostring(),expected_im.tostring(), 'failed comparing actual (%s) and expected(%s)' % (actual,'tests/python_tests/'+ expected))
Ejemplo n.º 55
0
 def test_edge_scaling_with_nodata():
     m = mapnik.Map(600,400)
     mapnik.load_map(m,'../data/good_maps/raster-nodata-edge.xml')
     m.zoom_all()
     actual = '/tmp/mapnik-raster-nodata-edge.png'
     expected = 'images/support/raster-nodata-edge.png'
     im = mapnik.Image(m.width,m.height)
     mapnik.render(m,im)
     im.save(actual)
     expected_im = mapnik.Image.open(expected)
     eq_(im.tostring(),expected_im.tostring(), 'failed comparing actual (%s) and expected(%s)' % (actual,'tests/python_tests/'+ expected))
Ejemplo n.º 56
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)
 def test_marker_ellipse_render1():
     m = mapnik.Map(256,256)
     mapnik.load_map(m,'../data/good_maps/marker_ellipse_transform.xml')
     m.zoom_all()
     im = mapnik.Image(m.width,m.height)
     mapnik.render(m,im)
     actual = '/tmp/mapnik-marker-ellipse-render1.png'
     expected = 'images/support/mapnik-marker-ellipse-render1.png'
     im.save(actual)
     expected_im = mapnik.Image.open(expected)
     eq_(im.tostring(),expected_im.tostring(), 'failed comparing actual (%s) and expected (%s)' % (actual,'tests/python_tests/'+ expected))
Ejemplo n.º 58
0
 def test_style_level_opacity():
     m = mapnik.Map(512,512)
     mapnik.load_map(m,'../data/good_maps/style_level_opacity_and_blur.xml')
     m.zoom_all()
     im = mapnik.Image(512,512)
     mapnik.render(m,im)
     actual = '/tmp/mapnik-style-level-opacity.png'
     expected = 'images/support/mapnik-style-level-opacity.png'
     im.save(actual,'png32')
     expected_im = mapnik.Image.open(expected)
     eq_(im.tostring('png32'),expected_im.tostring('png32'), 'failed comparing actual (%s) and expected (%s)' % (actual,'tests/python_tests/'+ expected))
Ejemplo n.º 59
0
    def _add_layer(self, filename, datasources):
        if not isinstance(datasources, list):
            datasources = [datasources]

        idx = len(self._map.layers)
        current_dir = pathlib.Path(__file__).parent
        mapnik.load_map(self._map, str(current_dir / '..' / filename))

        for ds in datasources:
            data = mapnik.Datasource(type='geojson', inline=json.dumps(ds))
            self._map.layers[idx].datasource = data
            idx += 1
Ejemplo n.º 60
0
 def test_map_query_in_pixels_works2():
     m = mapnik.Map(256,256)
     mapnik.load_map(m,'../data/good_maps/merc2wgs84_reprojection.xml')
     wgs84_bounds = mapnik.Box2d(-179.999999975,-85.0511287776,179.999999975,85.0511287776)
     m.maximum_extent = wgs84_bounds
     # caution - will go square due to evil aspect_fix_mode backhandedness
     m.zoom_all()
     # validate that aspect_fix_mode modified the bbox reasonably
     eq_(str(m.envelope()),str(mapnik.Box2d(-179.999999975,-167.951396161,179.999999975,192.048603789)))
     fs = m.query_map_point(0,55,100) # somewhere in Canada
     feat = fs.next()
     eq_(feat.attributes['NAME'],u'Canada')