Example #1
0
def test_render_grid():
    """ test old method """
    width,height = 256,256
    m = create_grid_map(width,height)
    ul_lonlat = mapnik2.Coord(142.30,-38.20)
    lr_lonlat = mapnik2.Coord(143.40,-38.80)
    m.zoom_to_box(mapnik2.Box2d(ul_lonlat,lr_lonlat))
    grid = mapnik2.render_grid(m,0,key='Name',resolution=4,fields=['Name'])
    eq_(grid,grid_correct)
    eq_(resolve(grid,0,0),None)
    
    # check every pixel of the nw symbol
    expected = {"Name": "North West"}
    
    # top row
    eq_(resolve(grid,23,9),expected)
    eq_(resolve(grid,23,10),expected)
    eq_(resolve(grid,23,11),expected)

    # core
    eq_(resolve(grid,24,8),expected)
    eq_(resolve(grid,24,9),expected)
    eq_(resolve(grid,24,10),expected)
    eq_(resolve(grid,24,11),expected)
    eq_(resolve(grid,24,12),expected)
    eq_(resolve(grid,25,8),expected)
    eq_(resolve(grid,25,9),expected)
    eq_(resolve(grid,25,10),expected)
    eq_(resolve(grid,25,11),expected)
    eq_(resolve(grid,25,12),expected)
    
    # bottom row
    eq_(resolve(grid,26,9),expected)
    eq_(resolve(grid,26,10),expected)
    eq_(resolve(grid,26,11),expected)
def render_legend(mapfile, tile_uri):
    m = mapnik.Map(1024, 2048)
    # 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(20)

    # Convert to map projection (e.g. mercator co-ords EPSG:900913)
    c0 = prj.forward(mapnik.Coord(14.4503,50.0673))
    c1 = prj.forward(mapnik.Coord(14.457,50.0678))

    # Bounding box for the tile
    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)
    render_size_x = 1024
    render_size_y = 1500
    m.resize(render_size_x, render_size_y)
    m.zoom_to_box(bbox)
    m.buffer_size = 128

    # Render image with default Agg renderer
    im = mapnik.Image(render_size_x, render_size_y)
    mapnik.render(m, im)
    im.save(tile_uri, 'png256')

    surface = cairo.SVGSurface('legend.svg', render_size_x, render_size_y)
    mapnik.render(m, surface)
    surface.finish()
Example #3
0
    def render(self, filename, tile_x, tile_y, zoom):
        """
        Render a single tile to a given filename.
        """
        print 'Rendering %s' % (filename)

        # Calculate pixel positions of bottom-left & top-right
        half_width = self.width / 2
        half_height = self.height / 2
        px0 = (tile_x * self.width, (tile_y + 1) * self.height)
        px1 = ((tile_x + 1) * self.width, tile_y * self.height)

        # Convert tile coords to LatLng
        ll0 = self.tile_projection.fromPixelToLL(px0, zoom)
        ll1 = self.tile_projection.fromPixelToLL(px1, zoom)

        # Convert LatLng to map coords
        c0 = self.map_projection.forward(mapnik2.Coord(ll0[0], ll0[1]))
        c1 = self.map_projection.forward(mapnik2.Coord(ll1[0], ll1[1]))

        # Create bounding box for the render
        bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)

        self.mapnik_map.zoom_to_box(bbox)
        self.mapnik_map.buffer_size = self.buffer_size

        # Render image with default renderer
        image = mapnik2.Image(self.width, self.height)
        mapnik2.render(self.mapnik_map, image)
        image.save(filename, self.filetype)
    def render_tile(self, tile_uri, x, y, z):

        # 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 = self.tileproj.fromPixelToLL(p0, z)
        l1 = self.tileproj.fromPixelToLL(p1, z)

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

        # Bounding box for the tile
        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)
        render_size = 256
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        if (self.m.buffer_size < 128):
            self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik.Image(render_size, render_size)
        mapnik.render(self.m, im)
        im.save(tile_uri, 'png256')
Example #5
0
def test_render_grid():
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(143.10, -38.60, 'Name', 'South East')
    places_ds.add_point(142.48, -38.60, 'Name', 'South West')
    places_ds.add_point(142.48, -38.38, 'Name', 'North West')
    places_ds.add_point(143.10, -38.38, 'Name', 'North East')
    s = mapnik2.Style()
    r = mapnik2.Rule()
    #symb = mapnik2.PointSymbolizer()
    symb = mapnik2.MarkersSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    label = mapnik2.TextSymbolizer(mapnik2.Expression('[Name]'),
                                   'DejaVu Sans Book', 10,
                                   mapnik2.Color('black'))
    label.allow_overlap = True
    label.displacement = (0, -10)
    #r.symbols.append(label)

    s.rules.append(r)
    lyr = mapnik2.Layer('Places')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    m = mapnik2.Map(256, 256)
    m.append_style('places_labels', s)
    m.layers.append(lyr)
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    m.zoom_to_box(mapnik2.Box2d(ul_lonlat, lr_lonlat))
    grid = mapnik2.render_grid(m, 0, key='Name', resolution=4, fields=['Name'])
    eq_(grid, grid_correct)
    eq_(resolve(grid, 0, 0), None)

    # check every pixel of the nw symbol
    expected = {"Name": "North West"}

    # top row
    eq_(resolve(grid, 23, 9), expected)
    eq_(resolve(grid, 23, 10), expected)
    eq_(resolve(grid, 23, 11), expected)

    # core
    eq_(resolve(grid, 24, 8), expected)
    eq_(resolve(grid, 24, 9), expected)
    eq_(resolve(grid, 24, 10), expected)
    eq_(resolve(grid, 24, 11), expected)
    eq_(resolve(grid, 24, 12), expected)
    eq_(resolve(grid, 25, 8), expected)
    eq_(resolve(grid, 25, 9), expected)
    eq_(resolve(grid, 25, 10), expected)
    eq_(resolve(grid, 25, 11), expected)
    eq_(resolve(grid, 25, 12), expected)

    # bottom row
    eq_(resolve(grid, 26, 9), expected)
    eq_(resolve(grid, 26, 10), expected)
    eq_(resolve(grid, 26, 11), expected)
Example #6
0
def test_render_points():
    # Test for effectivenes of ticket #402 (borderline points get lost on reprojection)
    raise Todo("See: http://trac.mapnik2.org/ticket/402")

    if not mapnik2.has_pycairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, 'Name',
                        'Westernmost Point')  # westernmost
    places_ds.add_point(143.10, -38.60, 'Name',
                        'Southernmost Point')  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    from cairo import SVGSurface
    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        import StringIO
        svg_memory_file = StringIO.StringIO()
        surface = SVGSurface(svg_memory_file, m.width, m.height)
        mapnik2.render(m, surface)
        surface.flush()
        surface.finish()
        svg = svg_memory_file.getvalue()
        svg_memory_file.close()
        num_points_present = len(places_ds.all_features())
        num_points_rendered = svg.count('<image ')
        eq_(
            num_points_present, num_points_rendered,
            "Not all points were rendered (%d instead of %d) at projection %s"
            % (num_points_rendered, num_points_present, projdescr))
Example #7
0
def test_wgs84_inverse_forward():
    p = mapnik2.Projection('+init=epsg:4326')

    c = mapnik2.Coord(3.01331418311, 43.3333092669)
    e = mapnik2.Box2d(-122.54345245, 45.12312553, 68.2335581353, 48.231231233)

    # It appears that the y component changes very slightly, is this OK?
    # so we test for 'almost equal float values'
    
    assert_almost_equal(p.inverse(c).y, c.y)
    assert_almost_equal(p.inverse(c).x, c.x)

    assert_almost_equal(p.forward(c).y, c.y)
    assert_almost_equal(p.forward(c).x, c.x)

    assert_almost_equal(p.inverse(e).center().y, e.center().y)
    assert_almost_equal(p.inverse(e).center().x, e.center().x)

    assert_almost_equal(p.forward(e).center().y, e.center().y)
    assert_almost_equal(p.forward(e).center().x, e.center().x)

    assert_almost_equal(c.inverse(p).y, c.y)
    assert_almost_equal(c.inverse(p).x, c.x)

    assert_almost_equal(c.forward(p).y, c.y)
    assert_almost_equal(c.forward(p).x, c.x)

    assert_almost_equal(e.inverse(p).center().y, e.center().y)
    assert_almost_equal(e.inverse(p).center().x, e.center().x)

    assert_almost_equal(e.forward(p).center().y, e.center().y)
    assert_almost_equal(e.forward(p).center().x, e.center().x)
Example #8
0
    def render_location_with_variants(self, variants):
               # target projection
        #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')
        data = []
        for item in range(0,variants):
            if item == 0:
                teta = 0
                zoom = 20
                shift_lat = 0
                shift_lon = 0
            else:
                shift_lat = 0.1*self.size*(random.random()-random.random()) 
                shift_lon = 0.1*self.size*(random.random()-random.random())
                teta = 45 * (random.random()-random.random())
                zoom = random.randint(17,21)

            layer = "complete"
            projec = mapnik.Projection('+proj=aeqd +ellps=WGS84 +lat_0=90 +lon_0='+str(teta))        
            # WGS lat/long source projection of centre
            longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
            
            # make a new Map object for the given mapfile
            m = mapnik.Map(self.width, self.height)
            mapfile = "renderer/map_data/styles/bs_" + layer + ".xml"
            mapnik.load_map(m, mapfile)
            
            # ensure the target map projection is mercator
            m.srs = projec.params()
            
            # transform the centre point into the target coord sys
            centre = mapnik.Coord(self.lon+shift_lon, self.lat+shift_lat)  
            transform = mapnik.ProjTransform(longlat, projec)
            merc_centre = transform.forward(centre)
            
            # 360/(2**zoom) degrees = 256 px
            # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
            # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
            
            dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom)))
            minx = merc_centre.x - dx
            maxx = merc_centre.x + dx
            
            # grow the height bbox, as we only accurately set the width bbox
            m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

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

            # render the map image to a file
            # mapnik.render_to_file(m, output)
            #render the map to an image
            im = mapnik.Image(self.width,self.height)
            mapnik.render(m, im)
            img = im.tostring('png256')
            img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1)
            img =np.asarray(img)
            data.append(img)
        data = np.stack(data)
        return data
    def render_tile(self, tile_uri, x, y, z):

        # 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 = self.tileproj.fromPixelToLL(p0, z)
        l1 = self.tileproj.fromPixelToLL(p1, z)

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

        # Bounding box for the tile
        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)
        render_size = 256
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik.Image(render_size, render_size)
        mapnik.render(self.m, im)
        im.save(tile_uri, 'png256')
        grid_uri = tile_uri.replace('.png', '.grid.json')

        # new mapnik.Grid api, works like mapnik.Image
        # with the exception that you can only render one
        # layer to it with the mapnik.render_layer function

        # create grid as same size as map/image
        grid = mapnik.Grid(render_size, render_size)
        # render a layer to that grid array
        mapnik.render_layer(self.m, grid, layer=0, fields=['POP2005', 'NAME'])
        # then encode the grid array as utf, resample to 1/4 the size, and dump features
        grid_utf = grid.encode('utf', resolution=4, add_features=True)

        # below is the old grid api - will be removed soon, don't use
        #grid_utf = mapnik.render_grid(self.m,0,key='__id__',resolution=4,fields=['POP2005','NAME'])
        # client code uses jsonp, so fake by wrapping in grid() callback
        open(grid_uri, 'wb').write('grid(' + json.dumps(grid_utf) + ')')
Example #10
0
def test_render_points():

    if not mapnik2.has_cairo(): return

    # create and populate point datasource (WGS84 lat-lon coordinates)
    places_ds = mapnik2.PointDatasource()
    places_ds.add_point(142.48, -38.38, 'Name',
                        'Westernmost Point')  # westernmost
    places_ds.add_point(143.10, -38.60, 'Name',
                        'Southernmost Point')  # southernmost
    # create layer/rule/style
    s = mapnik2.Style()
    r = mapnik2.Rule()
    symb = mapnik2.PointSymbolizer()
    symb.allow_overlap = True
    r.symbols.append(symb)
    s.rules.append(r)
    lyr = mapnik2.Layer('Places', '+proj=latlon +datum=WGS84')
    lyr.datasource = places_ds
    lyr.styles.append('places_labels')
    # latlon bounding box corners
    ul_lonlat = mapnik2.Coord(142.30, -38.20)
    lr_lonlat = mapnik2.Coord(143.40, -38.80)
    # render for different projections
    projs = {
        'latlon': '+proj=latlon +datum=WGS84',
        'merc': '+proj=merc +datum=WGS84 +k=1.0 +units=m +over +no_defs',
        'google': '+proj=merc +ellps=sphere +R=6378137 +a=6378137 +units=m',
        'utm': '+proj=utm +zone=54 +datum=WGS84'
    }
    for projdescr in projs.iterkeys():
        m = mapnik2.Map(1000, 500, projs[projdescr])
        m.append_style('places_labels', s)
        m.layers.append(lyr)
        p = mapnik2.Projection(projs[projdescr])
        m.zoom_to_box(p.forward(mapnik2.Box2d(ul_lonlat, lr_lonlat)))
        # Render to SVG so that it can be checked how many points are there with string comparison
        svg_file = '/tmp/%s.svg'
        mapnik2.render_to_file(m, svg_file)
        num_points_present = len(places_ds.all_features())
        svg = open(svg_file, 'r').read()
        num_points_rendered = svg.count('<image ')
        eq_(
            num_points_present, num_points_rendered,
            "Not all points were rendered (%d instead of %d) at projection %s"
            % (num_points_rendered, num_points_present, projdescr))
Example #11
0
    def render_tile(self, tile_uri, x, y, z):
        # Calculate pixel positions of bottom-left & top-right
        p0 = (x * TILES_SIZE, (y + 1) * TILES_SIZE)
        p1 = ((x + 1) * TILES_SIZE, y * TILES_SIZE)

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

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

        # Bounding box for the tile
        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)
        render_size = TILES_SIZE
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        if FORMAT == 'grid':
            grid = mapnik.Grid(render_size, render_size)
            #            mapnik.render_layer(self.m, grid, layer=64, fields=['name'])
            for n, l in enumerate(self.m.layers):
                if l.name != 'admin-012345678':
                    if 'name' in l.datasource.fields():
                        mapnik.render_layer(self.m,
                                            grid,
                                            layer=n,
                                            fields=['name'])
            utfgrid = grid.encode('utf', resolution=4)
            f = open(tile_uri + '.' + FILE_EXTENSION, 'w')
            f.write(json.dumps(utfgrid))
            f.close()
        else:
            # Render image with default Agg renderer
            im = mapnik.Image(render_size, render_size)
            mapnik.render(self.m, im)
            im.save(tile_uri + '.' + FILE_EXTENSION, FORMAT)
Example #12
0
def test_render_grid2():
    """ test old against new"""
    width,height = 256,256
    m = create_grid_map(width,height)
    ul_lonlat = mapnik2.Coord(142.30,-38.20)
    lr_lonlat = mapnik2.Coord(143.40,-38.80)
    m.zoom_to_box(mapnik2.Box2d(ul_lonlat,lr_lonlat))

    # new method
    grid = mapnik2.Grid(m.width,m.height,key='Name')
    mapnik2.render_layer(m,grid,layer=0,fields=['Name'])
    utf1 = grid.encode('utf',resolution=4)
    eq_(utf1,grid_correct_new)

    # old method - to be removed
    utf2 = mapnik2.render_grid(m,0,key='Name',resolution=4,fields=['Name'])
    eq_(utf2,grid_correct)

    # for complex polygons these will not be true
    eq_(len(utf2['grid']),len(utf1['grid']))
    eq_(len(utf2['keys']),len(utf1['keys']))
    eq_(len(utf2['data']),len(utf1['data']))
    
    # check a full view is the same as a full image
    grid_view = grid.view(0,0,width,height)
    # for kicks check at full res too
    utf3 = grid.encode('utf',resolution=1)
    utf4 = grid_view.encode('utf',resolution=1)
    eq_(utf3['grid'],utf4['grid'])
    eq_(utf3['keys'],utf4['keys'])
    eq_(utf3['data'],utf4['data'])
    
    eq_(resolve(utf4,0,0),None)
    
    # resolve some center points in the
    # resampled view
    utf5 = grid_view.encode('utf',resolution=4)
    eq_(resolve(utf5,25,10),{"Name": "North West"})
    eq_(resolve(utf5,25,46),{"Name": "North East"})
    eq_(resolve(utf5,38,10),{"Name": "South West"})
    eq_(resolve(utf5,38,46),{"Name": "South East"})
Example #13
0
    def render_tile(self, tile_uri, x, y, z):
        # Calculate pixel positions of bottom-left & top-right
        #        start=time.time()
        #        p0 = (x * TILESIZE, (y + 1) * TILESIZE)
        #        p1 = ((x + 1) * TILESIZE, y * TILESIZE)
        #
        #        # Convert to LatLong (EPSG:4326)
        #        l0 = self.tileproj.fromPixelToLL(p0, z);
        #        l1 = self.tileproj.fromPixelToLL(p1, z);
        #
        #        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        #        c0 = self.prj.forward(mapnik2.Coord(l0[0],l0[1]))
        #        c1 = self.prj.forward(mapnik2.Coord(l1[0],l1[1]))

        l0y, l0x = num2deg(x, y + 1, z)
        l1y, l1x = num2deg(x + 1, y, z)

        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik2.Coord(l0x, l0y))
        c1 = self.prj.forward(mapnik2.Coord(l1x, l1y))

        # Bounding box for the tile
        if hasattr(mapnik2,
                   'mapnik_version') and mapnik2.mapnik_version() >= 800:
            bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
        else:
            bbox = mapnik2.Envelope(c0.x, c0.y, c1.x, c1.y)
        render_size = TILESIZE
        self.m.resize(render_size, render_size)
        self.m.zoom_to_box(bbox)
        self.m.buffer_size = 128

        # Render image with default Agg renderer
        im = mapnik2.Image(render_size, render_size)
        #        print("%f"%(time.time()-start))
        #        start=time.time()
        mapnik2.render(self.m, im)
        #        print("%f"%(time.time()-start))
        #        start=time.time()
        im.save(tile_uri, 'png256')
Example #14
0
    def generate_map_tile(self, m, filename, z, x, y):
        # Code taken from OSM generate_tiles.py
        proj = GoogleProjection()
        mprj = mapnik.Projection(m.srs)

        p0 = (x * 256, (y + 1) * 256)
        p1 = ((x + 1) * 256, y * 256)
        l0 = proj.fromPixelToLL(p0, z);
        l1 = proj.fromPixelToLL(p1, z);
        c0 = mprj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = mprj.forward(mapnik.Coord(l1[0], l1[1]))

        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.resize(256, 256)
        m.zoom_to_box(bbox)

        im = mapnik.Image(256, 256)
        mapnik.render(m, im)
        im.save(str(filename), "png256")
Example #15
0
File: tile.py Project: skripkar/noc
 def render_tile(self, zoom, x, y):
     t0 = time.time()
     tl = "(zoom=%s x=%s y=%s)" % (zoom, x, y)
     self.log("Rendering tile %s" % tl)
     # Convert tile index to LatLong (EPSG:4326)
     l0 = xy_to_ll(zoom, (x, y + 1))
     l1 = xy_to_ll(zoom, (x + 1, y))
     # Convert to map projection (e.g. mercator co-ords EPSG:900913)
     # and get tile's bounding box
     c0 = self.prj.forward(mapnik2.Coord(l0[0], l0[1]))
     c1 = self.prj.forward(mapnik2.Coord(l1[0], l1[1]))
     bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
     # Render
     self.m.resize(TS, TS)
     self.m.zoom_to_box(bbox)
     self.m.buffer_size = 128
     im = mapnik2.Image(TS, TS)
     mapnik2.render(self.m, im)
     data = im.tostring("png256")
     # Save to database
     tc = TileCache.objects.filter(map=self.map.id, zoom=zoom, x=x,
                                   y=y).first()
     if tc:
         tc.ready = True
         tc.last_updated = datetime.datetime.now()
         tc.data = data
         tc.save()
     else:
         TileCache(map=self.map.id,
                   zoom=zoom,
                   x=x,
                   y=y,
                   ready=True,
                   last_updated=datetime.datetime.now(),
                   data=data).save()
     self.log("Tile %s completed in %dms" % (tl, (time.time() - t0) * 1000))
Example #16
0
    def rpc_renderCoordOld(self, lat, lon, zoom):
        """
        Renders a map for the given coordinates.
        """
        Map = None

        LandmassShapefile = 'cape/Interface/ne_110m_admin_0_countries.shp'

        im = mapnik.Image(self.mapsize[0], self.mapsize[1])
        m = mapnik.Map(self.mapsize[0], self.mapsize[1])

        m.background = mapnik.Color(self.backgroundColor)
        s = mapnik.Style()
        r = mapnik.Rule()
        polygon_symbolizer = mapnik.PolygonSymbolizer(
            mapnik.Color(self.foregroundColor))
        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=LandmassShapefile)
        layer = mapnik.Layer('world')
        layer.datasource = ds
        layer.styles.append('My Style')
        m.layers.append(layer)

        center = mapnik.Coord(lat, lon)
        transform = mapnik.ProjTransform(self.longlat, self.merc)
        merc_center = transform.forward(center)

        dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom)))
        minx = merc_center.x - dx
        maxx = merc_center.x + dx

        m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx,
                                 merc_center.y + 1)
        m.zoom_to_box(merc_bbox)
        mapnik.render(m, im)
        Map = im.tostring('png')

        return (True, Map)
Example #17
0
    def render_location_with_zoom(self, zoom):
        # target projection
        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')

        # WGS lat/long source projection of centrel 
        longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        
        # make a new Map object for the given mapfile
        m = mapnik.Map(self.width, self.height)
        mapnik.load_map(m, self.mapfile)
        
        # ensure the target map projection is mercator
        m.srs = merc.params()
        
        # transform the centre point into the target coord sys
        centre = mapnik.Coord(self.lon, self.lat)  
        transform = mapnik.ProjTransform(longlat, merc)
        merc_centre = transform.forward(centre)
        
        # 360/(2**zoom) degrees = 256 px
        # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
        # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
        dx = ((20037508.34*2*(self.width/2)))/(256*(2 ** (zoom)))
        minx = merc_centre.x - dx
        maxx = merc_centre.x + dx
        
        # grow the height bbox, as we only accurately set the width bbox
        m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

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

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


        #render the map to an image
        im = mapnik.Image(self.width,self.height)
        mapnik.render(m, im)
        img = im.tostring('png256')
        img = cv2.imdecode(np.fromstring(img, dtype=np.uint8), 1)
        img =np.asarray(img)
        window_name = "Location"
        cv2.imshow(window_name, img)
        cv2.waitKey(1)
Example #18
0
    def rendertiles(self, cpoint, data, item, label, lat, layer, lon,
                    num_items, projec, zoom):
        # target projection
        #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')
        merc = projec
        # WGS lat/long source projection of centre
        longlat = mapnik.Projection(
            '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')

        # make a new Map object for the given mapfile
        m = mapnik.Map(self.width, self.height)
        mapfile = "/map_data/styles/bs_" + layer + ".xml"
        mapnik.load_map(m, mapfile)

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

        # transform the centre point into the target coord sys
        centre = mapnik.Coord(cpoint[0], cpoint[1])
        transform = mapnik.ProjTransform(longlat, merc)
        merc_centre = transform.forward(centre)

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

        dx = ((20037508.34 * 2 * (self.width / 2))) / (256 * (2**(zoom)))
        minx = merc_centre.x - dx
        maxx = merc_centre.x + dx

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

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

        # render the map image to a file
        # mapnik.render_to_file(m, output)
        #render the map to an image
        im = mapnik.Image(self.width, self.height)
        mapnik.render(m, im)
        img = im.tostring('png256')
        data[(item, layer)] = img
Example #19
0
    def rpc_renderCoord(self, lat, lon, zoom):
        im = mapnik.Image(self.mapsize[0], self.mapsize[1])

        center = mapnik.Coord(lat, lon)
        transform = mapnik.ProjTransform(self.longlat, self.merc)
        merc_center = transform.forward(center)

        dx = (20037508.34 * 2 * (self.mapsize[0] / 2)) / (256 * (2**(zoom)))
        minx = merc_center.x - dx
        maxx = merc_center.x + dx

        self.rendermap.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT

        merc_bbox = mapnik.Box2d(minx, merc_center.y - 1, maxx,
                                 merc_center.y + 1)
        self.rendermap.zoom_to_box(merc_bbox)
        mapnik.render(self.rendermap, im)
        Map = im.tostring('png')

        return (True, Map)
Example #20
0
    def render_map(self,
                   lat,
                   lon,
                   angle=None,
                   angle_offset=0,
                   zoom=None,
                   overwrite=False,
                   img_width=None,
                   img_height=None,
                   zoom_to_layer=False,
                   layer_padding=10):
        """Renders map with help of mapnik

        If maps_cache is used it is first checked if image already exists in
        cache. Image name is created with self._make_name which creates name
        from lat_lon rounded to 5 decimals and width height if they are
        provided. If image exists and overwrite is False image is returned as
        ImageClip. If overwrite is True image is deleted and image is rendered
        and also returned as ImageClip.

        Parameters
        ---------
        lat : float
            Latitude in WGS84 - center point of a map (around 46 in Europe)
        lon : float
            Longitude in WGS84 - center point of a map (around 15 in Europe)
        angle : float
            If we want to rotate map. It should show where up is. AKA bearing
        angle_offset : int
            How much offset is between camera and forward direction so that
            map is correctly oriented
        zoom : float
            Mapnik zoom from 0-19 (higher number higher zoom) If we want
            different zoom then what was set in constructor
        overwrite : bool
            If we are using map cache do we want to overwrite existing images
        img_width : int
            If we want different size of map then what was set in constructor
        img_height : int
            If we want different size of map then what was set in constructor
        zoom_to_layer: bool
            If true it shows whole gpx layer in a map. lat, lon, zoom, angle are
            ignored
        layer_padding: int
            How much padding to add between edges of layer and image

        Returns
        -------
        moviepy.video.VideoClip.ImageClip, tuple
            Rendered image as clip, and tuple with x and y coordinate of center
            in pixel units. (Used to add point on current location)


        """
        map_uri = None
        width = self.map_width if img_width is None else img_width
        height = self.map_height if img_height is None else img_height
        if zoom is None:
            if self.map_zoom is None:
                raise Exception("One of map_zoom or zoom needs to be set!")
            zoom = self.map_zoom

        if angle is None:
            # spherical mercator (most common target map projection of osm data imported with osm2pgsql)
            merc = self.mercator_projection
        else:
            #Map rotation https://gis.stackexchange.com/questions/183175/rotating-90-using-two-point-equidistant-projection-with-proj4
            merc = mapnik.Projection(
                '+proj=aeqd +ellps=sphere +lat_0=90 +lon_0=-' +
                str(angle + angle_offset))
        self._lazy_init_map()
        # ensure the target map projection is mercator
        self.m.srs = merc.params()

        centre = mapnik.Coord(lon, lat)
        transform = mapnik.ProjTransform(MapnikRenderer.longlat, merc)
        merc_centre = transform.forward(centre)

        if img_width is not None and img_height is not None:
            self.m.resize(width, height)

        if not zoom_to_layer:
            # 360/(2**zoom) degrees = 256 px
            # so in merc 1px = (20037508.34*2) / (256 * 2**zoom)
            # hence to find the bounds of our rectangle in projected coordinates + and - half the image width worth of projected coord units
            dx = ((20037508.34 * 2 * (width / 2))) / (256 * (2**(zoom)))
            minx = merc_centre.x - dx
            maxx = merc_centre.x + dx
            # grow the height bbox, as we only accurately set the width bbox
            self.m.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_BBOX_HEIGHT
            bounds = mapnik.Box2d(
                minx, merc_centre.y - 10, maxx, merc_centre.y + 10
            )  # the y bounds will be fixed by mapnik due to ADJUST_BBOX_HEIGHT
        else:
            names = ["gpx"]
            ppmm = 90.7 / 25.4
            self.m.aspect_fix_mode = mapnik.aspect_fix_mode.GROW_BBOX
            #Next for loop is from Zverik/Nik4 app
            #Calculate extent of given layers and bbox
            for layer in (l for l in self.m.layers if l.name in names):
                # it may as well be a GPX layer in WGS84
                proj = mapnik.Projection(layer.srs)
                bbox = layer.envelope() \
                        .inverse(proj).forward(self.mercator_projection)
                tscale = min((bbox.maxx - bbox.minx) / max(width, 0.01),
                             (bbox.maxy - bbox.miny) / max(height, 0.01))
                bbox.pad(layer_padding * ppmm * tscale)
                bounds = bbox

# Note: aspect_fix_mode is only available in Mapnik >= 0.6.0
        self.m.zoom_to_box(bounds)

        center_pixel_coord = self.m.view_transform().forward(merc_centre)
        #print ("img_width: {} map_width:{} width:{}".format(img_width, self.map_width, width))
        if self.maps_cache is not None:
            zoom_name = zoom if self.zoom_changeable else None
            fn = self._make_name(lat, lon, width, height, zoom_name,
                                 zoom_to_layer)
            #print ("Rendering " + fn)
            map_uri = os.path.join(self.maps_cache, "{}.png".format(fn))
            #If we don't want to overwrite and file already exists skip map rendering
            if not overwrite and os.path.isfile(map_uri):
                return ImageClip(map_uri), (center_pixel_coord.x,
                                            center_pixel_coord.y)


#If we want to overwrite and file exists we remove file
            if overwrite and os.path.isfile(map_uri):
                os.remove(map_uri)

        #start = time.perf_counter()
        if self.maps_cache is not None:
            mapnik.render_to_file(self.m, map_uri)
            map_data = map_uri
        else:
            #Renders map to image in memory saves it to buffer and reads in numpy
            im = mapnik.Image(self.m.width, self.m.height)
            mapnik.render(self.m, im)
            #im.save("/tmp/tmp.png", 'png256')
            #Saving image to bytes buffer needs to be nonpalletted image otherwise it needs
            #to be converted to RGB when reading in numpy anyways
            string_image = im.tostring('png32')
            buffer = BytesIO(string_image)
            #with open("/tmp/tmp1.png", "wb") as o:
            #o.write(buffer.getvalue())
            pil_image = ImagePIL.open(buffer)
            #print (pil_image.format, pil_image.mode, pil_image.size,
            #pil_image.palette)
            map_data = np.asarray(pil_image)
            #map_data = "/tmp/tmp.png"
        if img_width is not None and img_height is not None:
            self.m.resize(self.map_width, self.map_height)

        #print ("render took %r s" % (time.perf_counter()-start,))
        return ImageClip(map_data), (center_pixel_coord.x,
                                     center_pixel_coord.y)
Example #21
0
def render_map(mapfile):
    #A4
    #filename = 'export_A4'
    #render_size_x = 842
    #render_size_y = 595
    #A3
    #filename = 'export_A3'
    #render_size_x = 1191
    #render_size_y = 842
    #A2
    #filename = 'export_A2'
    #render_size_x = 1684
    #render_size_y = 1191
    #A1
    #filename = 'export_A1'
    #render_size_x = 2384
    #render_size_y = 1684
    #A0
    filename = 'export_A0'
    render_size_x = 3370
    render_size_y = 2384
    #A-1
    #filename = 'export_A-1'
    #render_size_x = 4768
    #render_size_y = 3370
    #A-2
    #filename = 'export_A-2'
    #render_size_x = 6740
    #render_size_y = 4768

    m = mapnik.Map(render_size_x, render_size_y)
    # 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(20)

    # Convert to map projection (e.g. mercator co-ords EPSG:900913)
    c0 = prj.forward(mapnik.Coord(14.33, 50.05))
    c1 = prj.forward(mapnik.Coord(14.53, 50.14))

    #filename = filename + '_BIG'
    #c0 = prj.forward(mapnik.Coord(14.25,49.95))
    #c1 = prj.forward(mapnik.Coord(14.68,50.16))

    # Bounding box for the tile
    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.resize(render_size_x, render_size_y)
    m.zoom_to_box(bbox)
    m.buffer_size = 128

    # Render image with default Agg renderer
    #im = mapnik.Image(render_size_x, render_size_y)
    #mapnik.render(m, im)
    #im.save('export.png', 'png256')

    #surface = cairo.PDFSurface(filename + '.pdf', render_size_x, render_size_y)
    #mapnik.render(m, surface)

    surface = cairo.PSSurface(filename + '.ps', render_size_x, render_size_y)

    surface.dsc_comment("%%Title: Cyklisticka mapa prahy")
    surface.dsc_comment("%%Copyright: CC-BY-SA")
    mapnik.render(m, surface)

    #surface = cairo.SVGSurface(filename + '.svg', render_size_x, render_size_y)
    #mapnik.render(m, surface)
    surface.finish()
Example #22
0
def metadata_image(bboxes, mapfile):
    """Create a metadata image"""

    from json import dumps as tojson
    import mapnik2 as mapnik

    features = []

    for bbox in bboxes:
        minx, miny, maxx, maxy = bbox

        # create the bounding box as a json string
        width, height = (maxx - minx, maxy - miny)
        min_dim = 0.0125                        # minimum dimension for display as a rectangle (in degrees)
        if width < min_dim or height < min_dim:   # it should be a point
            feature = { "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": [minx, miny]
                            },
                        "properties": {
                            "type": "point"
                            }
                        }
            width, height = (9, 9)
        else:
            feature = { "type": "Feature",
                        "geometry": {
                            "type": "Polygon",
                            "coordinates": [[[minx, miny], [maxx, miny], [maxx, maxy], [minx, maxy], [minx, miny]]]
                            },
                        "properties": {
                            "type": "bbox"
                            }
                        }
        features.append(feature)

    json = tojson({
            "type": "FeatureCollection",
            "features": features
            })

    # instantiate the map
    m = mapnik.Map(250, 250)
    mapnik.load_map_from_string(m, mapfile)

    # set the datasource for the last layer to show the bounding box
    datasource = mapnik.Ogr(file=json, layer='OGRGeoJSON')
    m.layers[-1].datasource = datasource

    # create an image of the area of interest with a border
    border = 80.0                       # percentage border
    dx = width * (border / 100)
    minx2 = minx - dx; maxx2 = maxx + dx
    dy = height * (border / 100)
    miny2 = miny - dy; maxy2 = maxy + dy

    # don't create a border larger than the globe's extent
    if minx2 < -180.0 or maxx2 > 180.0 or miny2 < -90.0 or maxy2 > 90.0:
        minx2 = minx; maxx2 = maxx; miny2 = miny; maxy2 = maxy
    
    bbox = mapnik.Envelope(mapnik.Coord(minx2, miny2), mapnik.Coord(maxx2, maxy2))
    m.zoom_to_box(bbox)
    image = mapnik.Image(m.width, m.height)
    mapnik.render(m, image)

    return image
Example #23
0
    map_uri = "image.png"

    #---------------------------------------------------
    #  Change this to the bounding box you want
    #
    #ll = (10.95,63.85, 11.05, 63.9)
    #ll = (10,63,11,64)
    ll = (6.8, 46.8, 7.2, 47.2)
    #ll= (0,10,0,10)
    #---------------------------------------------------

    z = 10
    imgx = 200 * z
    imgy = 200 * z

    m = mapnik2.Map(imgx, imgy)
    mapnik2.load_map(m, mapfile)
    prj = mapnik2.Projection("+init=epsg:3857 +over")
    #prj = mapnik2.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(mapnik2.Coord(ll[0], ll[1]))
    c1 = prj.forward(mapnik2.Coord(ll[2], ll[3]))
    bbox = mapnik2.Box2d(c0.x, c0.y, c1.x, c1.y)
    #bbox=mapnik2.Box2d(-626172.1357121642,0,0,626172.1357121639)
    print c0, c1
    print bbox
    m.zoom_to_box(bbox)
    im = mapnik2.Image(imgx, imgy)
    mapnik2.render(m, im)
    view = im.view(0, 0, imgx, imgy)  # x,y,width,height
    view.save(map_uri, 'png256')
Example #24
0
        elif o in ("-w", "--width"):
            width = int(a)
        elif o in ("-h", "--height"):
            height = int(a)
        elif o in ("-o", "--output"):
            output = a

    # make a new Map object for the given mapfile
    m = mapnik.Map(width, height)
    mapnik.load_map(m, mapfile)

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

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

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

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

    bounds = mapnik.Box2d(
        minx, merc_centre.y - 10, maxx, merc_centre.y +
Example #25
0
    def render_metatile(self, metatile):
        z = metatile.z
        x = metatile.x
        y = metatile.y

        # TODO: move all this somewhere else
        # Calculate pixel positions of bottom-left & top-right
        p0 = (x * self.tile_size, (y + self.metatile_size) * self.tile_size)
        p1 = ((x + self.metatile_size) * self.tile_size, y * self.tile_size)

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

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

        # Bounding box for the tile
        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)

        self.m.resize(self.image_size, self.image_size)
        self.m.zoom_to_box(bbox)
        if self.m.buffer_size < 128:
            self.m.buffer_size = 128

        # we must decide wether to render the subtiles/children of this tile
        render_children = {child: False for child in metatile.children()}

        if not self.opts.dry_run:
            # Render image with default Agg renderer
            start = time.perf_counter()
            im = mapnik.Image(self.image_size, self.image_size)

            try:
                mapnik.render(self.m, im)
            except RuntimeError as e:
                exception("%r: %s", metatile, e)
            else:
                mid = time.perf_counter()

                # save the image, splitting it in the right amount of tiles
                for tile in metatile.tiles:
                    i, j = tile.meta_index

                    # TODO: Tile.meta_pixel_coords
                    img = im.view(i * self.tile_size, j * self.tile_size,
                                  self.tile_size, self.tile_size)
                    tile.data = img.tostring('png256')
                    # TODO: move to Tile
                    is_empty = map_utils.is_empty(tile.data)

                    if not is_empty or self.opts.empty == 'write':
                        self.backend.store(tile)

                        # at least something to render. note that if we're
                        # rendering only one tile (either metatile_size == 1
                        # or z == 0), i, j can only be == 0. this matches
                        # the situation further down
                        render_children[metatile.child(tile)] = True
                    else:
                        if self.opts.empty == 'skip':
                            # empty tile, skip
                            debug("%r: empty" % tile)
                            continue
                        # TODO: else?

                    self.backend.commit()

                end = time.perf_counter()
                info("%r: %f, %f" % (metatile, mid - start, end - mid))

        else:
            # simulate some work
            time.sleep(randint(0, 30) / 10)
            for child in metatile.children():
                if random() <= 0.75 or 2**metatile.z < self.opts.metatile_size:
                    render_children[child] = True

        return render_children
    def render_metatile(
            self, metatile: map_utils.MetaTile) -> Dict[map_utils.Tile, bool]:
        # get LatLong (EPSG:4326)
        l0 = metatile.coords[0]
        l1 = metatile.coords[1]

        # this is the only time where we convert manually into WebMerc
        # Convert to map projection (e.g. mercator co-ords EPSG:900913)
        c0 = self.prj.forward(mapnik.Coord(l0[0], l0[1]))
        c1 = self.prj.forward(mapnik.Coord(l1[0], l1[1]))

        # Bounding box for the tile
        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)

        image_size = self.opts.tile_size * min(self.metatile_size, 2**
                                               metatile.z)
        self.m.resize(image_size, image_size)
        self.m.zoom_to_box(bbox)
        if self.m.buffer_size < 128:
            self.m.buffer_size = 128

        bail_out = True

        start = time.perf_counter()
        if not self.opts.dry_run:
            im = mapnik.Image(image_size, image_size)
            # Render image with default Agg renderer
            debug('[%s] rende...', self.name)
            # TODO: handle exception, send back into queue
            mapnik.render(self.m, im)
            debug('[%s] ...ring!', self.name)
            mid = time.perf_counter()

            # TODO: all this is on a single tile, not a metatile

            # converting to png256 is the fastest I have found so far:
            # python3.6 -m timeit -s 'import mapnik; im = mapnik.Image.fromstring(open("Attic/tmp/369.png", "br").read())' 'data = im.tostring("png256")'
            # 100 loops, best of 3: 7.72 msec per loop
            # tostring() looks nice, but I can't rebuild a mapnik.Image from it :(
            # python3.6 -m timeit -s 'import mapnik; im = mapnik.Image.fromstring(open("Attic/tmp/369.png", "br").read())' 'data = im.tostring()'
            # 100000 loops, best of 3: 13.8 usec per loop
            # python3.6 -m timeit -s 'import mapnik, bz2; im = mapnik.Image.fromstring(open("Attic/tmp/369.png", "br").read())' 'c = bz2.BZ2Compressor(); c.compress(im.tostring()); data = c.flush()'
            # 10 loops, best of 3: 20.3 msec per loop
            # python3.6 -m timeit -s 'import mapnik, gzip; im = mapnik.Image.fromstring(open("Attic/tmp/369.png", "br").read())' 'data = gzip.compress(im.tostring())'
            # 10 loops, best of 3: 27.7 msec per loop
            # python3.6 -s -m timeit -s 'import mapnik, lzma; im = mapnik.Image.fromstring(open("Attic/tmp/369.png", "br").read())' "c = lzma.LZMACompressor(); c.compress(im.tostring()); data = c.flush()"
            # 10 loops, best of 3: 92 msec per loop

            # TODO:
            # but bz2 compresses the best, 52714 png vs 49876 bzip vs 70828 gzip vs 53032 lzma

            if not self.opts.store_thread:
                # metatile will go in a non-marshaling queue, no need tostring() it
                metatile.im = im
            else:
                metatile.im = im.tostring('png256')

            end = time.perf_counter()
        else:
            debug('[%s] thumbtumbling', self.name)
            time.sleep(randint(0, 30) / 10)
            mid = time.perf_counter()
            end = time.perf_counter()

        metatile.render_time = mid - start
        metatile.serializing_time = end - mid
        bail_out = False

        debug("[%s] putting %r", self.name, metatile)
        self.output.put(metatile)
        debug("[%s] put! (%d)", self.name, self.output.qsize())

        if not self.opts.store_thread and self.output.qsize() > 0:
            # NOTE: mypy complains here that Item "Process" of "Union[Process, StormBringer]" has no attribute "single_step"
            # the solutions are ugly, so I'm leaving it as that
            self.store_thread.single_step()

        return bail_out
Example #27
0
 def latlng_to_map(self, lat, lng):
     """Transforms given longlat Box2d or Coord to map projection."""
     coord = mapnik2.Coord(lng, lat)
     merc_coord = self.lnglat_to_merc(coord)
     return self.merc_to_map(merc_coord)
Example #28
0
def test_coord_multiplication():
    c = mapnik2.Coord(100, 100)
    c *= 2

    eq_(c.x, 200)
    eq_(c.y, 200)
Example #29
0
def test_coord_init():
    c = mapnik2.Coord(100, 100)

    eq_(c.x, 100)
    eq_(c.y, 100)
Example #30
0
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#

import mapnik2

mapfile = 'tutorial2.xml'
map_output = '~/geodata/raster/world/hello_world_using_xml_config.png'
map_output = 'hello_world_using_xml_config.png'

# Instantiate a map object with given width, height and spatial reference system
#m = mapnik.Map(600,300,"+proj=latlong +datum=WGS84")
m = mapnik2.Map(600, 300)

mapnik2.load_map(m, mapfile)
bbox = mapnik2.Envelope(mapnik2.Coord(-180.0, -90.0),
                        mapnik2.Coord(180.0, 90.0))
m.zoom_to_box(bbox)

# Write the data to a png image called world.png in the base directory of your user
mapnik2.render_to_file(m, map_output)

# Exit the python interpreter
exit()