mapnik.Map

Here are the examples of the python api mapnik.Map taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

62 Examples 7

Page 1 Selected Page 2

Example 1

Project: python-mapnik Source File: markers_complex_rendering_test.py
    def test_marker_ellipse_render2():
        m = mapnik.Map(256, 256)
        mapnik.load_map(m, '../data/good_maps/marker_ellipse_transform2.xml')
        m.zoom_all()
        im = mapnik.Image(m.width, m.height)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-marker-ellipse-render2.png'
        expected = 'images/support/mapnik-marker-ellipse-render2.png'
        im.save(actual, 'png32')
        if os.environ.get('UPDATE'):
            im.save(expected, 'png32')
        expected_im = mapnik.Image.open(expected)
        eq_(im.tostring('png32'),
            expected_im.tostring('png32'),
            'failed comparing actual (%s) and expected (%s)' % (actual,
                                                                'test/python_tests/' + expected))

Example 2

Project: python-mapnik Source File: render_test.py
def get_paired_images(w, h, mapfile):
    tmp_map = 'tmp_map.xml'
    m = mapnik.Map(w, h)
    mapnik.load_map(m, mapfile)
    im = mapnik.Image(w, h)
    m.zoom_all()
    mapnik.render(m, im)
    mapnik.save_map(m, tmp_map)
    m2 = mapnik.Map(w, h)
    mapnik.load_map(m2, tmp_map)
    im2 = mapnik.Image(w, h)
    m2.zoom_all()
    mapnik.render(m2, im2)
    os.remove(tmp_map)
    return im, im2

Example 3

Project: python-mapnik Source File: pdf_printing_test.py
def make_map_from_xml(source_xml):
	m = mapnik.Map(100, 100)
	mapnik.load_map(m, source_xml, True)
	m.zoom_all()

	return m

Example 4

Project: python-mapnik Source File: map_query_test.py
    def test_map_query_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()
        # mapnik.render_to_file(m,'works2.png')
        # validate that aspect_fix_mode modified the bbox reasonably
        e = m.envelope()
        assert_almost_equal(e.minx, -179.999999975, places=7)
        assert_almost_equal(e.miny, -167.951396161, places=7)
        assert_almost_equal(e.maxx, 179.999999975, places=7)
        assert_almost_equal(e.maxy, 192.048603789, places=7)
        fs = m.query_point(0, -98.9264, 38.1432)  # somewhere in kansas
        feat = fs.next()
        eq_(feat.attributes['NAME'], u'United States')

Example 5

Project: python-mapnik Source File: compositing_test.py
def test_pre_multiply_status_of_map1():
    m = mapnik.Map(256, 256)
    im = mapnik.Image(m.width, m.height)
    eq_(validate_pixels_are_not_premultiplied(im), True)
    mapnik.render(m, im)
    eq_(validate_pixels_are_not_premultiplied(im), True)

Example 6

Project: python-mapnik Source File: markers_complex_rendering_test.py
    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, 'png32')
        if os.environ.get('UPDATE'):
            im.save(expected, 'png32')
        expected_im = mapnik.Image.open(expected)
        eq_(im.tostring('png32'),
            expected_im.tostring('png32'),
            'failed comparing actual (%s) and expected (%s)' % (actual,
                                                                'test/python_tests/' + expected))

Example 7

Project: python-mapnik Source File: render_test.py
def test_simplest_render():
    m = mapnik.Map(256, 256)
    im = mapnik.Image(m.width, m.height)
    eq_(im.painted(), False)
    eq_(im.is_solid(), True)
    mapnik.render(m, im)
    eq_(im.painted(), False)
    eq_(im.is_solid(), True)
    s = im.tostring()
    if PYTHON3:
        eq_(s, 256 * 256 * b'\x00\x00\x00\x00')
    else:
        eq_(s, 256 * 256 * '\x00\x00\x00\x00')

Example 8

Project: python-mapnik Source File: compositing_test.py
def test_background_image_and_background_color():
    m = mapnik.Map(8, 8)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    m.background_image = '../data/images/stripes_pattern.png'
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    eq_(get_unique_colors(im), ['rgba(255,255,255,128)', 'rgba(74,74,74,255)'])

Example 9

Project: python-mapnik Source File: reprojection_test.py
    def test_visual_zoom_all_rendering3():
        m = mapnik.Map(512, 512)
        mapnik.load_map(m, '../data/good_maps/bounds_clipping.xml')
        m.zoom_all()
        im = mapnik.Image(512, 512)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-merc2merc-reprojection-render1.png'
        expected = 'images/support/mapnik-merc2merc-reprojection-render1.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,
                                                                'test/python_tests/' + expected))

Example 10

Project: TileStache Source File: MapnikGrid.py
def get_mapnikMap(mapfile):
    """ Get a new mapnik.Map instance for a mapfile
    """
    mmap = mapnik.Map(0, 0)

    if exists(mapfile):
        mapnik.load_map(mmap, str(mapfile))

    else:
        handle, filename = mkstemp()
        os.write(handle, urlopen(mapfile).read())
        os.close(handle)

        mapnik.load_map(mmap, filename)
        os.unlink(filename)

    return mmap

Example 11

Project: python-mapnik Source File: map_query_test.py
    @raises(RuntimeError)
    def test_map_query_throw5():
        m = mapnik.Map(256, 256)
        mapnik.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml')
        m.zoom_all()
        m.query_point(0, 9999999999999999, 9999999999999999)

Example 12

Project: python-mapnik Source File: compositing_test.py
def test_pre_multiply_status_of_map2():
    m = mapnik.Map(256, 256)
    m.background = mapnik.Color(1, 1, 1, 255)
    im = mapnik.Image(m.width, m.height)
    eq_(validate_pixels_are_not_premultiplied(im), True)
    mapnik.render(m, im)
    eq_(validate_pixels_are_not_premultiplied(im), True)

Example 13

Project: landez Source File: sources.py
    def _prepare_rendering(self, bbox, width=None, height=None):
        if not self._mapnik:
            self._mapnik = mapnik.Map(width, height)
            # Load style XML
            mapnik.load_map(self._mapnik, self.stylefile, True)
            # Obtain <Map> projection
            self._prj = mapnik.Projection(self._mapnik.srs)

        # Convert to map projection
        assert len(bbox) == 4, _("Provide a bounding box tuple (minx, miny, maxx, maxy)")
        c0 = self._prj.forward(mapnik.Coord(bbox[0], bbox[1]))
        c1 = self._prj.forward(mapnik.Coord(bbox[2], bbox[3]))

        # Bounding box for the tile
        bbox = mapnik.Box2d(c0.x, c0.y, c1.x, c1.y)
        self._mapnik.resize(width, height)
        self._mapnik.zoom_to_box(bbox)
        self._mapnik.buffer_size = 128

Example 14

Project: python-mapnik Source File: map_query_test.py
    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
        e = m.envelope()
        assert_almost_equal(e.minx, -179.999999975, places=7)
        assert_almost_equal(e.miny, -167.951396161, places=7)
        assert_almost_equal(e.maxx, 179.999999975, places=7)
        assert_almost_equal(e.maxy, 192.048603789, places=7)
        fs = m.query_map_point(0, 55, 100)  # somewhere in Canada
        feat = fs.next()
        eq_(feat.attributes['NAME'], u'Canada')

Example 15

Project: python-mapnik Source File: map_query_test.py
    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')

Example 16

Project: python-mapnik Source File: raster_symbolizer_test.py
def test_load_save_map():
    map = mapnik.Map(256, 256)
    in_map = "../data/good_maps/raster_symbolizer.xml"
    try:
        mapnik.load_map(map, in_map)

        out_map = mapnik.save_map_to_string(map)
        assert 'RasterSymbolizer' in out_map
        assert 'RasterColorizer' in out_map
        assert 'stop' in out_map
    except RuntimeError as e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))

Example 17

Project: python-mapnik Source File: compositing_test.py
def test_background_image_with_alpha_and_background_color_against_composited_control():
    m = mapnik.Map(10, 10)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    m.background_image = '../data/images/yellow_half_trans.png'
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    # create and composite the expected result
    im1 = mapnik.Image(10, 10)
    im1.fill(mapnik.Color('rgba(255,255,255,.5)'))
    im1.premultiply()
    im2 = mapnik.Image(10, 10)
    im2.fill(mapnik.Color('rgba(255,255,0,.5)'))
    im2.premultiply()
    im1.composite(im2)
    im1.demultiply()

Example 18

Project: python-mapnik Source File: reprojection_test.py
    def test_visual_zoom_all_rendering1():
        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()
        im = mapnik.Image(512, 512)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-wgs842merc-reprojection-render.png'
        expected = 'images/support/mapnik-wgs842merc-reprojection-render.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,
                                                                'test/python_tests/' + expected))

Example 19

Project: python-mapnik Source File: map_query_test.py
    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()
        # somewhere in kansas
        fs = m.query_point(0, -11012435.5376, 4599674.6134)
        feat = fs.next()
        eq_(feat.attributes['NAME_FORMA'], u'United States of America')

Example 20

Project: MeraMap Source File: z0_generate_tiles.py
Function: init
    def __init__(self, tile_dir, mapfile, q, printLock, maxZoom):
        self.tile_dir = tile_dir
        self.q = q
        self.m = mapnik.Map(256, 256)
        self.printLock = printLock
        # 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)

Example 21

Project: python-mapnik Source File: reprojection_test.py
    def test_visual_zoom_all_rendering2():
        m = mapnik.Map(512, 512)
        mapnik.load_map(m, '../data/good_maps/merc2wgs84_reprojection.xml')
        m.zoom_all()
        im = mapnik.Image(512, 512)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-merc2wgs84-reprojection-render.png'
        expected = 'images/support/mapnik-merc2wgs84-reprojection-render.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,
                                                                'test/python_tests/' + expected))

Example 22

Project: python-mapnik Source File: fontset_test.py
def test_loading_fontset_from_map():
    m = mapnik.Map(256, 256)
    mapnik.load_map(m, '../data/good_maps/fontset.xml', True)
    fs = m.find_fontset('book-fonts')
    eq_(len(fs.names), 2)
    eq_(list(fs.names), ['DejaVu Sans Book', 'DejaVu Sans Oblique'])

Example 23

Project: python-mapnik Source File: datasource_xml_template_test.py
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)

Example 24

Project: python-mapnik Source File: layer_buffer_size_test.py
    def test_layer_buffer_size_1():
        m = mapnik.Map(512, 512)
        eq_(m.buffer_size, 0)
        mapnik.load_map(m, '../data/good_maps/layer_buffer_size_reduction.xml')
        eq_(m.buffer_size, 256)
        eq_(m.layers[0].buffer_size, -150)
        m.zoom_all()
        im = mapnik.Image(m.width, m.height)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-layer-buffer-size.png'
        expected = 'images/support/mapnik-layer-buffer-size.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))

Example 25

Project: python-mapnik Source File: extra_map_props_test.py
def test_serializing_arbitrary_parameters():
    m = mapnik.Map(256, 256)
    m.parameters.append(mapnik.Parameter('width', m.width))
    m.parameters.append(mapnik.Parameter('height', m.height))

    m2 = mapnik.Map(1, 1)
    mapnik.load_map_from_string(m2, mapnik.save_map_to_string(m))
    eq_(m2.parameters['width'], m.width)
    eq_(m2.parameters['height'], m.height)

Example 26

Project: python-mapnik Source File: compositing_test.py
    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))

Example 27

Project: mapbook Source File: mapbook.py
	def __init__(self, fobj, area, appearance):
		# Setup cairo
		self.area = area
		self._surface=cairo.PDFSurface(fobj,*(self.area.pagesize_points))
		self._ctx = cairo.Context(self._surface)
		self.appearance = appearance
		
		# Setup mapnik
		self._m=mapnik.Map(*(self.area.pagesize_pixels))
		
		self._m.aspect_fix_mode=mapnik.aspect_fix_mode.GROW_BBOX
			
		self._im=mapnik.Image(*(self.area.pagesize_pixels))
		mapnik.load_map(self._m,self.appearance.mapfile) # Fixme: specify srs?
		
		self._m.buffer_size = int(0.5*max(self.area.pagesize_pixels[0],self.area.pagesize_pixels[1]))	

Example 28

Project: python-mapnik Source File: compositing_test.py
def test_background_image_with_alpha_and_background_color():
    m = mapnik.Map(10, 10)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    m.background_image = '../data/images/yellow_half_trans.png'
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    eq_(get_unique_colors(im), ['rgba(255,255,85,191)'])

Example 29

Project: python-mapnik Source File: reprojection_test.py
    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()

Example 30

Project: python-mapnik Source File: reprojection_test.py
    def test_visual_zoom_all_rendering4():
        m = mapnik.Map(512, 512)
        mapnik.load_map(m, '../data/good_maps/bounds_clipping.xml')
        m.maximum_extent = None
        m.zoom_all()
        im = mapnik.Image(512, 512)
        mapnik.render(m, im)
        actual = '/tmp/mapnik-merc2merc-reprojection-render2.png'
        expected = 'images/support/mapnik-merc2merc-reprojection-render2.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,
                                                                'test/python_tests/' + expected))

Example 31

Project: MeraMap Source File: generate_xml.py
Function: serialize
def serialize(xml,options):
    try:
        import mapnik
    except:
        sys.exit(color_text(1,'Error: saving xml requires Mapnik python bindings to be installed'))
    m = mapnik.Map(1,1)
    if options.from_string:
        mapnik.load_map_from_string(m,xml,True)
    else:
        mapnik.load_map(m,xml,True)
    if options.output:
        mapnik.save_map(m,options.output)
    else:
        if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 700:
            print mapnik.save_map_to_string(m)
        else:
            sys.exit(color_text(1,'Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file'))

Example 32

Project: quantumnik Source File: quantumnik.py
Function: load_xml
    def load_xml(self,refresh=False):
        # TODO - consider putting into its own layer:
        # https://trac.osgeo.org/qgis/ticket/2392#comment:4
        self.from_mapfile = True
        self.mapfile_format = 'xml mapfile'
        if self.loaded_mapfile and refresh:
            mapfile = self.loaded_mapfile
        else:
            mapfile = QFileDialog.getOpenFileName(None, "Open file dialog",
                                                  '', "XML Mapfile (*.xml)")
        if mapfile:
            self.mapnik_map = mapnik.Map(1,1)
            mapnik.load_map(self.mapnik_map,str(mapfile))
            if self.loaded_mapfile and refresh:
                self.set_mapnik_to_canvas()            
            else:
                self.set_canvas_from_mapnik()
            self.loaded_mapfile = str(mapfile)

Example 33

Project: python-mapnik Source File: extra_map_props_test.py
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)

Example 34

Project: python-mapnik Source File: map_query_test.py
@raises(IndexError)
def test_map_query_throw2():
    m = mapnik.Map(256, 256)
    m.query_point(-1, 0, 0)

Example 35

Project: python-mapnik Source File: compositing_test.py
def test_rounding_and_color_expectations():
    m = mapnik.Map(1, 1)
    m.background = mapnik.Color('rgba(255,255,255,.4999999)')
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    eq_(get_unique_colors(im), ['rgba(255,255,255,127)'])
    m = mapnik.Map(1, 1)
    m.background = mapnik.Color('rgba(255,255,255,.5)')
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)
    eq_(get_unique_colors(im), ['rgba(255,255,255,128)'])
    im_file = mapnik.Image.open('../data/images/stripes_pattern.png')
    eq_(get_unique_colors(im_file), ['rgba(0,0,0,0)', 'rgba(74,74,74,255)'])
    # should have no effect
    im_file.premultiply()
    eq_(get_unique_colors(im_file), ['rgba(0,0,0,0)', 'rgba(74,74,74,255)'])
    im_file.apply_opacity(.5)
    # should have effect now that image has transparency
    im_file.premultiply()
    eq_(get_unique_colors(im_file), ['rgba(0,0,0,0)', 'rgba(37,37,37,127)'])
    # should restore to original nonpremultiplied colors
    im_file.demultiply()
    eq_(get_unique_colors(im_file), ['rgba(0,0,0,0)', 'rgba(74,74,74,127)'])

Example 36

Project: tilelite Source File: tilelite.py
Function: init
    def __init__(self, mapfile, config=None):
        # private
        self._changed = []
        self._config = config
        self._locked = False

        self._log = logging.getLogger('tilelite')
        
        # mutable
        self.size = 256
        self.buffer_size = 128
        self.format = 'png'
        self.paletted = False
        self.max_zoom = 22
        self.debug = True
        self.watch_mapfile = False
        self.watch_interval = 2
        self.max_failures = 6

        self.caching = False
        self.cache_force = False
        self.cache_path = '/tmp' #tempfile.gettempdir()
        self.metatile = 0

        self._mapnik_map = mapnik.Map(self.size,self.size)

        if self._config:
            self.absorb_options(parse_config(self._config))

        self._mapfile = mapfile
        if mapfile.endswith('.xml'):
            mapnik.load_map(self._mapnik_map, self._mapfile)
        elif mapfile.endswith('.mml'):
            import cascadenik
            if hasattr(cascadenik,'VERSION'):
                major = int(cascadenik.VERSION.split('.')[0])
                if major < 1:
                    from cascadenik import compile as _compile
                    compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                    open(compiled, 'w').write(_compile(self._mapfile))
                    mapnik.load_map(self._mapnik_map, compiled)
                elif major == 1:
                    if str(mapfile).startswith('http'):
                        output_dir = os.getcwd() #os.path.expanduser('~/.cascadenik')
                    else:
                        output_dir = os.path.dirname(str(mapfile))
                    cascadenik.load_map(self._mapnik_map,mapfile,output_dir,verbose=self.debug)
                elif major > 1:
                    raise NotImplementedError('This TileLite version does not yet support Cascadenik > 1.x, please upgrade to the latest release')
            else:
                from cascadenik import compile as _compile
                compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                open(compiled, 'w').write(_compile(self._mapfile))
                mapnik.load_map(self._mapnik_map, compiled)

        self.post_init_setup()
        
        if self.watch_mapfile:
            self.modified = os.path.getmtime(self._mapfile)
            import thread
            thread.start_new_thread(self.watcher, ())
        self._mapnik_map.zoom_all()
        self.envelope = self._mapnik_map.envelope()

        self.empty_tile = mapnik.Image(self.size, self.size)
        if self._mapnik_map.background:
            self.empty_tile.background = self._mapnik_map.background

Example 37

Project: OGCServer Source File: common.py
    def _buildMap(self, params):
        if str(params['crs']) not in self.allowedepsgcodes:
            raise OGCException('Unsupported CRS "%s" requested.' % str(params['crs']).upper(), 'InvalidCRS')
        if params['bbox'][0] >= params['bbox'][2]:
            raise OGCException("BBOX values don't make sense.  minx is greater than maxx.")
        if params['bbox'][1] >= params['bbox'][3]:
            raise OGCException("BBOX values don't make sense.  miny is greater than maxy.")

        # relax this for now to allow for a set of specific layers (meta layers even)
        # to be used without known their styles or putting the right # of commas...

        #if params.has_key('styles') and len(params['styles']) != len(params['layers']):
        #    raise OGCException('STYLES length does not match LAYERS length.')
        m = Map(params['width'], params['height'], '+init=%s' % params['crs'])

        transparent = params.get('transparent', '').lower() == 'true'

        # disable transparent on incompatible formats 
        if transparent and params.get('format', '') == 'image/jpeg':
            transparent = False

        if transparent:
            # transparent has highest priority
            pass
        elif params.has_key('bgcolor'):
            # if not transparent use bgcolor in url            
            m.background = params['bgcolor']
        else:
            # if not bgcolor in url use map background
            if mapnik_version() >= 200000:
                bgcolor = self.mapfactory.map_attributes.get('bgcolor', None)
            else:
                bgcolor = self.mapfactory.map_attributes.get('background-color', None)

            if bgcolor:
                m.background = bgcolor
            else:
                # if not map background defined use white color
                m.background = Color(255, 255, 255, 255)


        if params.has_key('buffer_size'):
            if params['buffer_size']:
                m.buffer_size = params['buffer_size']
        else:
            buffer_ = self.mapfactory.map_attributes.get('buffer_size')
            if buffer_:
                m.buffer_size = self.mapfactory.map_attributes['buffer_size']

        # haiti spec tmp hack! show meta layers without having
        # to request huge string to avoid some client truncating it!
        if params['layers'] and params['layers'][0] in ('osm_haiti_overlay','osm_haiti_overlay_900913'):
            for layer_obj in self.mapfactory.ordered_layers:
                layer = copy_layer(layer_obj)
                if not hasattr(layer,'meta_style'):
                    pass
                else:
                    layer.styles.append(layer.meta_style)
                    m.append_style(layer.meta_style, self.mapfactory.meta_styles[layer.meta_style])
                    m.layers.append(layer)        
        # a non WMS spec way of requesting all layers
        # uses orderedlayers that preserves original ordering in XML mapfile
        elif params['layers'] and params['layers'][0] == '__all__':
            for layer_obj in self.mapfactory.ordered_layers:
                # if we don't copy the layer here we get
                # duplicate layers added to the map because the
                # layer is kept around and the styles "pile up"...
                layer = copy_layer(layer_obj)
                if hasattr(layer,'meta_style'):
                    continue
                reqstyle = layer.wmsdefaultstyle
                if reqstyle in self.mapfactory.aggregatestyles.keys():
                    for stylename in self.mapfactory.aggregatestyles[reqstyle]:
                        layer.styles.append(stylename)
                else:
                    layer.styles.append(reqstyle)
                for stylename in layer.styles:
                    if stylename in self.mapfactory.styles.keys():
                        m.append_style(stylename, self.mapfactory.styles[stylename])
                m.layers.append(layer)
        else:
            for layerindex, layername in enumerate(params['layers']):
                if layername in self.mapfactory.meta_layers:
                    layer = copy_layer(self.mapfactory.meta_layers[layername])
                    layer.styles.append(layername)
                    m.append_style(layername, self.mapfactory.meta_styles[layername])
                else:
                    try:
                        # uses unordered dict of layers
                        # order based on params['layers'] request which
                        # should be originally informed by order of GetCaps response
                        layer = copy_layer(self.mapfactory.layers[layername])
                    except KeyError:
                        raise OGCException('Layer "%s" not defined.' % layername, 'LayerNotDefined')
                    try:
                        reqstyle = params['styles'][layerindex]
                    except IndexError:
                        reqstyle = ''
                    if len(layer.wmsextrastyles) > 1 and reqstyle == 'default':
                        reqstyle = ''
                    if reqstyle and reqstyle not in layer.wmsextrastyles:
                        raise OGCException('Invalid style "%s" requested for layer "%s".' % (reqstyle, layername), 'StyleNotDefined')
                    if not reqstyle:
                        reqstyle = layer.wmsdefaultstyle
                    if reqstyle in self.mapfactory.aggregatestyles.keys():
                        for stylename in self.mapfactory.aggregatestyles[reqstyle]:
                            layer.styles.append(stylename)
                    else:
                        layer.styles.append(reqstyle)

                    for stylename in layer.styles:
                        if stylename in self.mapfactory.styles.keys():
                            m.append_style(stylename, self.mapfactory.styles[stylename])
                        else:
                            raise ServerConfigurationError('Layer "%s" refers to non-existent style "%s".' % (layername, stylename))
                
                m.layers.append(layer)
        m.zoom_to_box(Envelope(params['bbox'][0], params['bbox'][1], params['bbox'][2], params['bbox'][3]))
        return m

Example 38

Project: OGCServer Source File: WMS.py
    def loadXML(self, xmlfile=None, strict=False, xmlstring='', basepath=''):
        config = ConfigParser.SafeConfigParser()
        map_wms_srs = None
        if self.configpath:
            config.readfp(open(self.configpath))

            if config.has_option('map', 'wms_srs'):
                map_wms_srs = config.get('map', 'wms_srs')

        tmp_map = Map(0,0)
        if xmlfile:
            load_map(tmp_map, xmlfile, strict)
        elif xmlstring:
            load_map_from_string(tmp_map, xmlstring, strict, basepath)
        else:
            raise ServerConfigurationError("Mapnik configuration XML is not specified - 'xmlfile' and 'xmlstring' variables are empty.\
Please set one of this variables to load mapnik map object.")
        # parse map level attributes
        if tmp_map.background:
            self.map_attributes['bgcolor'] = tmp_map.background
        if tmp_map.buffer_size:
            self.map_attributes['buffer_size'] = tmp_map.buffer_size
        for lyr in tmp_map.layers:
            layer_section = 'layer_%s' % lyr.name
            layer_wms_srs = None
            if config.has_option(layer_section, 'wms_srs'):
                layer_wms_srs = config.get(layer_section, 'wms_srs')
            else:
                layer_wms_srs = map_wms_srs

            if config.has_option(layer_section, 'title'):
                lyr.title = config.get(layer_section, 'title')
            else:
                lyr.title = ''

            if config.has_option(layer_section, 'abstract'):
                lyr.abstract = config.get(layer_section, 'abstract')
            else:
                lyr.abstract = ''

            style_count = len(lyr.styles)
            if style_count == 0:
                raise ServerConfigurationError("Cannot register Layer '%s' without a style" % lyr.name)
            elif style_count == 1:
                style_obj = tmp_map.find_style(lyr.styles[0])
                style_name = lyr.styles[0]

                meta_s = extract_named_rules(style_obj)
                if meta_s:
                    self.meta_styles['%s_meta' % lyr.name] = meta_s
                    if hasattr(lyr,'abstract'):
                        name_ = lyr.abstract
                    else:
                        name_ = lyr.name
                    meta_layer_name = '%s:%s' % (name_,'-'.join(meta_s.names))
                    meta_layer_name = meta_layer_name.replace(' ','_')
                    self.meta_styles[meta_layer_name] = meta_s
                    meta_lyr = common.copy_layer(lyr)
                    meta_lyr.meta_style = meta_layer_name
                    meta_lyr.name = meta_layer_name
                    meta_lyr.wmsextrastyles = ()
                    meta_lyr.defaultstyle = meta_layer_name
                    meta_lyr.wms_srs = layer_wms_srs
                    self.ordered_layers.append(meta_lyr)
                    self.meta_layers[meta_layer_name] = meta_lyr
                    print meta_layer_name

                if style_name not in self.aggregatestyles.keys() and style_name not in self.styles.keys():
                    self.register_style(style_name, style_obj)

                # must copy layer here otherwise we'll segfault
                lyr_ = common.copy_layer(lyr)
                lyr_.wms_srs = layer_wms_srs
                self.register_layer(lyr_, style_name, extrastyles=(style_name,))

            elif style_count > 1:
                for style_name in lyr.styles:
                    style_obj = tmp_map.find_style(style_name)

                    meta_s = extract_named_rules(style_obj)
                    if meta_s:
                        self.meta_styles['%s_meta' % lyr.name] = meta_s
                        if hasattr(lyr,'abstract'):
                            name_ = lyr.abstract
                        else:
                            name_ = lyr.name
                        meta_layer_name = '%s:%s' % (name_,'-'.join(meta_s.names))
                        meta_layer_name = meta_layer_name.replace(' ','_')
                        self.meta_styles[meta_layer_name] = meta_s
                        meta_lyr = common.copy_layer(lyr)
                        meta_lyr.meta_style = meta_layer_name
                        print meta_layer_name
                        meta_lyr.name = meta_layer_name
                        meta_lyr.wmsextrastyles = ()
                        meta_lyr.defaultstyle = meta_layer_name
                        meta_lyr.wms_srs = layer_wms_srs
                        self.ordered_layers.append(meta_lyr)
                        self.meta_layers[meta_layer_name] = meta_lyr

                    if style_name not in self.aggregatestyles.keys() and style_name not in self.styles.keys():
                        self.register_style(style_name, style_obj)
                aggregates = tuple([sty for sty in lyr.styles])
                aggregates_name = '%s_aggregates' % lyr.name
                self.register_aggregate_style(aggregates_name,aggregates)
                # must copy layer here otherwise we'll segfault
                lyr_ = common.copy_layer(lyr)
                lyr_.wms_srs = layer_wms_srs
                self.register_layer(lyr_, aggregates_name, extrastyles=aggregates)
                if 'default' in aggregates:
                    sys.stderr.write("Warning: Multi-style layer '%s' contains a regular style named 'default'. \
This style will effectively be hidden by the 'all styles' default style for multi-style layers.\n" % lyr_.name)

Example 39

Project: python-mapnik Source File: datasource_test.py
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 xrange(0, 256, 4):
            for x in xrange(0, 256, 4):
                featureset = m.query_map_point(0, x, y)
                added = False
                for feature in featureset:
                    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 as e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))

Example 40

Project: quantumnik Source File: quantumnik.py
    def load_mml(self,refresh=False):
        self.from_mapfile = True
        self.mapfile_format = 'Cascadenik mml'
        if self.loaded_mapfile and refresh:
            mapfile = self.loaded_mapfile
        else:
            mapfile = QFileDialog.getOpenFileName(None, "Open file dialog",
                                                  '', "Cascadenik MML (*.mml)")
        if mapfile:
            self.mapnik_map = mapnik.Map(1,1)
            import cascadenik
            if hasattr(cascadenik,'VERSION'):
                major = int(cascadenik.VERSION.split('.')[0])
                if major < 1:
                    from cascadenik import compile
                    compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                    open(compiled, 'w').write(compile(str(mapfile)))
                    mapnik.load_map(self.mapnik_map, compiled)
                elif major == 1:
                    output_dir = os.path.dirname(str(mapfile))
                    cascadenik.load_map(self.mapnik_map,str(mapfile),output_dir,verbose=False)
                elif major > 1:
                    raise NotImplementedError('This nik2img version does not yet support Cascadenik > 1.x, please upgrade nik2img to the latest release')
            else:
                from cascadenik import compile
                compiled = '%s_compiled.xml' % os.path.splitext(str(mapfile))[0]
                #if os.path.exits(compiled):
                    #pass
                open(compiled, 'w').write(compile(str(mapfile)))
                mapnik.load_map(self.mapnik_map, compiled)

            if self.loaded_mapfile and refresh:
                self.set_mapnik_to_canvas()            
            else:
                self.set_canvas_from_mapnik()
            self.loaded_mapfile = str(mapfile)

Example 41

Project: tilelite Source File: tilelite.py
Function: 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
        return

Example 42

Project: python-mapnik Source File: cairo_test.py
def make_tmp_map():
    m = mapnik.Map(512, 512)
    m.background_color = mapnik.Color('steelblue')
    ds = mapnik.MemoryDatasource()
    context = mapnik.Context()
    context.push('Name')
    f = mapnik.Feature(context, 1)
    f['Name'] = 'Hello'
    f.geometry = mapnik.Geometry.from_wkt('POINT (0 0)')
    ds.add_feature(f)
    s = mapnik.Style()
    r = mapnik.Rule()
    sym = mapnik.MarkersSymbolizer()
    sym.allow_overlap = True
    r.symbols.append(sym)
    s.rules.append(r)
    lyr = mapnik.Layer('Layer')
    lyr.datasource = ds
    lyr.styles.append('style')
    m.append_style('style', s)
    m.layers.append(lyr)
    return m

Example 43

Project: python-mapnik Source File: cairo_test.py
        def _pycairo_surface(type, sym):
            test_cairo_file = '/tmp/mapnik-cairo-surface-test.%s.%s' % (
                sym, type)
            expected_cairo_file = './images/pycairo/cairo-surface-expected.%s.%s' % (
                sym, type)
            m = mapnik.Map(256, 256)
            mapnik.load_map(m, '../data/good_maps/%s_symbolizer.xml' % sym)
            m.zoom_all()
            if hasattr(cairo, '%sSurface' % type.upper()):
                surface = getattr(
                    cairo,
                    '%sSurface' %
                    type.upper())(
                    test_cairo_file,
                    m.width,
                    m.height)
                mapnik.render(m, surface)
                surface.finish()
                if not os.path.exists(
                        expected_cairo_file) or os.environ.get('UPDATE'):
                    print(
                        'generated expected cairo surface file',
                        expected_cairo_file)
                    shutil.copy(test_cairo_file, expected_cairo_file)
                diff = abs(
                    os.stat(expected_cairo_file).st_size -
                    os.stat(test_cairo_file).st_size)
                msg = 'diff in size (%s) between actual (%s) and expected(%s)' % (
                    diff, test_cairo_file, 'tests/python_tests/' + expected_cairo_file)
                if os.uname()[0] == 'Darwin':
                    eq_(diff < 2100, True, msg)
                else:
                    eq_(diff < 23000, True, msg)
                os.remove(test_cairo_file)
                return True
            else:
                print(
                    'skipping cairo.%s test since surface is not available' %
                    type.upper())
                return True

Example 44

Project: python-mapnik Source File: filter_test.py
def test_filter_init():
    m = mapnik.Map(1, 1)
    mapnik.load_map_from_string(m, map_)
    filters = []
    filters.append(mapnik.Filter("([region]>=0) and ([region]<=50)"))
    filters.append(mapnik.Filter("(([region]>=0) and ([region]<=50))"))
    filters.append(mapnik.Filter("((([region]>=0) and ([region]<=50)))"))
    filters.append(mapnik.Filter('((([region]>=0) and ([region]<=50)))'))
    filters.append(mapnik.Filter('''((([region]>=0) and ([region]<=50)))'''))
    filters.append(mapnik.Filter('''
    ((([region]>=0)
    and
    ([region]<=50)))
    '''))
    filters.append(mapnik.Filter('''
    ([region]>=0)
    and
    ([region]<=50)
    '''))
    filters.append(mapnik.Filter('''
    ([region]
    >=
    0)
    and
    ([region]
    <=
    50)
    '''))

    s = m.find_style('s')

    for r in s.rules:
        filters.append(r.filter)

    first = filters[0]
    for f in filters:
        eq_(str(first), str(f))

    s = m.find_style('s2')

    eq_(s.filter_mode, mapnik.filter_mode.FIRST)

Example 45

Project: python-mapnik Source File: image_filters_test.py
    def test_style_level_image_filter():
        m = mapnik.Map(256, 256)
        mapnik.load_map(m, '../data/good_maps/style_level_image_filter.xml')
        m.zoom_all()
        successes = []
        fails = []
        for name in ("", "agg-stack-blur(2,2)", "blur",
                     "edge-detect", "emboss", "gray", "invert",
                     "sharpen", "sobel", "x-gradient", "y-gradient"):
            if name == "":
                filename = "none"
            else:
                filename = re.sub(r"[^-_a-z.0-9]", "", name)
            # find_style returns a copy of the style object
            style_markers = m.find_style("markers")
            style_markers.image_filters = name
            style_labels = m.find_style("labels")
            style_labels.image_filters = name
            # replace the original style with the modified one
            replace_style(m, "markers", style_markers)
            replace_style(m, "labels", style_labels)
            im = mapnik.Image(m.width, m.height)
            mapnik.render(m, im)
            actual = '/tmp/mapnik-style-image-filter-' + filename + '.png'
            expected = 'images/style-image-filter/' + filename + '.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-image-filter-' +
                    filename +
                    '.fail.png',
                    'png32')
        eq_(len(fails), 0, '\n' + '\n'.join(fails))

Example 46

Project: python-mapnik Source File: layer_modification_test.py
def test_adding_datasource_to_layer():
    map_string = '''<?xml version="1.0" encoding="utf-8"?>
<Map>

    <Layer name="world_borders">
        <StyleName>world_borders_style</StyleName>
        <StyleName>point_style</StyleName>
        <!-- leave datasource empty -->
        <!--
        <Datasource>
            <Parameter name="file">../data/shp/world_merc.shp</Parameter>
            <Parameter name="type">shape</Parameter>
        </Datasource>
        -->
    </Layer>

</Map>
'''
    m = mapnik.Map(256, 256)

    try:
        mapnik.load_map_from_string(m, map_string)

        # validate it loaded fine
        eq_(m.layers[0].styles[0], 'world_borders_style')
        eq_(m.layers[0].styles[1], 'point_style')
        eq_(len(m.layers), 1)

        # also assign a variable reference to that layer
        # below we will test that this variable references
        # the same object that is attached to the map
        lyr = m.layers[0]

        # ensure that there was no datasource for the layer...
        eq_(m.layers[0].datasource, None)
        eq_(lyr.datasource, None)

        # also note that since the srs was black it defaulted to wgs84
        eq_(m.layers[0].srs,
            '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        eq_(lyr.srs, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')

        # now add a datasource one...
        ds = mapnik.Shapefile(file='../data/shp/world_merc.shp')
        m.layers[0].datasource = ds

        # now ensure it is attached
        eq_(m.layers[0].datasource.describe()['name'], "shape")
        eq_(lyr.datasource.describe()['name'], "shape")

        # and since we have now added a shapefile in spherical mercator, adjust
        # the projection
        lyr.srs = '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'

        # test that assignment
        eq_(m.layers[
            0].srs, '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
        eq_(lyr.srs, '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
    except RuntimeError as e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(e)

Example 47

Project: python-mapnik Source File: load_map_test.py
Function: test_good_files
def test_good_files():
    good_files = glob.glob("../data/good_maps/*.xml")
    good_files.extend(glob.glob("../visual_tests/styles/*.xml"))

    failures = []
    for filename in good_files:
        try:
            m = mapnik.Map(512, 512)
            strict = True
            mapnik.load_map(m, filename, strict)
            base_path = os.path.dirname(filename)
            with open(filename, 'rb') as f:
                mapnik.load_map_from_string(m, f.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))

Example 48

Project: create-utfgrids Source File: create_utfgrids.py
def create_utfgrids(shppath, minzoom, maxzoom, outdir, fields=None, layernum=0):
    ds = ogr.Open(shppath)
    print 
    print "WARNING:"
    print " This script assumes a polygon shapefile in spherical mercator projection."
    print " If any of these assumptions are not true, don't count on the results!"
    # TODO confirm polygons
    # TODO confirm mercator
    # TODO get layernum from command line 
    layer = ds.GetLayer(layernum)
    bbox = layer.GetExtent()

    mercator = globalmaptiles.GlobalMercator()
            
    m = mapnik.Map(256,256)

    # Since grids are `rendered` they need a style 
    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)

    ds = mapnik.Shapefile(file=shppath)
    mlayer = mapnik.Layer('poly')
    mlayer.datasource = ds
    mlayer.styles.append('My Style')
    m.layers.append(mlayer)

    if fields is None:
        fields = mlayer.datasource.fields() 

    for tz in range(minzoom, maxzoom+1):
        print " * Processing Zoom Level %s" % tz
        tminx, tminy = mercator.MetersToTile( bbox[0], bbox[2], tz)
        tmaxx, tmaxy = mercator.MetersToTile( bbox[1], bbox[3], tz)
        for ty in range(tminy, tmaxy+1):
            for tx in range(tminx, tmaxx+1):
                output = os.path.join(outdir, str(tz), str(tx))
                if not os.path.exists(output):
                    os.makedirs(output)

                # Use top origin tile scheme (like OSM or GMaps)
                # TODO support option for TMS bottom origin scheme (ie opt to not invert)
                ymax = 1 << tz;
                invert_ty = ymax - ty - 1;

                tilefilename = os.path.join(output, "%s.json" % invert_ty) # ty for TMS bottom origin
                tilebounds = mercator.TileBounds( tx, ty, tz)
                #print tilefilename, tilebounds

                box = mapnik.Box2d(*tilebounds)
                m.zoom_to_box(box)
                grid = mapnik.Grid(m.width,m.height)
                mapnik.render_layer(m,grid,layer=0,fields=fields)
                utfgrid = grid.encode('utf',resolution=4)
                with open(tilefilename, 'w') as file:
                    file.write(json.dumps(utfgrid))

Example 49

Project: python-mapnik Source File: compositing_test.py
    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))

Example 50

Project: python-mapnik Source File: map_query_test.py
@raises(IndexError)
def test_map_query_throw1():
    m = mapnik.Map(256, 256)
    m.zoom_to_box(mapnik.Box2d(-1, -1, 0, 0))
    m.query_point(0, 0, 0)
See More Examples - Go to Next Page
Page 1 Selected Page 2