• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python mapnik.load_map函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mapnik.load_map函数的典型用法代码示例。如果您正苦于以下问题:Python load_map函数的具体用法?Python load_map怎么用?Python load_map使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了load_map函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_style_level_comp_op

 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))
开发者ID:MapQuest,项目名称:mapnik,代码行数:31,代码来源:compositing_test.py


示例2: renderTile

    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) + ')')
开发者ID:paulsmith,项目名称:TileStache,代码行数:28,代码来源:MapnikGrid.py


示例3: test_hit_grid

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:')
开发者ID:noirbizarre,项目名称:pymapnik2,代码行数:25,代码来源:datasource_test.py


示例4: test_render_mvt_merc_nested_layers

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)
开发者ID:mapycz,项目名称:python-mapnik,代码行数:33,代码来源:mvt_render_test.py


示例5: watcher

 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
开发者ID:embrow,项目名称:tilelite,代码行数:31,代码来源:tilelite.py


示例6: render_tile

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')
开发者ID:shujaatak,项目名称:luckygps2,代码行数:35,代码来源:generate_tiles.py


示例7: renderPage

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 [email protected] +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();
开发者ID:ssinger,项目名称:cake-maker,代码行数:32,代码来源:cake-maker.py


示例8: loop

    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()
开发者ID:thomaskonrad,项目名称:osm-austria-building-coverage,代码行数:32,代码来源:generate_tiles_multiprocess.py


示例9: render

    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 [email protected]"
            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
开发者ID:JeffHeard,项目名称:terrapyn,代码行数:34,代码来源:rendering.py


示例10: generate_img

 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)
开发者ID:simone-f,项目名称:compare-to-osm,代码行数:7,代码来源:renderer.py


示例11: renderTile

    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) + ')')
开发者ID:Ahlzen,项目名称:TileStache,代码行数:32,代码来源:MapnikGrid.py


示例12: test_render_with_palette

    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))
开发者ID:cbenz,项目名称:python-mapnik,代码行数:28,代码来源:palette_test.py


示例13: test_arbitrary_parameters_attached_to_map

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)
开发者ID:kiivihal,项目名称:python-mapnik,代码行数:27,代码来源:extra_map_props_test.py


示例14: _init_mapnik

 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
开发者ID:Kotaimen,项目名称:mason,代码行数:7,代码来源:mapniker.py


示例15: test_mapnik

 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())
开发者ID:Mappy,项目名称:pycnikr,代码行数:7,代码来源:test_mapnik.py


示例16: test_non_member_known_attributes

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')
开发者ID:novldp,项目名称:mapnik,代码行数:7,代码来源:extra_map_props_test.py


示例17: test_datasource_template_is_working

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)
开发者ID:manz,项目名称:python-mapnik,代码行数:7,代码来源:datasource_xml_template_test.py


示例18: run

    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()
开发者ID:JoeGermuska,项目名称:invar,代码行数:34,代码来源:renderer.py


示例19: test_hit_grid

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))
开发者ID:MapQuest,项目名称:mapnik,代码行数:28,代码来源:datasource_test.py


示例20: test_render_mvt_with_optional_arguments

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)
开发者ID:mapycz,项目名称:python-mapnik,代码行数:27,代码来源:mvt_render_test.py



注:本文中的mapnik.load_map函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mapnik.load_map_from_string函数代码示例发布时间:2022-05-27
下一篇:
Python mapnik.has_cairo函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap