Exemple #1
0
def test_map_init():
    m = mapnik2.Map(256, 256)

    eq_(m.width, 256)
    eq_(m.height, 256)
    eq_(m.srs, '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    eq_(m.base, '')

    m = mapnik2.Map(256, 256, '+proj=latlong')
    eq_(m.srs, '+proj=latlong')
Exemple #2
0
def test_map_pickle():
    # Fails due to scale() not matching, possibly other things
    raise(Todo("Map does not support pickling yet (Tickets #345)."))

    m = mapnik2.Map(256, 256)

    eq_(pickle.loads(pickle.dumps(m)), m)

    m = mapnik2.Map(256, 256, '+proj=latlong')

    eq_(pickle.loads(pickle.dumps(m)), m)
Exemple #3
0
def get_paired_images(w, h, mapfile):
    tmp_map = 'tmp_map.xml'
    m = mapnik2.Map(w, h)
    mapnik2.load_map(m, mapfile)
    i = mapnik2.Image(w, h)
    m.zoom_all()
    mapnik2.render(m, i)
    mapnik2.save_map(m, tmp_map)
    m2 = mapnik2.Map(w, h)
    mapnik2.load_map(m2, tmp_map)
    i2 = mapnik2.Image(w, h)
    m2.zoom_all()
    mapnik2.render(m2, i2)
    os.remove(tmp_map)
    return i, i2
    def loop(self, nb):
        self.m = mapnik.Map(TILES_SIZE, TILES_SIZE)
        # Load style XML
        mapnik.load_map(self.m, self.mapfile, True)
        # Obtain <Map> projection
        self.prj = mapnik.Projection(self.m.srs)
        # Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
        self.tileproj = GoogleProjection(self.maxZoom + 1)

        while True:
            #Fetch a tile from the queue and render it
            r = self.q.get()
            if (r == None):
                self.q.task_done()
                break
            else:
                (name, tile_uri, x, y, z) = r

            exists = ""
            if os.path.isfile(tile_uri + '.' + FILE_EXTENSION):
                exists = "exists"
            else:
                self.render_tile(tile_uri, x, y, z)

            self.printLock.acquire()
            print name, ":", z, x, y, exists
            self.printLock.release()
            self.q.task_done()
Exemple #5
0
def serialize(xml, options):
    try:
        import mapnik2 as mapnik
    except:
        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'
                ))
Exemple #6
0
 def render_location(self):
     # spherical mercator (most common target map projection of osm data imported with osm2pgsql)
     merc = mapnik.Projection('+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs +over')
     longlat = mapnik.Projection('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
     mapfile = "renderer/map_data/styles/bs_complete.xml"
     bounds = (self.lon-self.size, self.lat-self.size, self.lon+self.size,self.lat+self.size)
     z = 1
     imgx = 224 * z
     imgy = 224 * z
     m = mapnik.Map(imgx,imgy)
     mapnik.load_map(m,mapfile)
     m.srs = merc.params()
     if hasattr(mapnik,'Box2d'):
         bbox = mapnik.Box2d(*bounds)
     else:
         bbox = mapnik.Envelope(*bounds)
     transform = mapnik.ProjTransform(longlat,merc)
     merc_bbox = transform.forward(bbox)
     m.zoom_to_box(merc_bbox)
     #render the map to an image
     im = mapnik.Image(imgx,imgy)
     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(0)
Exemple #7
0
def test_hit_grid():
    import os
    from itertools import groupby

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

    m = mapnik2.Map(256, 256)
    mapnik2.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml')
    m.zoom_all()
    join_field = 'NAME'
    fg = []  # feature grid
    for y in range(0, 256, 4):
        for x in range(0, 256, 4):
            featureset = m.query_map_point(0, x, y)
            added = False
            for feature in featureset.features:
                fg.append(feature[join_field])
                added = True
            if not added:
                fg.append('')
    hit_list = '|'.join(rle_encode(fg))
    eq_(hit_list[:16], '730:|2:Greenland')
    eq_(hit_list[-12:], '1:Chile|812:')
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()
Exemple #9
0
    def compare_map(in_map):

        mapnik2.load_map(map, in_map)

        (handle, test_map) = tempfile.mkstemp(suffix='.xml',
                                              prefix='mapnik-temp-map1-')
        os.close(handle)

        (handle, test_map2) = tempfile.mkstemp(suffix='.xml',
                                               prefix='mapnik-temp-map2-')
        os.close(handle)

        if os.path.exists(test_map):
            os.remove(test_map)

        mapnik2.save_map(map, test_map)
        new_map = mapnik2.Map(256, 256)

        mapnik2.load_map(new_map, test_map)
        open(test_map2, 'w').write(mapnik2.save_map_to_string(new_map))

        diff = ' diff %s %s' % (os.path.abspath(test_map),
                                os.path.abspath(test_map2))
        try:
            eq_(open(test_map).read(), open(test_map2).read())
        except AssertionError, e:
            raise AssertionError(
                'serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s'
                % (in_map, diff))
Exemple #10
0
def renderToPdf(envLL, filename, sizex, sizey):
    """Renders the specified Box2d and zoom level as a PDF"""
    basefilename = os.path.splitext(filename)[0]
    mergedpdf = None
    for mapname in MAPNIK_LAYERS:
        print 'Rendering', mapname
        # Render layer PDF.
        localfilename = basefilename + '_' + mapname + '.pdf'
        file = open(localfilename, 'wb')
        surface = cairo.PDFSurface(file.name, sizex, sizey)
        envMerc = LLToMerc(envLL)
        map = mapnik.Map(sizex, sizey)
        mapnik.load_map(map, mapname + ".xml")
        map.zoom_to_box(envMerc)
        mapnik.render(map, surface)
        surface.finish()
        file.close()
        # Merge with master.
        if not mergedpdf:
            mergedpdf = PdfFileWriter()
            localpdf = PdfFileReader(open(localfilename, "rb"))
            page = localpdf.getPage(0)
            mergedpdf.addPage(page)
        else:
            localpdf = PdfFileReader(open(localfilename, "rb"))
            page.mergePage(localpdf.getPage(0))
    output = open(filename, 'wb')
    mergedpdf.write(output)
    output.close()
Exemple #11
0
    def loop(self):

        self.m = mapnik.Map(128, 128)
        # Load style XML
        #mapnik.load_map(self.m, self.mapfile, True)
        # Obtain <Map> projection
        self.prj = mapnik.Projection(self.m.srs)
        # Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
        #self.tileproj = GoogleProjection(self.maxZoom+1)

        while True:
            #Fetch a tile from the queue and render it
            r = self.q.get()
            if (r == None):
                self.q.task_done()
                break
            else:
                (name, bounds, data, item, label, lat, layer, lon, num_items,
                 projec) = r

            self.rendertiles(bounds, data, item, label, lat, layer, lon,
                             num_items, projec)
            self.printLock.acquire()
            self.printLock.release()
            self.q.task_done()
Exemple #12
0
    def run(self):
        self.mapnik_map = mapnik2.Map(self.width, self.height)
        mapnik2.load_map(self.mapnik_map, self.config, True)

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

        while True:
            tile_parameters = None

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

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

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

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

                    continue

            self.render(*tile_parameters)
            tile_queue.task_done()
Exemple #13
0
    def renderArea(self, width, height, srs, xmin, ymin, xmax, ymax, zoom):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)

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

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

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

        self.mapnik.width = width
        self.mapnik.height = height
        self.mapnik.zoom_to_box(mapnik.Envelope(xmin, ymin, xmax, ymax))

        img = mapnik.Image(width, height)
        mapnik.render(self.mapnik, img)

        img = Image.fromstring('RGBA', (width, height), img.tostring())

        return img
Exemple #14
0
def create_grid_map(width,height):
    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(width,height)
    m.append_style('places_labels',s)
    m.layers.append(lyr)
    return m
    def loop(self):

        self.m = mapnik.Map(256, 256)
        # Load style XML
        mapnik.load_map(self.m, self.mapfile, True)
        # Obtain <Map> projection
        self.prj = mapnik.Projection(self.m.srs)
        # Projects between tile pixel co-ordinates and LatLong (EPSG:4326)
        self.tileproj = spherical_mercator.SphericalMercator(self.maxZoom + 1)

        while True:
            # Fetch a tile from the queue and render it
            r = self.q.get()
            if (r == None):
                self.q.task_done()
                break
            else:
                (name, tile_uri, x, y, z) = r

            exists = ""
            if os.path.isfile(tile_uri):
                exists = "exists"
            else:
                self.render_tile(tile_uri, x, y, z)
            bytes = os.stat(tile_uri)[6]
            empty = ''
            if bytes == 103:
                empty = " Empty Tile "
            self.printLock.acquire()
            print(name, ":", z, x, y, exists, empty)
            self.printLock.release()
            self.q.task_done()
Exemple #16
0
def test_map_init_from_string():
    map_string = '''<Map background-color="steelblue" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">
     <Style name="My Style">
      <Rule>
       <PolygonSymbolizer>
        <CssParameter name="fill">#f2eff9</CssParameter>
       </PolygonSymbolizer>
       <LineSymbolizer>
        <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter>
        <CssParameter name="stroke-width">0.1</CssParameter>
       </LineSymbolizer>
      </Rule>
     </Style>
     <Layer name="boundaries">
      <StyleName>My Style</StyleName>
       <Datasource>
        <Parameter name="type">shape</Parameter>
        <Parameter name="file">../../demo/data/boundaries</Parameter>
       </Datasource>
      </Layer>
    </Map>'''

    m = mapnik2.Map(600, 300)
    
    mapnik2.load_map_from_string(m, map_string)
    mapnik2.load_map_from_string(m, map_string, False, "")
    mapnik2.load_map_from_string(m, map_string, True, "")
    raise(Todo("Need to write more map property tests in 'object_test.py'..."))
Exemple #17
0
    def renderTile(self, width, height, srs, coord):
        """
        """
        if self.mapnik is None:
            self.mapnik = mapnik.Map(0, 0)
            mapnik.load_map(self.mapnik, str(self.mapfile))

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

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

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

        if self.wrapper is None:
            return SaveableResponse(json.dumps(grid_utf))
        else:
            return SaveableResponse(self.wrapper + '(' + json.dumps(grid_utf) +
                                    ')')
Exemple #18
0
    def rendertiles(self, bounds, data, item, label, lat, layer, lon,
                    num_items, projec):
        z = 1
        imgx = 128 * z
        imgy = 128 * z

        mapfile = "/map_data/styles/bs_" + layer + ".xml"

        m = mapnik.Map(imgx, imgy)
        mapnik.load_map(m, mapfile)
        # ensure the target map projection is mercator
        m.srs = projec.params()

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

        transform = mapnik.ProjTransform(longlat, projec)
        merc_bbox = transform.forward(bbox)

        m.zoom_to_box(merc_bbox)

        # render the map to an image
        im = mapnik.Image(imgx, imgy)
        mapnik.render(m, im)
        img = im.tostring('png256')
        data[(item, layer)] = img
Exemple #19
0
def test_dataraster_query_point():
    srs = '+init=epsg:32630'
    lyr = mapnik2.Layer('dataraster')
    lyr.datasource = mapnik2.Gdal(
        file='../data/raster/dataraster.tif',
        band=1,
    )
    lyr.srs = srs
    _map = mapnik2.Map(256, 256, srs)
    _map.layers.append(lyr)

    # point inside raster extent with valid data
    x, y = 427417, 4477517
    features = _map.query_point(0, x, y).features
    assert len(features) == 1
    feat = features[0]
    center = feat.envelope().center()
    assert center.x == x and center.y == y, center
    value = feat['value']
    assert value == 21.0, value

    # point outside raster extent
    features = _map.query_point(0, -427417, 4477517).features
    assert len(features) == 0

    # point inside raster extent with nodata
    features = _map.query_point(0, 126850, 4596050).features
    assert len(features) == 0
Exemple #20
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
Exemple #21
0
 def run(self):
     self.log("Loading map XML")
     self.m = mapnik2.Map(TS, TS)
     try:
         mapnik2.load_map_from_string(self.m, self.xml)
     except RuntimeError, why:
         logging.error("Cannot load map: %s" % why)
         os._exit(1)
def test_load_save_load_map():
    map = mapnik2.Map(256, 256)
    in_map = "../data/good_maps/glyph_symbolizer.xml"
    mapnik2.load_map(map, in_map)
    style = map.find_style('arrows')
    sym = style.rules[0].symbols[0]
    assert isinstance(sym, mapnik2.GlyphSymbolizer)
    assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH

    out_map = mapnik2.save_map_to_string(map).decode('utf8')
    map = mapnik2.Map(256, 256)
    mapnik2.load_map_from_string(map, out_map.encode('utf8'))
    assert 'GlyphSymbolizer' in out_map
    assert 'RasterColorizer' in out_map
    # make sure non-ascii characters are well supported since most interesting
    # glyphs for symbology are usually in that range
    assert u'í' in out_map, out_map
Exemple #23
0
 def init_zoomlevel(self, z):
     self.currentz = z
     self.tilesize = getTileSize(NTILES[z], True)
     self.maps = {}
     for mapName in MAPNIK_LAYERS:
         console.debugMessage('Loading mapnik.Map: ' + mapName)
         self.maps[mapName] = mapnik.Map(self.tilesize, self.tilesize)
         mapnik.load_map(self.maps[mapName], mapName + ".xml")
Exemple #24
0
def test_simplest_render():
    m = mapnik2.Map(256, 256)
    i = mapnik2.Image(m.width, m.height)

    mapnik2.render(m, i)

    s = i.tostring()

    eq_(s, 256 * 256 * '\x00\x00\x00\x00')
Exemple #25
0
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 = mapnik2.Map(256, 256)
    
    mapnik2.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 = mapnik2.Shapefile(file='../data/shp/world_merc.shp')
    m.layers[0].datasource = ds
    
    # now ensure it is attached
    eq_(m.layers[0].datasource.name(),"shape")
    eq_(lyr.datasource.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')
    
    
    
Exemple #26
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)
Exemple #27
0
def test_load_save_map():
    map = mapnik2.Map(256, 256)
    in_map = "../data/good_maps/raster_symbolizer.xml"
    mapnik2.load_map(map, in_map)

    out_map = mapnik2.save_map_to_string(map)
    assert 'RasterSymbolizer' in out_map
    assert 'RasterColorizer' in out_map
    assert 'ColorBand' in out_map
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik2.Map(800, 600)
    mapnik2.load_map(m, mapxmlfile)
    mapnik2.save_map(m, mapxmloutputfile)
    m.zoom_all()
    mapnik2.render_to_file(m, outputfile)
 def __init__(self, tile_dir, mapfile, q, maxZoom):
     self.tile_dir = tile_dir
     self.q = q
     self.m = mapnik.Map(256, 256)
     # Load style XML
     mapnik.load_map(self.m, mapfile, False)
     # 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)
Exemple #30
0
def assert_loads_successfully(file):
    m = mapnik2.Map(512, 512)

    strict = True
    mapnik2.load_map(m, file, strict)

    # libxml2 is not smart about paths, and clips the last directory off
    # of a path if it does not end in a trailing slash
    base_path = os.path.dirname(file) + '/'
    mapnik2.load_map_from_string(m, open(file, 'rb').read(), strict, base_path)