示例#1
0
def import_style_mml(url):
    """
    """
    # Create a local style.xml file by way of a dummy mapnik.Map instance.
    
    mmap = mapnik.Map(1, 1)
    mmap.srs = epsg3857
    cascadenik.load_map(mmap, url, 'gunicorn', verbose=False)
    mapnik.save_map(mmap, 'gunicorn/style.xml')
    
    # Build a new TileStache configuration file.
    
    config = json.load(open('gunicorn/tilestache.cfg'))
    
    config['layers'] = {'tiles': {'provider': {}}}
    layer = config['layers']['tiles']
    
    layer['provider']['name'] = 'mapnik'
    layer['provider']['mapfile'] = 'style.xml'
    layer['bounds'] = dict(zip('south west north east'.split(), options.bbox))
    layer['bounds'].update(dict(low=0, high=18))
    layer['preview'] = dict(zoom=15, lat=(options.bbox[0]/2 + options.bbox[2]/2), lon=(options.bbox[1]/2 + options.bbox[3]/2))
    
    # Done.
    
    json.dump(config, open('gunicorn/tilestache.cfg', 'w'), indent=2)
示例#2
0
    def compare_map(in_map):

        mapnik.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)

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

        mapnik.load_map(new_map, test_map)
        open(test_map2, 'w').write(mapnik.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))
示例#3
0
def main(file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'
    cascadenik.load_map(mmap, file, **kwargs)

    (handle, filename) = tempfile.mkstemp(suffix='.xml',
                                          prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, filename)

    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(filename, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(filename, 'wb')
        doc.write(f)
        f.close()

    if kwargs.get('compiled'):
        os.rename(filename, kwargs['compiled'])
    else:
        print open(filename, 'r').read()
        os.unlink(filename)
    return 0
def main(file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'
    cascadenik.load_map(mmap, file, **kwargs)
    
    (handle, filename) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, filename)
    
    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(filename, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(filename, 'wb')
        doc.write(f)
        f.close()
        
    if kwargs.get('compiled'):
        os.rename(filename, kwargs['compiled'])
    else:
        print open(filename, 'r').read()
        os.unlink(filename)
    return 0
示例#5
0
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'
                ))
示例#6
0
def main(src_file, dest_file, **kwargs):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    # allow [zoom] filters to work
    mmap.srs = '+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null'
    load_kwargs = dict([(k, v) for (k, v) in kwargs.items() if k in ('cache_dir', 'verbose', 'datasources_cfg')])
    cascadenik.load_map(mmap, src_file, dirname(realpath(dest_file)), **load_kwargs)
    
    (handle, tmp_file) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    mapnik.save_map(mmap, tmp_file)
    
    if kwargs.get('pretty'):
        doc = ElementTree.fromstring(open(tmp_file, 'rb').read())
        cascadenik._compile.indent(doc)
        f = open(tmp_file, 'wb')
        ElementTree.ElementTree(doc).write(f)
        f.close()
        
    # manually unlinking seems to be required on windows
    if os.path.exists(dest_file):
        os.unlink(dest_file)
    shutil.move(tmp_file, dest_file)
    return 0
def main():
    # print( getFieldInShapefile(shp_file, label_field) )

    geom_types = getGeometryTypes(shp_file)

    epsg = getProj4FromShapefile(shp_file)

    m = mapnik.Map(600, 300)

    for geom_type in geom_types:
        if 'POLYGON' == geom_type:
            s = getPolygonStyle()
            m.append_style(
                'Polygon Style', s
            )  # Styles are given names only as they are applied to the map
        elif 'LINESTRING' == geom_type:
            s = getLineStyle()
            m.append_style(
                'LineString Style', s
            )  # Styles are given names only as they are applied to the map
        elif 'POINT' == geom_type:
            s = getPointStyle()
            m.append_style(
                'Point Style', s
            )  # Styles are given names only as they are applied to the map
        else:
            raise ValueError('Uncaught geometry type: ' + geom_type)

    # if label_field and getFieldInShapefile(shp_file, label_field):
    # s = getTextStyle(label_field)
    # m.append_style('Label Style', s)

    s = getPointStyle()
    m.append_style(
        'Point Style',
        s)  # Styles are given names only as they are applied to the map

    # add datasource
    ds = mapnik.Shapefile(file=shp_file)

    # add layer
    layer = mapnik.Layer('Layer')
    # note: layer.srs will default to '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs'
    layer.datasource = ds
    layer.styles.append('Polygon Style')
    layer.styles.append('LineString Style')
    layer.styles.append('Point Style')

    # add layer to map
    m.layers.append(layer)
    m.zoom_all()

    print(mapnik.save_map_to_string(m))
    mapnik.save_map(m, 'style.xml')

    mapnik.render_to_file(m, 'sample.png', 'png')
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik.Map(800, 600)
    mapnik.load_map(m, mapxmlfile)
    mapnik.save_map(m, mapxmloutputfile)
    m.zoom_all()
    mapnik.render_to_file(m, outputfile)
示例#9
0
def main(imagefilename, xmlfilename):
    m = mapnik.Map(image_width, image_height)
    m.srs = shapefile_projection
    m.background = mapnik.Color('lightgrey')
    style, envelope = build_stylesheet(shapefile, shapefile_projection,
                                       AGS_prefixes)
    mapnik.load_map_from_string(m, style)
    m.zoom_to_box(envelope)
    mapnik.render_to_file(m, imagefilename)
    if xmlfilename:
        mapnik.save_map(m, xmlfilename)
示例#10
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik.Map(800, 600)
    try:
        mapnik.load_map(m, mapxmlfile)
        mapnik.save_map(m, mapxmloutputfile)
        m.zoom_all()
        mapnik.render_to_file(m, outputfile)
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
示例#11
0
def test_gen_map():
    mapxmlfile = '../data/good_maps/raster_colorizer.xml'
    mapxmloutputfile = 'raster_colorizer_test_save.xml'
    outputfile = 'raster_colorizer_test.png'

    m = mapnik.Map(800, 600)
    try:
        mapnik.load_map(m, mapxmlfile)
        mapnik.save_map(m, mapxmloutputfile)
        m.zoom_all()
        mapnik.render_to_file(m, outputfile)
    except RuntimeError,e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
示例#12
0
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
示例#13
0
def get_paired_images(w,h,mapfile):
    tmp_map = 'tmp_map.xml'
    m = mapnik.Map(w,h)
    mapnik.load_map(m,mapfile)
    i = mapnik.Image(w,h)
    m.zoom_all()
    mapnik.render(m,i)
    mapnik.save_map(m,tmp_map)
    m2 = mapnik.Map(w,h)
    mapnik.load_map(m2,tmp_map)
    i2 = mapnik.Image(w,h)
    m2.zoom_all()
    mapnik.render(m2,i2)
    os.remove(tmp_map)
    return i,i2    
示例#14
0
文件: generate.py 项目: s1l2/map-it
def renderMap(m):
    print 'Rendering map with dimensions %s, %s' % (m.width, m.height)
    im = mapnik.Image(m.width, m.height)
    mapnik.render(m, im)

    # Render cairo examples
    if mapnik.has_pycairo():
        print 'Rendering PDF'

        pdf_surface = cairo.PDFSurface(OUTPUT_PATH + 'slovakia.pdf', m.width, m.height)
        mapnik.render(m, pdf_surface)
        pdf_surface.finish()
        print 'Rendered PDF to %s' % (OUTPUT_PATH + 'slovakia.pdf',)

    print 'Saving map configuration to %s' % (OUTPUT_PATH + "map_slovakia.xml",)
    mapnik.save_map(m, OUTPUT_PATH + "map_slovakia.xml")
示例#15
0
def main(file, dir):
    """ Given an input layers file and a directory, print the compiled
        XML file to stdout and save any encountered external image files
        to the named directory.
    """
    mmap = mapnik.Map(1, 1)
    cascadenik.load_map(mmap, file, dir)
    
    (handle, filename) = tempfile.mkstemp(suffix='.xml', prefix='cascadenik-mapnik-')
    os.close(handle)
    
    mapnik.save_map(mmap, filename)
    print open(filename, 'r').read()
    
    os.unlink(filename)
    return 0
示例#16
0
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'))
示例#17
0
def import_style_tdcfg(url):
    """ Load a Cascadenik style and its constituent pieces from a URL.
    """
    style = json.loads(urlopen(url).read())
    mapfile = urljoin(options.style, style['mapfile'])

    # Create a local style.xml file by way of a dummy mapnik.Map instance.
    
    mmap = mapnik.Map(1, 1)
    mmap.srs = epsg3857
    cascadenik.load_map(mmap, mapfile, 'gunicorn', verbose=False)
    mapnik.save_map(mmap, 'gunicorn/style.xml')
    
    # Build a new TileStache configuration file.
    
    config = json.load(open('gunicorn/tilestache.cfg'))
    
    config['layers'] = {'tiles': {'provider': {}}}
    layer = config['layers']['tiles']
    
    layer['provider']['name'] = 'mapnik'
    layer['provider']['mapfile'] = 'style.xml'
    layer['bounds'] = dict(zip('south west north east'.split(), options.bbox))
    layer['bounds'].update(dict(low=0, high=18))
    layer['preview'] = dict(zoom=15, lat=(options.bbox[0]/2 + options.bbox[2]/2), lon=(options.bbox[1]/2 + options.bbox[3]/2))
    
    # Apply various layer options.
    
    for (parameter, value) in style['layer'].items():
        if parameter == 'png options' and 'palette' in value:
            palette_url = urljoin(url, value['palette'])
            palette_data = urlopen(palette_url).read()
            palette_file = 'gunicorn/palette.act'
            
            print >> stderr, ' ', palette_file, '<--', palette_url
            
            open(palette_file, 'w').write(palette_data)
            value['palette'] = 'palette.act'
        
        layer[parameter] = value
    
    # Done.
    
    json.dump(config, open('gunicorn/tilestache.cfg', 'w'), indent=2)
def compare_map(xml):
    m = mapnik.Map(256, 256)
    absolute_base = os.path.abspath(os.path.dirname(xml))
    mapnik.load_map(m, xml, False, absolute_base)
    (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)
    mapnik.save_map(m, test_map)
    new_map = mapnik.Map(256, 256)
    mapnik.load_map(new_map, test_map,False,absolute_base)
    open(test_map2,'w').write(mapnik.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' % (xml,diff))
示例#19
0
def compare_map(xml):
    m = mapnik.Map(256, 256)
    absolute_base = os.path.abspath(os.path.dirname(xml))
    try:
        mapnik.load_map(m, xml, False, absolute_base)
    except RuntimeError 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):
            raise RuntimeError(str(e))
        return
    (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)
    mapnik.save_map(m, test_map)
    new_map = mapnik.Map(256, 256)
    mapnik.load_map(new_map, test_map, False, absolute_base)
    with open(test_map2, 'w') as f:
        f.write(mapnik.save_map_to_string(new_map))
    diff = ' diff -u %s %s' % (os.path.abspath(test_map),
                               os.path.abspath(test_map2))
    try:
        with open(test_map) as f1:
            with open(test_map2) as f2:
                eq_(f1.read(), f2.read())
    except AssertionError as e:
        raise AssertionError(
            'serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s' %
            (xml, diff))

    if os.path.exists(test_map):
        os.remove(test_map)
    else:
        # Fail, the map wasn't written
        return False
示例#20
0
def compare_map(xml):
    m = mapnik.Map(256, 256)
    absolute_base = os.path.abspath(os.path.dirname(xml))
    try:
        mapnik.load_map(m, xml, False, absolute_base)
    except RuntimeError 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):
            raise RuntimeError(str(e))
        return
    (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)
    mapnik.save_map(m, test_map)
    new_map = mapnik.Map(256, 256)
    mapnik.load_map(new_map, test_map, False, absolute_base)
    with open(test_map2, 'w') as f:
        f.write(mapnik.save_map_to_string(new_map))
    diff = ' diff -u %s %s' % (os.path.abspath(test_map),
                               os.path.abspath(test_map2))
    try:
        with open(test_map) as f1:
            with open(test_map2) as f2:
                eq_(f1.read(), f2.read())
    except AssertionError as e:
        raise AssertionError(
            'serialized map "%s" not the same after being reloaded, \ncompare with command:\n\n$%s'
            % (xml, diff))

    if os.path.exists(test_map):
        os.remove(test_map)
    else:
        # Fail, the map wasn't written
        return False
示例#21
0
def render_tile(layer, z, x, y):
    """
    Render the tile using mapnik.
    """
    folder = os.path.join("baselayers",layer)
    if not os.path.exists(folder):
        raise ValueError("files not found")
    # Create map
    m = mapnik.Map(TILE_WIDTH, TILE_HEIGHT)
    # Load mapnik xml stylesheet
    stylesheet = os.path.join("baselayers",str(layer),"style.xml")
    mapnik.load_map(m, stylesheet)
    # Zoom to all features
    m.zoom_all()
    # Store artifacts
    stylesheet = os.path.join("stylesheets",layer + ".xml")
    mapnik.save_map(m, str(stylesheet))
    # Render Map Tile
    renderer = TiledMapRenderer(m)
    im = renderer.render_tile(z, x, y)
    # Return image
    return im.tostring('png'), 200, {'Content-type': 'image/png'}
def main(shapefile, label_field=None, output="style.xml"):

    # getAreaStatistics(shapefile)
    projection = getProj4FromShapefile(shapefile)

    label_style = ''
    if label_field:
        label_style = getLabelStyleForZooms(shapefile, label_field)

    stylesheet = buildStylesheet(shapefile, projection, label_style)

    image = 'tmp.png'
    m = mapnik.Map(900, 600)
    mapnik.load_map_from_string(m, stylesheet)
    m.zoom_all()
    m.zoom(0.05)
    # m.zoom(0.25)
    # m.zoom(0.5)
    mapnik.render_to_file(m, image)

    # print(mapnik.save_map_to_string(m))

    mapnik.save_map(m, output)
示例#23
0
def buildMapnikXML(extractName, **kwargs):
    mapnik_args = dict()
    mapnik_args['host'] = kwargs.get('host','localhost')
    mapnik_args['port'] = kwargs.get('port','5432')
    mapnik_args['user'] = kwargs.get('user','postgres')
    mapnik_args['password'] = kwargs.get('password','')
    mapnik_args['dbname'] = kwargs.get('database','osm')
    
    #FIXME: We can probably calculate this based on the extract
    mapnik_args['estimate_extent'] = 'false'
    mapnik_args['extent'] = ''
    
    mapnik_args['prefix'] = extractName
    mapnik_args['world_boundaries'] = kwargs.get('world_boundaries','./world_boundaries/')
    
    #FIXME: Can we determine the import projection from the DB?
    mapnik_args['epsg'] = kwargs.get('epsg','900913;')
    mapnik_args['symbols'] = kwargs.get('symbols','./symbols/')
    
    inc_files = ['inc/settings.xml.inc', 'inc/datasource-settings.xml.inc']
    for inc_file in inc_files:
        infile = open(inc_file + ".template")
        outfile = open(inc_file, "w")
        
        s = infile.read()
        s = s % mapnik_args
        outfile.truncate(0)
        outfile.write(s)
        
        infile.close()
        outfile.close()
        
    import mapnik
    m = mapnik.Map(1,1)
    mapnik.load_map(m,"osm_template.xml",True)
    mapnik.save_map(m,extractName + ".xml")
示例#24
0
def test():
    # TODO: Write a better test
    # 1. Construct map in memory
    # 2. Save map as XML
    # 3. Load map to a second object
    # 4. Compare both map objects
    map = mapnik.Map(256, 256)
    in_map = "../data/good_maps/osm-styles.xml"

    mapnik.load_map(map, in_map)
    test_map = "test_map.xml"

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

    mapnik.load_map(new_map, test_map)

    eq_(open(test_map).read(),mapnik.save_map_to_string(new_map))

    if os.path.exists(test_map):
        os.remove(test_map)
    else:
        # Fail, the map wasn't written
        return False
示例#25
0
def render_raster_tile(datasource, z, x, y):
    file = os.path.join("baselayers", datasource + ".tif")
    if not os.path.exists(file):
        raise ValueError("file not found")
    raster = mapnik.Gdal(file=os.path.abspath(file))
    lyr = mapnik.Layer("TIFF")
    lyr.datasource = raster
    lyr.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over"
    # Create map
    m = mapnik.Map(TILE_WIDTH, TILE_HEIGHT)
    # Create Style and Rules
    s = mapnik.Style()
    r = mapnik.Rule()
    # Create style for lyr
    r.symbols.append(mapnik.RasterSymbolizer())
    s.rules.append(r)
    m.append_style('TIFF',s)
    lyr.styles.append('TIFF')
    # Set map srs to google
    # 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')
    # m.srs = merc.params()
    m.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs +over"
    # Add layer to map
    m.layers.append(lyr)
    # Zoom to all features
    #m.maximum_extent = mapnik.Box2d(-180,-90,180,90)
    m.maximum_extent = mapnik.Box2d(-20037508.34,-20037508.34,20037508.34,20037508.34) # merc_bounds
    m.zoom_all()
    # Store artifacts
    stylesheet = os.path.join("stylesheets", datasource + ".xml")
    mapnik.save_map(m, str(stylesheet))
    # Render Map Tile
    renderer = TiledMapRenderer(m)
    im = renderer.render_tile(z, x, y)
    # Return image
    return im.tostring('png'), 200, {'Content-type': 'image/png'}
示例#26
0
文件: tms.py 项目: DemersM/Basqui
def tileMapConfig(map_id):

    map_selected = BasquiMap.objects.get(pk=map_id)
    layersMapOptions = LayerMapOptions.objects.filter(basqui_map=map_selected).order_by('-position')
    layers_used = Shapefile.objects.filter(Q(layermapoptions__basqui_map=map_selected), Q(layermapoptions__style_visible=True) | Q(layermapoptions__label_visible=True))

    mapXML = mapnik.Map(TILE_WIDTH, TILE_HEIGHT, "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over")
    mapXML.buffer_size=128

    if len(layers_used) >0:
        query = """(SELECT shapefile_id, coalesce(geom_multipoint, geom_multilinestring, geom_multipolygon) as g
                    %s
                    FROM layers_feature WHERE shapefile_id IN (%s)
                    AND (geom_multipoint && !bbox! OR geom_multilinestring && !bbox! OR geom_multipolygon && !bbox! )
                    ) as geom""" % (
                    ''.join([",attribute_value->'" + label.field.name +"' as " +  str(label.field.name).lower() +"_" +  str(label.pk) for x in layersMapOptions.filter(label_visible=True) for label in x.layerlabel_set.all()]).replace(',None',''),
                    ','.join([str(x.pk) for x in layers_used ]))

    #','.join(["attribute_value->'" + x.label.field.name +"'" if x.label is not None else 'None' for x in layersMapOptions ]).replace(',None',''),

        datasource = mapnik.PostGIS(
                        host=dbSettings['HOST'],
                        user=dbSettings['USER'],
                        password=dbSettings['PASSWORD'],
                        dbname=dbSettings['NAME'],
                        port=dbSettings['PORT'],
                        table=query,
                        geometry_field = 'g',
                        #extent_from_subquery=True,
                        estimate_extent=False,
                        srid=3857,
                        extent='-20037508.34, -20037508.34, 20037508.34, 20037508.34',
                        simplify_geometries=True,
                        geometry_table='layers_feature')

        featureLayer = mapnik.Layer("tiled_layer")
        featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        featureLayer.datasource = datasource
        featureLayer.cache_features = True

        #defining the feature layer styles
        for layerMapOptions in layersMapOptions.filter(style_visible=True):
            layerStyles = layerMapOptions.layerstyle_set.all().order_by('-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(str(layer.name) + '_Styles_' + str(layerMapOptions.pk))
            layer_style = mapnik.Style()
            for layerStyle in layerStyles:
                style_rule = mapnik.Rule()
                if layerStyle.filter:
                    style_rule.filter = mapnik.Filter("[shapefile_id] = %s and (%s)" % (layer.pk, str(layerStyle.filter)))
                else:
                    style_rule.filter = mapnik.Filter("[shapefile_id] = %s" % layer.pk)
                if layerStyle.minScale:
                    style_rule.min_scale = layerStyle.minScale
                if layerStyle.maxScale:
                    style_rule.max_scale = layerStyle.maxScale
                if layer.geom_type in ["Point", "MultiPoint"]:
                    m = mapnik.MarkersSymbolizer()
                    m.filename = os.path.abspath("../media/%s" % layerStyle.marker.svg)
                    m.fill = mapnik.Color(str(layerStyle.fill))
                    m.fill_opacity = layerStyle.fill_opacity
                    s = mapnik.Stroke()
                    s.color = mapnik.Color(str(layerStyle.stroke_color))
                    s.width = layerStyle.stroke_width
                    s.opacity = layerStyle.stroke_opacity
                    m.stroke = s
                    if layerStyle.transform:
                        m.transform = str(layerStyle.transform)
                    m.allow_overlap = layerStyle.allow_overlap
                    m.spacing = layerStyle.spacing
                    m.max_error = layerStyle.max_error
                    #m.placement = mapnik.marker_placement(layerStyle.placement)
                    #m.ignore_placement = layerStyle.ignore_placement
                    style_rule.symbols.append(m)
                elif layer.geom_type in ["LineString", "MultiLineString"]:
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.width = layerStyle.stroke_width
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.line_join = mapnik.line_join(layerStyle.stroke_linejoin)
                    l.stroke.line_cap = mapnik.line_cap(layerStyle.stroke_linecap)
                    if layerStyle.dash_array:
                        dash_array = [tuple(float(i) for i in el.strip('()').split(',')) for el in layerStyle.dash_array.split('),(')]
                        for d in dash_array:
                            l.stroke.add_dash(d[0],d[1])
                    l.stroke.gamma = layerStyle.gamma
                    l.stroke.gamma_method = mapnik.gamma_method(layerStyle.gamma_method)
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.rasterizer = mapnik.line_rasterizer(layerStyle.stroke_rasterizer)
                    style_rule.symbols.append(l)
                elif layer.geom_type in ["Polygon", "MultiPolygon"]:
                    p = mapnik.PolygonSymbolizer()
                    p.fill = mapnik.Color(str(layerStyle.fill))
                    p.fill_opacity = layerStyle.fill_opacity
                    p.clip = layerStyle.clip
                    p.gamma = layerStyle.gamma
                    p.gamme_method = mapnik.gamma_method(layerStyle.gamma_method)
                    p.smooth = layerStyle.smooth
                    p.simplify_tolerance = layerStyle.simplify_tolerance
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.width = layerStyle.stroke_width
                    if layerStyle.dash_array:
                        dash_array = [tuple(float(i) for i in el.strip('()').split(',')) for el in layerStyle.dash_array.split('),(')]
                        for d in dash_array:
                            l.stroke.add_dash(d[0],d[1])
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.stroke.gamma = layerStyle.gamma
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    style_rule.symbols.append(p)
                    style_rule.symbols.append(l)
                layer_style.rules.append(style_rule)
            mapXML.append_style(str(layer.name) + '_Styles_' + str(layerMapOptions.pk), layer_style)

            #defining label styles
        for layerMapOptions in layersMapOptions.filter(label_visible=True):
            layerLabels = layerMapOptions.layerlabel_set.all().order_by('-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(str(layer.name) + '_Label_' + str(layerMapOptions.pk))
            label_style = mapnik.Style()
            for layerLabel in layerLabels:
                label_rule = mapnik.Rule()
                if layerLabel.filter:
                    label_rule.filter = mapnik.Filter("[shapefile_id] = %s and (%s)" % (layer.pk, str(layerLabel.filter)))
                else:
                    label_rule.filter = mapnik.Filter("[shapefile_id] = %s" % layer.pk)
                if layerLabel.minScale:
                    label_rule.min_scale = layerLabel.minScale
                if layerLabel.maxScale:
                    label_rule.max_scale = layerLabel.maxScale
                label_column = '[%s_%s]' % (str(layerLabel.field).lower(), str(layerLabel.pk))
                t = mapnik.TextSymbolizer(mapnik.Expression(label_column), str(layerLabel.face_name), layerLabel.size, mapnik.Color(str(layerLabel.fill)))
                t.halo_fill = mapnik.Color(str(layerLabel.halo_fill))
                t.halo_radius = layerLabel.halo_radius
                t.halo_rasterizer = mapnik.halo_rasterizer(layerLabel.halo_rasterizer)
                t.opacity = layerLabel.opacity
                t.character_spacing = layerLabel.character_spacing
                t.line_spacing = layerLabel.line_spacing
                t.text_ratio = layerLabel.text_ratio
                t.text_transform = mapnik.text_transform(layerLabel.text_transform)
                t.clip = layerLabel.clip
                t.label_placement = mapnik.label_placement(layerLabel.label_placement)
                t.vertical_alignment = mapnik.vertical_alignment(layerLabel.vertical_alignment)
                t.horizontal_alignment = mapnik.horizontal_alignment(layerLabel.horizontal_alignment)
                t.justify_alignment = mapnik.justify_alignment(layerLabel.justify_alignment)
                t.displacement = (layerLabel.dx, layerLabel.dy)
                t.orientation = mapnik.Expression(str(layerLabel.orientation))
                t.rotate_displacement = layerLabel.rotate_displacement
                t.label_position_tolerance = layerLabel.label_position_tolerance
                t.avoid_edges = layerLabel.avoid_edges
                t.minimum_padding = layerLabel.minimum_padding
                t.allow_overlap = layerLabel.allow_overlap
                t.minimum_distance = layerLabel.minimum_distance
                t.repeat_distance = mapnik.Expression(str(layerLabel.repeat_distance))
                t.minimum_path_length = layerLabel.minimum_path_length
                t.maximum_angle_char_delta = layerLabel.maximum_angle_char_delta
                t.wrap_width = layerLabel.wrap_width
                if layerLabel.wrap_character:
                    t.wrap_character = ord(layerLabel.wrap_character)
                t.wrap_before = layerLabel.wrap_before
                label_rule.symbols.append(t)
                label_style.rules.append(label_rule)
            mapXML.append_style(str(layer.name) + '_Label_' + str(layerMapOptions.pk), label_style)

        mapXML.layers.append(featureLayer)

    #saving the map mapnik xml
    mapnik_xml_path = "../tilestache/%s/maps/viewer/%s_%s.xml" % (str(map_selected.created_by.username), str(map_selected.name), str(map_selected.pk))
    mapnik.save_map(mapXML, mapnik_xml_path)
示例#27
0
    try:
        mapnik.load_map(m, xml, False, absolute_base)
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
        return
    (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)
    mapnik.save_map(m, test_map)
    new_map = mapnik.Map(256, 256)
    mapnik.load_map(new_map, test_map, False, absolute_base)
    open(test_map2, 'w').write(mapnik.save_map_to_string(new_map))
    diff = ' diff -u %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'
            % (xml, diff))

    if os.path.exists(test_map):
        os.remove(test_map)
    else:
示例#28
0
# Create the city layer.
city_lyr = mapnik.Layer('City Outline')
city_shp = mapnik.Shapefile(file=r'D:\osgeopy-data\Louisiana\NOLA')
city_lyr.datasource = city_shp

# Create a black dashed line.
city_color = mapnik.Color('black')
city_sym = mapnik.LineSymbolizer(city_color, 2)
city_sym.stroke.add_dash(4, 2)
city_rule = mapnik.Rule()
city_rule.symbols.append(city_sym)
city_style = mapnik.Style()
city_style.rules.append(city_rule)

m.append_style('city style', city_style)
city_lyr.styles.append('city style')

# Add all of the layers to the map.
m.layers.append(atlas_lyr)
m.layers.append(tiger_lyr)
m.layers.append(roads_lyr)
m.layers.append(city_lyr)

# Save the map.
mapnik.render_to_file(m, r'd:\temp\nola3.png')

# This saves an xml file describing the map. It's used in a later
# example in the book.
mapnik.save_map(m, r'd:\temp\nola_map.xml')
示例#29
0
    def build(self):
        self.msg('Loading mapfile...')
        loader = Load(self.mapfile, variables={}, from_string=self.from_string)
        if not self.from_string:
            self.msg('Loaded %s...' % self.mapfile)
        else:
            self.msg('Loaded XML from string')
        self.map = loader.build_map(self.width, self.height)

        if self.srs:
            self.msg('Setting srs to: %s' % self.srs)
            self.map.set_easy_srs(self.srs)

        if self.layers:
            selected, disactivated = self.map.select_layers(self.layers)
            self.msg('Selected layers: %s' % selected)
            if not selected:
                self.output_error(
                    'Layer not found: available layers are: "%s"' %
                    ',  '.join(disactivated))

        # handle shifts in pixel dimensions or bbox ratio
        # need to make as an option
        #try:
        #    self.map.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_CANVAS_HEIGHT
        #except:
        #    self.msg('aspect_fix_mode not available!')

        # zoom to max extent at beginning if we later need to
        # zoom to a center point
        # or need to zoom to a zoom-level
        if self.center or not self.zoom is None:
            if self.max_extent:
                self.msg('Zooming to max extent: %s' % self.max_extent)
                self.map.zoom_to_box(mapnik.Envelope(*self.max_extent))
            else:
                self.map.zoom_max()
                self.msg('Zoomed to *estimated* max extent: %s' %
                         self.map.envelope())

        if self.center and not self.zoom is None:
            self.msg('Zooming to Center (%s) and Zoom Level "%s"' %
                     (self.center, self.zoom))
            self.map.set_center_and_zoom(self.center[0], self.center[1],
                                         self.zoom)
        elif self.center and self.radius:
            self.msg('Zooming to Center (%s) and Radius "%s"' %
                     (self.center, self.radius))
            self.map.set_center_and_radius(self.center[0], self.center[1],
                                           self.radius)
        elif not self.zoom is None:
            self.msg('Zooming to Zoom Level "%s"' % (self.zoom))
            self.map.zoom_to_level(self.zoom)
        elif self.zoom_to_layers:
            self.msg('Zooming to Layers: "%s"' % (self.zoom_to_layers))
            self.map.activate_layers(self.zoom_to_layers)
            if len(self.zoom_to_layers) > 1:
                self.map.zoom_to_layers(self.zoom_to_layers)
            else:
                self.map.zoom_to_layer(self.zoom_to_layers[0])
        else:
            if self.extent:
                env = mapnik.Envelope(*self.extent)
                self.msg('Zooming to custom projected extent: "%s"' % env)
                self.map.zoom_to_box(env)
                from_prj = mapnik.Projection(self.map.srs)
                to_prj = mapnik.Projection('+init=epsg:4326')
                bbox = env.transform(from_prj, to_prj)
                self.msg('Custom extent in geographic coordinates: "%s"' %
                         bbox)
            elif self.bbox:
                env = mapnik.Envelope(*self.bbox)
                self.msg('Zooming to custom geographic extent: "%s"' % env)
                from_prj = mapnik.Projection('+init=epsg:4326')
                to_prj = mapnik.Projection(self.map.srs)
                self.map.zoom_to_box(env.transform(from_prj, to_prj))
            else:
                self.map.zoom_all()
                self.msg('Zoom to extent of all layers: "%s"' %
                         self.map.envelope())

        if self.save_xml:
            mapnik.save_map(self.map, self.save_xml)
示例#30
0
文件: test.py 项目: chriskoli/mapnik
    diff = compare(actual, expected)
    if diff > 0:
        print "-"*80
        print '\x1b[33mError:\x1b[0m %u different pixels' % diff
        print "-"*80

    return m

if __name__ == "__main__":
    if '-q' in sys.argv:
       quiet = True
       sys.argv.remove('-q')
    else:
       quiet = False

    if len(sys.argv) == 2:
        files = [{"name": sys.argv[1], "sizes": sizes_few_square}]
    elif len(sys.argv) > 2:
        files = []
        for name in sys.argv[1:]:
            files.append({"name": name})

    for f in files:
        config = dict(defaults)
        config.update(f)
        for size in config['sizes']:
            m = render(config['name'], size[0], size[1], config['bbox'], quiet=quiet)
        mapnik.save_map(m, os.path.join(dirname, 'xml_output', "%s-out.xml" % config['name']))

    summary()
示例#31
0
def tileLayer(request, version, shapefile_id, zoom, x, y):
    try:
        if version != "1.0":
            raise Http404
        try:
            shapefile = Shapefile.objects.get(id=shapefile_id,
                                              created_by=request.user)
        except Shapefile.DoesNotExist:
            raise Http404
        zoom = int(zoom)
        x = int(x)
        y = int(y)
        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404
        xExtent = _unitsPerPixel(zoom)
        yExtent = _unitsPerPixel(zoom)
        minLong = x * xExtent - 20037508.34
        minLat = y * yExtent - 20037508.34
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent
        if (minLong < -20037508.34 or maxLong > 20037508.34
                or minLat < -20037508.34 or maxLat > 20037508.34):
            raise Http404

        #create de mapnik.map object
        map = mapnik.Map(
            TILE_WIDTH, TILE_HEIGHT,
            "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        )
        map.background = mapnik.Color("#f2f3f7")
        #defining the feature layer
        geometryField = utils.calcGeometryField(shapefile.geom_type)
        field = "'NOM'"
        field2 = "'CODE'"
        query = '(select ' + geometryField + ', attribute_value->' + field + ' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(
            shapefile.id) + ')) as geom'

        ##        datasource = mapnik.SQLite(file='C:\mygeosite\sqlite3\sql3.db',
        ##                                        table=query,
        ##                                        srid=3857,
        ##                                        geometry_field=geometryField)

        ##        datasource = mapnik.PostGIS(user=dbSettings['USER'],
        ##                        password=dbSettings['PASSWORD'],
        ##                        dbname=dbSettings['NAME'],
        ##                        table=query,
        ##                        srid=3857,
        ##                        geometry_field=geometryField,
        ##                        simplify_geometries=True,
        ##                        geometry_table='"shapefile_feature"')

        feature = Feature.objects.filter(shapefile__id=shapefile_id).geojson()
        geoj = feature.geojson
        datasource = mapnik.Ogr(layer_by_index=0, string=geoj)
        ##
        featureLayer = mapnik.Layer("featureLayer")
        featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        featureLayer.datasource = datasource
        featureLayer.styles.append("featureLayerStyle")

        #defining the feature layer styles
        rule = mapnik.Rule()
        if shapefile.geom_type in ["Point", "MultiPoint"]:
            rule.symbols.append(mapnik.PointSymbolizer())
        elif shapefile.geom_type in ["LineString", "MultiLineString"]:
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
            rule.symbols.append(
                mapnik.PolygonSymbolizer(mapnik.Color("#f7edee")))
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))


##        label = mapnik.TextSymbolizer(mapnik.Expression('[label]'), 'DejaVu Sans Book', 10, mapnik.Color('black'))
##        label.halo_fill = mapnik.Color('white')
##        label.halo_radius = 4
##        label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT
##        label.allow_overlap = True
##        label.avoid_edges = True
##        rule.symbols.append(label)
        style = mapnik.Style()
        style.rules.append(rule)

        #add new feature to the map
        map.append_style("featureLayerStyle", style)
        map.layers.append(featureLayer)

        #rendering the map tile
        mapnik.save_map(
            map, "../tilestache/%s/%s.xml" %
            (str(request.user), str(shapefile.filename)))

        config = {
            "cache": {
                "name": "Test",
                "path": "../tilestache/%s" % (request.user),
                "umask": "0000",
                "dirs": "portable"
            },
            "layers": {
                shapefile.filename: {
                    "provider": {
                        "name":
                        "mapnik",
                        "mapfile":
                        "../tilestache/%s/%s.xml" %
                        (request.user, shapefile.filename)
                    },
                    "projection": "spherical mercator"
                }
            }
        }

        # like http://tile.openstreetmap.org/1/0/0.png
        #coord = ModestMaps.Core.Coordinate(y, x, zoom)
        path = "/%s/%s/%s/%s.png" % (shapefile.filename, zoom, x, y)
        config = TileStache.Config.buildConfiguration(config)
        #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png')
        type, bytes = TileStache.requestHandler(config, path)
        return HttpResponse(bytes, mimetype="image/png")

    except:
        traceback.print_exc()
        return HttpResponse("")
示例#32
0
# Create the city layer.
city_lyr = mapnik.Layer('City Outline')
city_shp = mapnik.Shapefile(file=r'D:\osgeopy-data\Louisiana\NOLA')
city_lyr.datasource = city_shp

# Create a black dashed line.
city_color = mapnik.Color('black')
city_sym = mapnik.LineSymbolizer(city_color, 2)
city_sym.stroke.add_dash(4, 2)
city_rule = mapnik.Rule()
city_rule.symbols.append(city_sym)
city_style = mapnik.Style()
city_style.rules.append(city_rule)

m.append_style('city style', city_style)
city_lyr.styles.append('city style')

# Add all of the layers to the map.
m.layers.append(atlas_lyr)
m.layers.append(tiger_lyr)
m.layers.append(roads_lyr)
m.layers.append(city_lyr)

# Save the map.
mapnik.render_to_file(m, r'd:\temp\nola3.png')

# This saves an xml file describing the map. It's used in a later
# example in the book.
mapnik.save_map(m, r'd:\temp\nola_map.xml')
r.symbols.append(PolygonSymbolizer(Color('#f2eff9')))
r.symbols.append(LineSymbolizer(Color('rgb(50%,50%,50%)'), 0.1))
s.rules.append(r)
m.append_style('My Style', s)

lyr = Layer('france', proj4)
import os

shp = Shapefile(base='.', file='departement')

lyr.datasource = shp
#lyr.datasource = SQLite(base=os.getcwd(), file = sqlitedatabase, table = tablename, geometry_field = 'Geometry', key_field = 'ID_GEOFLA', extent = shp_extent, wkb_format = 'spatialite')

lyr.styles.append('My Style')
lyr.styles.append('Text')

m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())

file_formats = {
    'svg': cairo.SVGSurface,
}

for type_format in file_formats:
    print '// --  Rendering %s -----------------------------' % type_format
    file_open = open('%s.%s' % (map_output, type_format), 'w')
    surface = file_formats[type_format](file_open.name, m.width, m.height)
    render(m, surface)
    save_map(m, "tmp_map.xml")
    surface.finish()
示例#34
0
    m = mapnik.Map(256, 256)
    absolute_base = os.path.abspath(os.path.dirname(xml))
    try:
        mapnik.load_map(m, xml, False, absolute_base)
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(str(e))
        return
    (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)
    mapnik.save_map(m, test_map)
    new_map = mapnik.Map(256, 256)
    mapnik.load_map(new_map, test_map,False,absolute_base)
    open(test_map2,'w').write(mapnik.save_map_to_string(new_map))
    diff = ' diff -u %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' % (xml,diff))

    if os.path.exists(test_map):
        os.remove(test_map)
    else:
        # Fail, the map wasn't written
        return False
示例#35
0
def xml_map_config(request, zoom, x, y, basqui_map, layersMapOptions):
    basqui_map.changed = False
    basqui_map.save()
    map = mapnik.Map(
        TILE_WIDTH, TILE_HEIGHT,
        "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
    )

    for layer in layersMapOptions.all():
        try:
            layerLabel = LayerLabel.objects.get(layerMapOptions=layer)
        except ObjectDoesNotExist:
            layerLabel = None
        for layerStyle in layer.styles.all():
            shapefile = layer.layer
            geometryField = utils.calcGeometryField(shapefile.geom_type)
            if layerLabel:
                query = '(select ' + geometryField + ', attribute_value->\'' + layerLabel.field.name + '\' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(
                    shapefile.id) + ')) as geom'
            else:
                query = '(select ' + geometryField + ', id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(
                    shapefile.id) + ')) as geom'

            datasource = mapnik.PostGIS(user=dbSettings['USER'],
                                        password=dbSettings['PASSWORD'],
                                        dbname=dbSettings['NAME'],
                                        port=5433,
                                        table=query,
                                        srid=3857,
                                        geometry_field=geometryField,
                                        geometry_table='"shapefile_feature"')

            featureLayer = mapnik.Layer(
                str(shapefile.filename) + str(layerStyle.id))
            featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
            featureLayer.datasource = datasource
            featureLayer.styles.append(
                str(shapefile.filename) + '_Style' + str(layerStyle.id))

            #defining the feature layer styles
            style_rule = mapnik.Rule()
            if shapefile.geom_type in ["Point", "MultiPoint"]:
                s = mapnik.PointSymbolizer(
                    mapnik.PathExpression(str(layerStyle.iconName)))
                s.allow_overlap = True
                style_rule.symbols.append(s)
            elif shapefile.geom_type in ["LineString", "MultiLineString"]:
                style_rule.symbols.append(
                    mapnik.LineSymbolizer(
                        mapnik.Color(str(layerStyle.strokeColor)),
                        layerStyle.strokeWeight))
            elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
                p = mapnik.PolygonSymbolizer(
                    mapnik.Color(str((layerStyle.fillColor))))
                p.fill_opacity = layerStyle.fillOpacity
                style_rule.symbols.append(p)
                style_rule.symbols.append(
                    mapnik.LineSymbolizer(
                        mapnik.Color(str(layerStyle.strokeColor)),
                        layerStyle.strokeWeight))
            layer_style = mapnik.Style()
            layer_style.rules.append(style_rule)

            #defining label styles
            if layerLabel:
                label_rule = mapnik.Rule()
                label = mapnik.TextSymbolizer(
                    mapnik.Expression('[label]'), 'DejaVu Sans Book',
                    layerLabel.font_size,
                    mapnik.Color(str(layerLabel.font_color)))
                label.halo_fill = mapnik.Color(str(layerLabel.halo_color))
                label.halo_radius = int(layerLabel.halo_radius)
                #label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT
                label.allow_overlap = False
                label.avoid_edges = True
                label_rule.symbols.append(label)
                label_style = mapnik.Style()
                label_style.rules.append(label_rule)
                featureLayer.styles.append(
                    str(shapefile.filename) + '_label' + str(layerStyle.id))
                #add label to the map
                map.append_style(
                    str(shapefile.filename) + '_label' + str(layerStyle.id),
                    label_style)

            #add new feature to the map
            map.append_style(
                str(shapefile.filename) + '_Style' + str(layerStyle.id),
                layer_style)
            map.layers.append(featureLayer)

    #saving the map mapnik xml
    mapnik.save_map(
        map, "c:\\basqui\\tilestache\\%s\\%s.xml" %
        (str(request.user), str(basqui_map.map_name)))
示例#36
0
    def build(self):
        self.msg('Loading mapfile...')
        loader = Load(self.mapfile,variables={},from_string=self.from_string)
        if not self.from_string:
            self.msg('Loaded %s...' % self.mapfile)
        else:
            self.msg('Loaded XML from string')
        self.map = loader.build_map(self.width,self.height)

        if self.srs:
            self.msg('Setting srs to: %s' % self.srs)
            self.map.set_easy_srs(self.srs)

        if self.layers:
            selected, disactivated = self.map.select_layers(self.layers)
            self.msg('Selected layers: %s' % selected)
            if not selected:
                self.output_error('Layer not found: available layers are: "%s"' % ',  '.join(disactivated))
                
        # handle shifts in pixel dimensions or bbox ratio
        # need to make as an option
        #try:
        #    self.map.aspect_fix_mode = mapnik.aspect_fix_mode.ADJUST_CANVAS_HEIGHT
        #except:
        #    self.msg('aspect_fix_mode not available!')

        
        # zoom to max extent at beginning if we later need to 
        # zoom to a center point
        # or need to zoom to a zoom-level
        if self.center or not self.zoom is None:
            if self.max_extent:
                self.msg('Zooming to max extent: %s' % self.max_extent) 
                self.map.zoom_to_box(mapnik.Envelope(*self.max_extent))
            else:
                self.map.zoom_max()
                self.msg('Zoomed to *estimated* max extent: %s' % self.map.envelope()) 

        if self.center and not self.zoom is None:
            self.msg('Zooming to Center (%s) and Zoom Level "%s"' % (self.center,self.zoom))
            self.map.set_center_and_zoom(self.center[0],self.center[1],self.zoom)
        elif self.center and self.radius:
            self.msg('Zooming to Center (%s) and Radius "%s"' % (self.center,self.radius))
            self.map.set_center_and_radius(self.center[0],self.center[1],self.radius)
        elif not self.zoom is None:
            self.msg('Zooming to Zoom Level "%s"' % (self.zoom))
            self.map.zoom_to_level(self.zoom)
        elif self.zoom_to_layers:
            self.msg('Zooming to Layers: "%s"' % (self.zoom_to_layers))
            self.map.activate_layers(self.zoom_to_layers)
            if len(self.zoom_to_layers) > 1:
                self.map.zoom_to_layers(self.zoom_to_layers)
            else:
                self.map.zoom_to_layer(self.zoom_to_layers[0])
        else:
            if self.extent:
                env = mapnik.Envelope(*self.extent)
                self.msg('Zooming to custom projected extent: "%s"' % env)
                self.map.zoom_to_box(env)
                from_prj = mapnik.Projection(self.map.srs)
                to_prj = mapnik.Projection('+init=epsg:4326')
                bbox = env.transform(from_prj,to_prj)
                self.msg('Custom extent in geographic coordinates: "%s"' % bbox)
            elif self.bbox:
                env = mapnik.Envelope(*self.bbox)
                self.msg('Zooming to custom geographic extent: "%s"' % env)
                from_prj = mapnik.Projection('+init=epsg:4326')
                to_prj = mapnik.Projection(self.map.srs)
                self.map.zoom_to_box(env.transform(from_prj,to_prj))
            else:
                self.map.zoom_all()
                self.msg('Zoom to extent of all layers: "%s"' % self.map.envelope())

        if self.save_xml:
            mapnik.save_map(self.map,self.save_xml)
示例#37
0
    "formating-2",
    "formating-3",
    "formating-4",
    "shieldsymbolizer-1",
    "expressionformat",
]


def render(filename, width):
    print 'Rendering style "%s" with width %d' % (filename, width)
    m = mapnik.Map(width, 100)
    mapnik.load_map(m, os.path.join(dirname, "%s.xml" % filename), False)
    bbox = mapnik.Box2d(-0.05, -0.01, 0.95, 0.01)
    m.zoom_to_box(bbox)
    mapnik.render_to_file(m, "%s-%d-agg.png" % (filename, width))
    return m


if len(sys.argv) > 1:
    filenames = []
    filenames_one_width = sys.argv[1:]

for filename in filenames:
    for width in widths:
        m = render(filename, width)
    mapnik.save_map(m, "%s-out.xml" % filename)

for filename in filenames_one_width:
    m = render(filename, 500)
    mapnik.save_map(m, "%s-out.xml" % filename)
示例#38
0
#!/usr/bin/env python
import mapnik
print ''
print '=' * 42
print '-' * 42
print 'Making...'
print '-' * 42
mapfile = "style.xml"
m = mapnik.Map(1690, 800)
mapnik.load_map(m, mapfile)
#bbox = mapnik.Envelope(mapnik.Coord(-180.0, -75.0), mapnik.Coord(180.0, 90.0))
#bbox = mapnik.Envelope(mapnik.Coord(-80, 30.0), mapnik.Coord(-49.0, 54.0))
#bbox = mapnik.Envelope(mapnik.Coord(-90, 40.0), mapnik.Coord(-64.0, 50.0))
bbox = mapnik.Envelope(mapnik.Coord(-70, 45.0), mapnik.Coord(-54.0, 50.0))
m.zoom_to_box(bbox)
mapnik.render_to_file(m, 'map.png', 'png')
mapnik.save_map(m, 'generated_map.xml')
print '-' * 42
print 'Made!'
print '-' * 42
print ''
示例#39
0
文件: tms.py 项目: DemersM/Basqui
def tileFeature(request, version, shapefile_id, feature_id, zoom, x, y):
    try:
        if version != "1.0":
            raise Http404
        try:
            shapefile = Shapefile.objects.get(id=shapefile_id,
                                              created_by=request.user)
        except Shapefile.DoesNotExist:
            raise Http404
        zoom = int(zoom)
        x = int(x)
        y = int(y)
        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404
        xExtent = _unitsPerPixel(zoom)
        yExtent = _unitsPerPixel(zoom)
        minLong = x * xExtent - 20037508.34
        minLat = y * yExtent - 20037508.34
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent
        if (minLong < -20037508.34 or maxLong > 20037508.34
                or minLat < -20037508.34 or maxLat > 20037508.34):
            raise Http404

        #create mapnik.map object
        map = mapnik.Map(
            TILE_WIDTH, TILE_HEIGHT,
            "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        )
        map.background = mapnik.Color("#fff")
        #defining the feature layer
        geometryField = utils.calcGeometryField(shapefile.geom_type)
        query = '(select ' + geometryField + ', id, id_relat as label from "layers_feature" WHERE shapefile_id = ' + str(
            shapefile.id) + ' AND id = ' + str(feature_id) + ') as geom'

        datasource = mapnik.PostGIS(host=dbSettings['HOST'],
                                    user=dbSettings['USER'],
                                    password=dbSettings['PASSWORD'],
                                    dbname=dbSettings['NAME'],
                                    port=dbSettings['PORT'],
                                    table=query,
                                    srid=3857,
                                    geometry_field=geometryField,
                                    simplify_geometries=True,
                                    geometry_table='"layers_feature"')

        featureLayer = mapnik.Layer("featureLayer")
        featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        featureLayer.datasource = datasource
        featureLayer.styles.append("featureLayerStyle")

        #defining the feature layer styles
        rule = mapnik.Rule()
        if shapefile.geom_type in [
                "Point", "3D Point", "MultiPoint", "3D MultiPoint"
        ]:
            rule.symbols.append(mapnik.PointSymbolizer())
        elif shapefile.geom_type in [
                "LineString", "3D LineString", "MultiLineString",
                "3D MultiLineString"
        ]:
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        elif shapefile.geom_type in [
                "Polygon", "3D Polygon", "MultiPolygon", "3D MultiPolygon"
        ]:
            rule.symbols.append(
                mapnik.PolygonSymbolizer(mapnik.Color("#f7edee")))
            rule.symbols.append(
                mapnik.LineSymbolizer(mapnik.Color("#000000"), 0.5))
        style = mapnik.Style()
        style.rules.append(rule)
        map.append_style("featureLayerStyle", style)

        label_rule = mapnik.Rule()
        label = mapnik.TextSymbolizer(mapnik.Expression('[label]'),
                                      'DejaVu Sans Book', 10,
                                      mapnik.Color('black'))
        label.halo_radius = 4
        label.allow_overlap = False
        label.avoid_edges = True
        label_rule.symbols.append(label)
        label_style = mapnik.Style()
        label_style.rules.append(label_rule)
        featureLayer.styles.append("featureLayerStyle_label")
        #add label to the map
        map.append_style("featureLayerStyle_label", label_style)

        #add new feature to the map
        map.layers.append(featureLayer)

        #rendering the map tile
        mapnik_xml_path = "../tilestache/%s/layers/vector/lightViewer/%s.xml" % (
            str(request.user), str(shapefile.name))
        mapnik.save_map(map, mapnik_xml_path)

        config = {
            "cache": {
                "name": "Test",
                "path": "../tilestache/%s" % (request.user),
                "umask": "0000",
                "dirs": "portable"
            },
            "layers": {
                shapefile.name: {
                    "provider": {
                        "name": "mapnik",
                        "mapfile": mapnik_xml_path
                    },
                    "metatile": {
                        "rows": 2,
                        "columns": 2,
                        "buffer": 64
                    },
                    "projection": "spherical mercator",
                    "write cache": False
                }
            }
        }

        path = "/%s/%s/%s/%s.png" % (shapefile.name, zoom, x, y)
        config = TileStache.Config.buildConfiguration(config)
        type, bytes = TileStache.requestHandler(config, path)
        return HttpResponse(bytes, content_type="image/png")

    except:
        traceback.print_exc()
        return HttpResponse("")
示例#40
0
#highways
s_highway = mapnik.Style()
r_highway = mapnik.Rule()
road_stroke = mapnik.Stroke()
road_stroke.width = 2.0
#dashed lines
#road_stroke.add_dash(8, 4)
#road_stroke.add_dash(2, 2)
#road_stroke.add_dash(2, 2)
road_stroke.color = mapnik.Color('yellow')
road_stroke.line_cap = mapnik.line_cap.ROUND_CAP
#r_highway.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color('yellow')))
r_highway.symbols.append(mapnik.LineSymbolizer(road_stroke))
s_highway.rules.append(r_highway)
m.append_style('highway', s_highway)
l_highway = mapnik.Layer('highway', "+proj=latlong +datum=WGS84")
l_highway.datasource = mapnik.Shapefile(file='target/export/highway')
l_highway.styles.append('highway')
m.append_style('highway', s_highway)

m.layers.append(l_building)
m.layers.append(l_highway)
m.layers.append(l_water)
m.layers.append(l_natural)
m.zoom_to_box(l_highway.envelope())
img_loc = 'target/export.png'
mapnik.render_to_file(m, img_loc, 'png')
mapnik.save_map(m, "target/map.xml")
os.system('open ' + img_loc)
示例#41
0
文件: composer.py 项目: hitzi/nik2img
    def build(self):
        self.msg('Loading mapfile...')
        
        builder = Load(self.mapfile,variables={},from_string=self.from_string,verbose=self.verbose)
        if not self.from_string:
            self.msg('Loaded %s...' % self.mapfile)
        else:
            self.msg('Loaded XML from string')
        self.map = builder.build_map(self.width,self.height)

        if self.srs:
            self.msg('Setting srs to: %s' % self.srs)
            self.map.set_easy_srs(self.srs)

        if self.layers:
            selected, disactivated = self.map.select_layers(self.layers)
            self.msg('Selected layers: %s' % selected)
            if not selected:
                self.output_error('Layer not found: available layers are: "%s"' % ',  '.join(disactivated))
                
        # set up behavior for fixing relationship between map aspect and bbox aspect
        if self.aspect_fix_mode:
            if not hasattr(self.map, 'aspect_fix_mode'):
                self.output_error('Your version of Mapnik does not support setting the aspect_fix_mode (only available in >= Mapnik 0.6.0')
            try:
                mode = getattr(mapnik.aspect_fix_mode,self.aspect_fix_mode.upper())
            except AttributeError:
                self.output_error('Error setting aspect_fix_mode, accepted values are: %s' % ', '.join(mapnik.aspect_fix_mode.names.keys()))
            
            self.map.aspect_fix_mode = mode

        # zoom to max extent at beginning if we later need to 
        # zoom to a center point
        # or need to zoom to a zoom-level
        self.msg('Setting Map view...')
        
        if self.center or not self.zoom is None:
            if self.max_extent:
                self.msg('Zooming to max extent: %s' % self.max_extent) 
                self.map.zoom_to_box(mapnik.Box2d(*self.max_extent))
            else:
                self.map.zoom_max()
                self.msg('Zoomed to *estimated* max extent: %s' % self.map.envelope()) 

        if self.center and not self.zoom is None:
            self.msg('Zooming to Center (%s) and Zoom Level "%s"' % (self.center,self.zoom))
            self.map.set_center_and_zoom(self.center[0],self.center[1],self.zoom)
        elif self.center and self.radius:
            self.msg('Zooming to Center (%s) and Radius "%s"' % (self.center,self.radius))
            self.map.set_center_and_radius(self.center[0],self.center[1],self.radius)
        elif not self.zoom is None:
            self.msg('Zooming to Zoom Level "%s"' % (self.zoom))
            self.map.zoom_to_level(self.zoom)
        elif self.zoom_to_layers:
            self.msg('Zooming to Layers: "%s"' % (self.zoom_to_layers))
            self.map.activate_layers(self.zoom_to_layers)
            if len(self.zoom_to_layers) > 1:
                self.map.zoom_to_layers(self.zoom_to_layers)
            else:
                self.map.zoom_to_layer(self.zoom_to_layers[0])
        else:
            if self.extent:
                env = mapnik.Box2d(*self.extent)
                self.msg('Zooming to custom projected extent: "%s"' % env)
                self.map.zoom_to_box(env)
                from_prj = mapnik.Projection(self.map.srs)
                to_prj = mapnik.Projection('+proj=latlong +datum=WGS84')
                bbox = env.forward(from_prj,to_prj)
                self.msg('Custom extent in geographic coordinates: "%s"' % bbox)
            elif self.bbox:
                env = mapnik.Box2d(*self.bbox)
                self.msg('Zooming to custom geographic extent: "%s"' % env)
                from_prj = mapnik.Projection('+proj=latlong +datum=WGS84')
                to_prj = mapnik.Projection(self.map.srs)
                self.map.zoom_to_box(env.forward(from_prj,to_prj))
            else:
                self.map.zoom_all()
                self.msg('Zoom to extent of all layers: "%s"' % self.map.envelope())
        
        if self.bbox_factor:
            if self.bbox_factor > 0:
                bbox = self.map.envelope() * self.bbox_factor
            else:
                bbox = self.map.envelope() / self.bbox_factor
            self.map.zoom_to_box(bbox)
            self.msg('Adjusting final extent by factor of %s: "%s"' % (self.bbox_factor,self.map.envelope()))
            
        self.msg('Finished setting extents...')
        
        if self.save_xml:
            mapnik.save_map(self.map,self.save_xml)
        
        return builder
示例#42
0
    if "--overwrite" in sys.argv:
        overwrite_failures = True
        sys.argv.remove("--overwrite")
    else:
        overwrite_failures = False

    if len(sys.argv) == 2:
        files = [{"name": sys.argv[1], "sizes": sizes_few_square}]
    elif len(sys.argv) > 2:
        files = []
        for name in sys.argv[1:]:
            files.append({"name": name})

    if not os.path.exists(visual_output_dir):
        os.makedirs(visual_output_dir)

    if "osm" in mapnik.DatasourceCache.plugin_names():
        reporting = Reporting(quiet, overwrite_failures)
        for f in files:
            config = dict(defaults)
            config.update(f)
            for size in config["sizes"]:
                for scale_factor in config["scales"]:
                    m = render(config, size[0], size[1], config.get("bbox"), scale_factor, reporting)
            mapnik.save_map(m, os.path.join(dirname, "xml_output", "%s-out.xml" % config["name"]))

        sys.exit(reporting.summary())
    else:
        print "OSM plugin required"
示例#43
0
def tileMap(request, version, ezmap_id, zoom, x, y):
    try:
        if version != "1.0":
            raise Http404
        try:
            ezmap = EzMap.objects.get(id=ezmap_id)
            layersMapOptions = LayerMapOptions.objects.filter(
                ezmap=ezmap, visible=True).order_by('-position')
        except Shapefile.DoesNotExist or Feature.DoesNotExist:
            raise Http404
        zoom = int(zoom)
        x = int(x)
        y = int(y)
        if zoom < 0 or zoom > MAX_ZOOM_LEVEL:
            raise Http404
        xExtent = _unitsPerPixel(zoom)
        yExtent = _unitsPerPixel(zoom)
        minLong = x * xExtent - 20037508.34
        minLat = y * yExtent - 20037508.34
        maxLong = minLong + xExtent
        maxLat = minLat + yExtent
        if (minLong < -20037508.34 or maxLong > 20037508.34
                or minLat < -20037508.34 or maxLat > 20037508.34):
            raise Http404

        if ezmap.changed:
            #create de mapnik.map object
            ezmap.changed = False
            ezmap.save()
            map = mapnik.Map(
                TILE_WIDTH, TILE_HEIGHT,
                "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
            )
            #map.background = mapnik.Color("#ffffff")
            #defining the feature layer
            for layer in layersMapOptions.all():
                label = LayerLabel.objects.get(layerMapOptions=layer)
                for layerStyle in layer.styles.all():
                    shapefile = layer.layer
                    geometryField = utils.calcGeometryField(
                        shapefile.geom_type)
                    query = '(select ' + geometryField + ', attribute_value->\'' + label.field.name + '\' as label, id_relat from "shapefile_feature" where' + ' shapefile_id in (' + str(
                        shapefile.id) + ')) as geom'

                    ##                    datasource = mapnik.SQLite(file='C:\mygeosite\sqlite3\sql3.db',
                    ##                                                    table=query,
                    ##                                                    srid=3857,
                    ##                                                    geometry_field=geometryField,
                    ##                                                    use_spatial_index=False)

                    datasource = mapnik.PostGIS(
                        user=dbSettings['USER'],
                        password=dbSettings['PASSWORD'],
                        dbname=dbSettings['NAME'],
                        table=query,
                        srid=3857,
                        geometry_field=geometryField,
                        geometry_table='"shapefile_feature"')

                    featureLayer = mapnik.Layer(
                        str(shapefile.filename) + str(layerStyle.id))
                    featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
                    featureLayer.datasource = datasource
                    featureLayer.styles.append(
                        str(shapefile.filename) + '_Style' +
                        str(layerStyle.id))

                    #defining the feature layer styles
                    rule = mapnik.Rule()
                    if shapefile.geom_type in ["Point", "MultiPoint"]:
                        s = mapnik.PointSymbolizer(
                            mapnik.PathExpression(str(layerStyle.iconName)))
                        s.allow_overlap = True
                        rule.symbols.append(s)
                    elif shapefile.geom_type in [
                            "LineString", "MultiLineString"
                    ]:
                        rule.symbols.append(
                            mapnik.LineSymbolizer(
                                mapnik.Color(str(layerStyle.strokeColor)),
                                layerStyle.strokeWeight))
                    elif shapefile.geom_type in ["Polygon", "MultiPolygon"]:
                        p = mapnik.PolygonSymbolizer(
                            mapnik.Color(str((layerStyle.fillColor))))
                        p.fill_opacity = layerStyle.fillOpacity
                        rule.symbols.append(p)
                        rule.symbols.append(
                            mapnik.LineSymbolizer(
                                mapnik.Color(str(layerStyle.strokeColor)),
                                layerStyle.strokeWeight))

                    label = mapnik.TextSymbolizer(
                        mapnik.Expression('[label]'), 'DejaVu Sans Book',
                        label.font_size, mapnik.Color(str(label.font_color)))
                    label.halo_fill = mapnik.Color(str(label.halo_color))
                    label.halo_radius = int(label.halo_radius)
                    label.label_placement = mapnik.label_placement.INTERIOR_PLACEMENT
                    label.allow_overlap = False
                    label.avoid_edges = True
                    rule.symbols.append(label)
                    style = mapnik.Style()
                    style.rules.append(rule)

                    #add new feature to the map
                    map.append_style(
                        str(shapefile.filename) + '_Style' +
                        str(layerStyle.id), style)
                    map.layers.append(featureLayer)

            #saving the map mapnik xml
            mapnik.save_map(
                map, "c:\\mygeosite\\tilestache\\%s\\%s.xml" %
                (str(request.user), str(ezmap.map_name)))

        config = {
            "cache": {
                "name": "test",
                "path": "../tilestache/%s" % (request.user),
                "umask": "0000",
                "dirs": "portable"
            },
            "layers": {
                ezmap.map_name: {
                    "provider": {
                        "name":
                        "mapnik",
                        "mapfile":
                        "../tilestache/%s/%s.xml" %
                        (request.user, ezmap.map_name)
                    },
                    "projection": "spherical mercator"
                }
            }
        }

        # like http://tile.openstreetmap.org/1/0/0.png
        #coord = ModestMaps.Core.Coordinate(y, x, zoom)
        path = "/%s/%s/%s/%s.png" % (ezmap.map_name, zoom, x, y)
        config = TileStache.Config.buildConfiguration(config)
        #type, bytes = TileStache.getTile(config.layers[shapefile.filename], coord, 'png')
        type, bytes = TileStache.requestHandler(config, path)
        return HttpResponse(bytes, mimetype="image/png")

    except:
        traceback.print_exc()
        return HttpResponse("")
示例#44
0
文件: tms.py 项目: DemersM/Basqui
def tileMapConfig(map_id):

    map_selected = BasquiMap.objects.get(pk=map_id)
    layersMapOptions = LayerMapOptions.objects.filter(
        basqui_map=map_selected).order_by('-position')
    layers_used = Shapefile.objects.filter(
        Q(layermapoptions__basqui_map=map_selected),
        Q(layermapoptions__style_visible=True)
        | Q(layermapoptions__label_visible=True))

    mapXML = mapnik.Map(
        TILE_WIDTH, TILE_HEIGHT,
        "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
    )
    mapXML.buffer_size = 128

    if len(layers_used) > 0:
        query = """(SELECT shapefile_id, coalesce(geom_multipoint, geom_multilinestring, geom_multipolygon) as g
                    %s
                    FROM layers_feature WHERE shapefile_id IN (%s)
                    AND (geom_multipoint && !bbox! OR geom_multilinestring && !bbox! OR geom_multipolygon && !bbox! )
                    ) as geom""" % (''.join([
            ",attribute_value->'" + label.field.name + "' as " +
            str(label.field.name).lower() + "_" + str(label.pk)
            for x in layersMapOptions.filter(label_visible=True)
            for label in x.layerlabel_set.all()
        ]).replace(',None', ''), ','.join([str(x.pk) for x in layers_used]))

        #','.join(["attribute_value->'" + x.label.field.name +"'" if x.label is not None else 'None' for x in layersMapOptions ]).replace(',None',''),

        datasource = mapnik.PostGIS(
            host=dbSettings['HOST'],
            user=dbSettings['USER'],
            password=dbSettings['PASSWORD'],
            dbname=dbSettings['NAME'],
            port=dbSettings['PORT'],
            table=query,
            geometry_field='g',
            #extent_from_subquery=True,
            estimate_extent=False,
            srid=3857,
            extent='-20037508.34, -20037508.34, 20037508.34, 20037508.34',
            simplify_geometries=True,
            geometry_table='layers_feature')

        featureLayer = mapnik.Layer("tiled_layer")
        featureLayer.srs = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +no_defs +over"
        featureLayer.datasource = datasource
        featureLayer.cache_features = True

        #defining the feature layer styles
        for layerMapOptions in layersMapOptions.filter(style_visible=True):
            layerStyles = layerMapOptions.layerstyle_set.all().order_by(
                '-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(
                str(layer.name) + '_Styles_' + str(layerMapOptions.pk))
            layer_style = mapnik.Style()
            for layerStyle in layerStyles:
                style_rule = mapnik.Rule()
                if layerStyle.filter:
                    style_rule.filter = mapnik.Filter(
                        "[shapefile_id] = %s and (%s)" %
                        (layer.pk, str(layerStyle.filter)))
                else:
                    style_rule.filter = mapnik.Filter("[shapefile_id] = %s" %
                                                      layer.pk)
                if layerStyle.minScale:
                    style_rule.min_scale = layerStyle.minScale
                if layerStyle.maxScale:
                    style_rule.max_scale = layerStyle.maxScale
                if layer.geom_type in ["Point", "MultiPoint"]:
                    m = mapnik.MarkersSymbolizer()
                    m.filename = os.path.abspath("../media/%s" %
                                                 layerStyle.marker.svg)
                    m.fill = mapnik.Color(str(layerStyle.fill))
                    m.fill_opacity = layerStyle.fill_opacity
                    s = mapnik.Stroke()
                    s.color = mapnik.Color(str(layerStyle.stroke_color))
                    s.width = layerStyle.stroke_width
                    s.opacity = layerStyle.stroke_opacity
                    m.stroke = s
                    if layerStyle.transform:
                        m.transform = str(layerStyle.transform)
                    m.allow_overlap = layerStyle.allow_overlap
                    m.spacing = layerStyle.spacing
                    m.max_error = layerStyle.max_error
                    #m.placement = mapnik.marker_placement(layerStyle.placement)
                    #m.ignore_placement = layerStyle.ignore_placement
                    style_rule.symbols.append(m)
                elif layer.geom_type in ["LineString", "MultiLineString"]:
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.width = layerStyle.stroke_width
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.line_join = mapnik.line_join(
                        layerStyle.stroke_linejoin)
                    l.stroke.line_cap = mapnik.line_cap(
                        layerStyle.stroke_linecap)
                    if layerStyle.dash_array:
                        dash_array = [
                            tuple(float(i) for i in el.strip('()').split(','))
                            for el in layerStyle.dash_array.split('),(')
                        ]
                        for d in dash_array:
                            l.stroke.add_dash(d[0], d[1])
                    l.stroke.gamma = layerStyle.gamma
                    l.stroke.gamma_method = mapnik.gamma_method(
                        layerStyle.gamma_method)
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.rasterizer = mapnik.line_rasterizer(
                        layerStyle.stroke_rasterizer)
                    style_rule.symbols.append(l)
                elif layer.geom_type in ["Polygon", "MultiPolygon"]:
                    p = mapnik.PolygonSymbolizer()
                    p.fill = mapnik.Color(str(layerStyle.fill))
                    p.fill_opacity = layerStyle.fill_opacity
                    p.clip = layerStyle.clip
                    p.gamma = layerStyle.gamma
                    p.gamme_method = mapnik.gamma_method(
                        layerStyle.gamma_method)
                    p.smooth = layerStyle.smooth
                    p.simplify_tolerance = layerStyle.simplify_tolerance
                    l = mapnik.LineSymbolizer()
                    l.stroke.color = mapnik.Color(str(layerStyle.stroke_color))
                    l.stroke.opacity = layerStyle.stroke_opacity
                    l.stroke.width = layerStyle.stroke_width
                    if layerStyle.dash_array:
                        dash_array = [
                            tuple(float(i) for i in el.strip('()').split(','))
                            for el in layerStyle.dash_array.split('),(')
                        ]
                        for d in dash_array:
                            l.stroke.add_dash(d[0], d[1])
                    l.offset = layerStyle.stroke_offset
                    l.clip = layerStyle.clip
                    l.stroke.gamma = layerStyle.gamma
                    l.smooth = layerStyle.smooth
                    l.simplify_tolerance = layerStyle.simplify_tolerance
                    style_rule.symbols.append(p)
                    style_rule.symbols.append(l)
                layer_style.rules.append(style_rule)
            mapXML.append_style(
                str(layer.name) + '_Styles_' + str(layerMapOptions.pk),
                layer_style)

            #defining label styles
        for layerMapOptions in layersMapOptions.filter(label_visible=True):
            layerLabels = layerMapOptions.layerlabel_set.all().order_by(
                '-position')
            layer = layerMapOptions.layer
            featureLayer.styles.append(
                str(layer.name) + '_Label_' + str(layerMapOptions.pk))
            label_style = mapnik.Style()
            for layerLabel in layerLabels:
                label_rule = mapnik.Rule()
                if layerLabel.filter:
                    label_rule.filter = mapnik.Filter(
                        "[shapefile_id] = %s and (%s)" %
                        (layer.pk, str(layerLabel.filter)))
                else:
                    label_rule.filter = mapnik.Filter("[shapefile_id] = %s" %
                                                      layer.pk)
                if layerLabel.minScale:
                    label_rule.min_scale = layerLabel.minScale
                if layerLabel.maxScale:
                    label_rule.max_scale = layerLabel.maxScale
                label_column = '[%s_%s]' % (str(
                    layerLabel.field).lower(), str(layerLabel.pk))
                t = mapnik.TextSymbolizer(mapnik.Expression(label_column),
                                          str(layerLabel.face_name),
                                          layerLabel.size,
                                          mapnik.Color(str(layerLabel.fill)))
                t.halo_fill = mapnik.Color(str(layerLabel.halo_fill))
                t.halo_radius = layerLabel.halo_radius
                t.halo_rasterizer = mapnik.halo_rasterizer(
                    layerLabel.halo_rasterizer)
                t.opacity = layerLabel.opacity
                t.character_spacing = layerLabel.character_spacing
                t.line_spacing = layerLabel.line_spacing
                t.text_ratio = layerLabel.text_ratio
                t.text_transform = mapnik.text_transform(
                    layerLabel.text_transform)
                t.clip = layerLabel.clip
                t.label_placement = mapnik.label_placement(
                    layerLabel.label_placement)
                t.vertical_alignment = mapnik.vertical_alignment(
                    layerLabel.vertical_alignment)
                t.horizontal_alignment = mapnik.horizontal_alignment(
                    layerLabel.horizontal_alignment)
                t.justify_alignment = mapnik.justify_alignment(
                    layerLabel.justify_alignment)
                t.displacement = (layerLabel.dx, layerLabel.dy)
                t.orientation = mapnik.Expression(str(layerLabel.orientation))
                t.rotate_displacement = layerLabel.rotate_displacement
                t.label_position_tolerance = layerLabel.label_position_tolerance
                t.avoid_edges = layerLabel.avoid_edges
                t.minimum_padding = layerLabel.minimum_padding
                t.allow_overlap = layerLabel.allow_overlap
                t.minimum_distance = layerLabel.minimum_distance
                t.repeat_distance = mapnik.Expression(
                    str(layerLabel.repeat_distance))
                t.minimum_path_length = layerLabel.minimum_path_length
                t.maximum_angle_char_delta = layerLabel.maximum_angle_char_delta
                t.wrap_width = layerLabel.wrap_width
                if layerLabel.wrap_character:
                    t.wrap_character = ord(layerLabel.wrap_character)
                t.wrap_before = layerLabel.wrap_before
                label_rule.symbols.append(t)
                label_style.rules.append(label_rule)
            mapXML.append_style(
                str(layer.name) + '_Label_' + str(layerMapOptions.pk),
                label_style)

        mapXML.layers.append(featureLayer)

    #saving the map mapnik xml
    mapnik_xml_path = "../tilestache/%s/maps/viewer/%s_%s.xml" % (str(
        map_selected.created_by.username), str(
            map_selected.name), str(map_selected.pk))
    mapnik.save_map(mapXML, mapnik_xml_path)
示例#45
0
    image_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, m.width, m.height)
    mapnik.render(m, image_surface)
    image_surface.write_to_png('demo_cairo_argb32.png')
    images_.append('demo_cairo_argb32.png')
    image_surface.finish()

else:
    print '\n\nPycairo not available...',
    if mapnik.has_cairo():
        print ' will render Cairo formats using alternative method'

        mapnik.render_to_file(m, 'demo.pdf')
        images_.append('demo.pdf')
        mapnik.render_to_file(m, 'demo.ps')
        images_.append('demo.ps')
        mapnik.render_to_file(m, 'demo.svg')
        images_.append('demo.svg')
        mapnik.render_to_file(m, 'demo_cairo_rgb24.png', 'RGB24')
        images_.append('demo_cairo_rgb.png')
        mapnik.render_to_file(m, 'demo_cairo_argb32.png', 'ARGB32')
        images_.append('demo_cairo_argb.png')

print "\n\n", len(images_), "maps have been rendered in the current directory:"

for im_ in images_:
    print "-", im_

print "\n\nHave a look!\n\n"

mapnik.save_map(m, "map.xml")
示例#46
0
    images_.append('demo.webp')

    im.save('demo_highest.webp', 'webp:quality=100')
    images_.append('demo_med.webp')

    im.save('demo_low.webp', 'webp:quality=50')
    images_.append('demo_low.webp')


# Render cairo examples
if  mapnik.has_cairo():
    mapnik.render_to_file(m,'demo.pdf')
    images_.append('demo.pdf')
    mapnik.render_to_file(m,'demo.ps')
    images_.append('demo.ps')
    mapnik.render_to_file(m,'demo.svg')
    images_.append('demo.svg')
    mapnik.render_to_file(m,'demo_cairo_rgb24.png','RGB24')
    images_.append('demo_cairo_rgb.png')
    mapnik.render_to_file(m,'demo_cairo_argb32.png','ARGB32')
    images_.append('demo_cairo_argb.png')

print ("\n\n", len(images_), "maps have been rendered in the current directory:")

for im_ in images_:
    print ("-", im_)

print ("\n\nHave a look!\n\n")

mapnik.save_map(m,"map.xml")
示例#47
0
            mapXml = '%s\%s\%s\%s\%sE%sN.xml' % (os.path.abspath('.'),
                                                 'VectorTiles', box[0],
                                                 zoomRank, rc[0], rc[1])
            if (os.path.exists('%s\%s\%s' %
                               (os.path.abspath('.'), 'VectorTiles', box[0]))
                    != True):
                os.makedirs('%s\%s\%s' %
                            (os.path.abspath('.'), 'VectorTiles', box[0]))
            if os.path.exists(
                ("%s\%s\%s\%s" % (os.path.abspath('.'), "VectorTiles", box[0],
                                  zoomRank))) != True:
                os.makedirs(
                    ("%s\%s\%s\%s" %
                     (os.path.abspath('.'), "VectorTiles", box[0], zoomRank)))
            index = index + 1
            xResolution = abs((grids[rc].maxx - grids[rc].minx) / 256)
            yResolution = abs((grids[rc].maxy - grids[rc].miny) / 256)
            m.zoom_to_box(
                mapnik.Box2d(grids[rc].minx - bufferWidth * xResolution,
                             grids[rc].miny - bufferWidth * yResolution,
                             grids[rc].maxx + bufferWidth * xResolution,
                             grids[rc].maxy + bufferWidth * yResolution))
            mapnik.save_map(m, mapXml)
            mapnik.render_to_file(m, png)
log = open("log.txt", 'a')
timeEnd = time.time()
print str(timeEnd - timeStart)
log.write('{0};{1};{2}\r\n'.format(zoomStart, zoomEnd,
                                   str(timeEnd - timeStart)))
log.close()
示例#48
0
    def save_map(self, output_filename,
                 title = "City's map",
                 file_type = None,
                 copyright_logo_png = None,
                 force = False):
        """
        Save the map as an image. By default, the format is inferred
        from the filename (its extension). It can be forced with the
        'file_type' parameter.
        @param output_filename (string) file to generate
        @param file_type (string) None, or 'xml', 'png', 'ps',
        'pdf', 'svg' or 'svgz'
        @param force (bool) fore render_map() to be called, even if it
        does not appear to have changed since last render_map()
        """
        if self._dirty or force:
            self.render_map()

        if file_type is None:
            file_type = output_filename.split('.')[-1]
        
        file_type = file_type.lower()
        cairo_factory = None

        if file_type == 'xml':
            mapnik.save_map(self._map, output_filename)
            return
        
        elif file_type == 'csv':
            l.debug('not rendering map as csv (not supported)')
            return

        elif file_type in ('png', 'png24'): # 24-bits, the default
            if (title is None) or (cairo is None):
                mapnik.render_to_file(self._map, output_filename, 'png')
                return
            else:
                cairo_factory = \
                    lambda w,h: cairo.ImageSurface(cairo.FORMAT_RGB24, w, h)

        elif file_type == 'svg' and cairo is not None:
            cairo_factory = lambda w,h: cairo.SVGSurface(output_filename, w, h)

        elif file_type == 'svgz' and cairo is not None:
            def cairo_factory(w,h):
                gz = gzip.GzipFile(output_filename, 'wb')
                return cairo.SVGSurface(gz, w, h)

        elif file_type == 'pdf' and cairo is not None:
            cairo_factory = lambda w,h: cairo.PDFSurface(output_filename, w, h)

        elif file_type == 'ps' and cairo is not None:
            cairo_factory = lambda w,h: cairo.PSSurface(output_filename, w, h)

        else:
            raise ValueError('Unsupported output format: %s' % file_type)

        # Cairo reendering
        if title is not None:
            frame_width = int(max(self._map.height / 20., 30))

            surface = cairo_factory(self._map.width + frame_width*2,
                                    self._map.height + frame_width*2)

            def my_render(ctx):
                mapnik.render(self._map,
                              ctx)
                draw_utils.add_logo(ctx, self._map.width,
                                    self._map.height,
                                    copyright_logo_png)

            draw_utils.enclose_in_frame(my_render,
                                        self._map.width, self._map.height,
                                        title,
                                        surface,
                                        self._map.width + frame_width*2,
                             self._map.height + frame_width*2, frame_width)
        else:
            surface = cairo_factory(self._map.width, self._map.height)
            ctx = cairo.Context(surface)
            mapnik.render(self._map, ctx)

        surface.flush()

        # png rendering with cairo...
        if file_type in ('png', 'png24'):
            surface.write_to_png(output_filename)

        surface.finish()
示例#49
0
# Script to create an xml file to describe the National Atlas
# hydrography layer.

import mapnik

m = mapnik.Map(0, 0)

water_rule = mapnik.Rule()
water_rule.filter = mapnik.Expression("[Feature]='Canal' or [Feature]='Lake'")
water_rule.symbols.append(mapnik.PolygonSymbolizer(mapnik.Color(165, 191,
                                                                221)))

marsh_rule = mapnik.Rule()
marsh_rule.filter = mapnik.Expression("[Feature]='Swamp or Marsh'")
marsh_color = mapnik.Color('#66AA66')
marsh_rule.symbols.append(mapnik.PolygonSymbolizer(marsh_color))
marsh_rule.symbols.append(mapnik.LineSymbolizer(marsh_color, 2))

atlas_style = mapnik.Style()
atlas_style.rules.append(water_rule)
atlas_style.rules.append(marsh_rule)
m.append_style('atlas', atlas_style)

lyr = mapnik.Layer('National Atlas Hydro',
                   "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
lyr.datasource = mapnik.Shapefile(file=r'D:\osgeopy-data\US\wtrbdyp010')
lyr.styles.append('atlas')
m.layers.append(lyr)

mapnik.save_map(m, r'D:\osgeopy-data\US\national_atlas_hydro.xml')
r.symbols.append(PolygonSymbolizer(Color('#f2eff9')))
r.symbols.append(LineSymbolizer(Color('rgb(50%,50%,50%)'), 0.1))
s.rules.append(r)
m.append_style('My Style', s)

lyr = Layer('france', proj4)
import os

shp = Shapefile(base='.',file='departement') 

lyr.datasource = shp
#lyr.datasource = SQLite(base=os.getcwd(), file = sqlitedatabase, table = tablename, geometry_field = 'Geometry', key_field = 'ID_GEOFLA', extent = shp_extent, wkb_format = 'spatialite')

lyr.styles.append('My Style')
lyr.styles.append('Text')

m.layers.append(lyr)
m.zoom_to_box(lyr.envelope())

file_formats = {'svg': cairo.SVGSurface,
                       }

for type_format in file_formats:
    print '// --  Rendering %s -----------------------------' % type_format
    file_open = open('%s.%s' % (map_output, type_format), 'w')
    surface = file_formats[type_format](file_open.name, m.width, m.height)
    render(m, surface)
    save_map(m,"tmp_map.xml")
    surface.finish()

示例#51
0
文件: render.py 项目: nix/mapsaw
def render_layer(workdir, layername, grid, sourcenames):
    layers = []
    for name in sourcenames:
        source = dict(mapconfig.datasources[name])
        if 'table' in source:
            source.update(mapconfig.db)
        if 'file' in source:
            source['type'] = 'shape'
            source['file'] = os.path.join(workdir, source['file'])

        layer = attrdict(name=name,
                         datasource_params=source)
        if 'srs' in source:
            layer.srs = source['srs']
        layers.append(layer)

    """
    if isinstance(source, basestring):
        source = dict(type='shape', file=source)
    else:
        table,multi = source
        source = dict(type='postgis',
                      table=table,
                      multiple_geometries=multi,
                      #estimate_extent='false',
                      #extent=','.join([str(x) for x in grid.extent()]),
                      user='******',
                      dbname='osmdb')
    lines = attrdict(name='lines',
                     datasource_params=source,
                     srs=data_srs)
    """

    sy,sx = grid.shape
    srs = grid.srs()

    base = None
    styletxt = get_mss(layername)
    styles = do_mss(layers, styletxt, base, srs)

    map = mapnik.Map(sx, sy, srs)
    styles.to_mapnik(map)

    x0,y0,x1,y1 = grid.extent()

    daspect = (x1-x0) / (y1-y0) * sy / sx
    if abs(daspect - 1) > 1e-5:
        raise Exception('aspect ratios must match to avoid mapnik bug? (grid %s vs map %s)'
                        % ((x1-x0) / (y1-y0), sy / sx))

    map.zoom_to_box(mapnik.Envelope(*grid.extent()))

    if 1:
        # XXX should use a tempfile here
        mapfile = 'foo.xml'
        mapnik.save_map(map, mapfile)
        print 'MAPXML'
        print open(mapfile).read()

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

    imgdata = N.frombuffer(img.tostring(), dtype=N.uint8).reshape((sy, sx, 4))
    return N.array(imgdata, N.float32) / 255.0
示例#52
0
    if len(sys.argv) == 2:
        files = [{"name": sys.argv[1], "sizes": sizes_few_square}]
    elif len(sys.argv) > 2:
        files = []
        for name in sys.argv[1:]:
            files.append({"name": name})

    if not os.path.exists(visual_output_dir):
        os.makedirs(visual_output_dir)


    if 'osm' in mapnik.DatasourceCache.plugin_names():
        reporting = Reporting(quiet, overwrite_failures)
        for f in files:
            config = dict(defaults)
            config.update(f)
            for size in config['sizes']:
                for scale_factor in config['scales']:
                    m = render(config,
                               size[0],
                               size[1],
                               config.get('bbox'),
                               scale_factor,
                               reporting)
            mapnik.save_map(m, os.path.join(dirname, 'xml_output', "%s-out.xml" % config['name']))

        sys.exit(reporting.summary())
    else:
        print "OSM plugin required"
示例#53
0
import cairo
import sys
import os.path

dirname = os.path.dirname(sys.argv[0])

widths = [800, 600, 400, 300, 250, 200, 150, 100]
filenames = ["list", "simple"]
filenames_one_width = [
    "simple-E", "simple-NE", "simple-NW", "simple-N", "simple-SE", "simple-SW",
    "simple-S", "simple-W"
]


def render(filename, width):
    print "Rendering style \"%s\" with width %d" % (filename, width)
    m = mapnik.Map(width, 100)
    mapnik.load_map(m, os.path.join(dirname, "%s.xml" % filename), False)
    bbox = mapnik.Box2d(-0.05, -0.01, 0.95, 0.01)
    m.zoom_to_box(bbox)
    mapnik.render_to_file(m, '%s-%d-agg.png' % (filename, width))
    return m


for filename in filenames:
    for width in widths:
        m = render(filename, width)
    mapnik.save_map(m, "%s-out.xml" % filename)

for filename in filenames_one_width:
    render(filename, 500)
示例#54
0
#!/usr/bin/env python
import mapnik
print ''
print '=' * 42
print '-' * 42
print 'Making...'
print '-' * 42
mapfile = "style.xml"
m = mapnik.Map(1690, 800)
mapnik.load_map(m, mapfile)
#bbox = mapnik.Envelope(mapnik.Coord(-180.0, -75.0), mapnik.Coord(180.0, 90.0))
#bbox = mapnik.Envelope(mapnik.Coord(-80, 30.0), mapnik.Coord(-49.0, 54.0))
#bbox = mapnik.Envelope(mapnik.Coord(-90, 40.0), mapnik.Coord(-64.0, 50.0))
bbox = mapnik.Envelope(mapnik.Coord(-70, 45.0), mapnik.Coord(-54.0, 50.0))
m.zoom_to_box(bbox) 
mapnik.render_to_file(m, 'map.png', 'png')
mapnik.save_map(m,'generated_map.xml')
print '-' * 42
print 'Made!'
print '-' * 42
print ''
示例#55
0
    select_files = {}
    if len(sys.argv) > 1:
        for name in sys.argv[1:]:
            if name in files:
                select_files[name]=files[name]
            else:
                select_files[name]={}
    if len(select_files) > 0:
        files = select_files

    if not os.path.exists(visual_output_dir):
        os.makedirs(visual_output_dir)

    reporting = Reporting(quiet, overwrite_failures)
    for filename in files:
        config = dict(defaults)
        config.update(files[filename])
        for size in config['sizes']:
            for scale_factor in config['scales']:
                m = render(filename,
                           config,
                           size[0],
                           size[1],
                           config.get('bbox'),
                           scale_factor,
                           reporting)
        mapnik.save_map(m, os.path.join(dirname, 'xml_output', "%s-out.xml" % filename))

    sys.exit(reporting.summary())
示例#56
0
 def saveMapXml(self, countryFilename, mapFilename):
     assert (self.m is not None)
     mapnik.save_map(self.m, mapFilename)
# hydrography layer.

import mapnik

m = mapnik.Map(0, 0)

water_rule = mapnik.Rule()
water_rule.filter = mapnik.Expression(
    "[Feature]='Canal' or [Feature]='Lake'")
water_rule.symbols.append(
    mapnik.PolygonSymbolizer(mapnik.Color(165, 191, 221)))

marsh_rule = mapnik.Rule()
marsh_rule.filter = mapnik.Expression("[Feature]='Swamp or Marsh'")
marsh_color = mapnik.Color('#66AA66')
marsh_rule.symbols.append(mapnik.PolygonSymbolizer(marsh_color))
marsh_rule.symbols.append(mapnik.LineSymbolizer(marsh_color, 2))

atlas_style = mapnik.Style()
atlas_style.rules.append(water_rule)
atlas_style.rules.append(marsh_rule)
m.append_style('atlas', atlas_style)

lyr = mapnik.Layer('National Atlas Hydro',
                   "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs")
lyr.datasource = mapnik.Shapefile(file=r'D:\osgeopy-data\US\wtrbdyp010')
lyr.styles.append('atlas')
m.layers.append(lyr)

mapnik.save_map(m, r'D:\osgeopy-data\US\national_atlas_hydro.xml')
示例#58
0
        overwrite_failures = True
        sys.argv.remove('--overwrite')
    else:
        overwrite_failures = False

    select_files = {}
    if len(sys.argv) > 1:
        for name in sys.argv[1:]:
            if name in files:
                select_files[name] = files[name]
            else:
                select_files[name] = {}
    if len(select_files) > 0:
        files = select_files

    if not os.path.exists(visual_output_dir):
        os.makedirs(visual_output_dir)

    reporting = Reporting(quiet, overwrite_failures)
    for filename in files:
        config = dict(defaults)
        config.update(files[filename])
        for size in config['sizes']:
            for scale_factor in config['scales']:
                m = render(filename, config, size[0], size[1],
                           config.get('bbox'), scale_factor, reporting)
        mapnik.save_map(
            m, os.path.join(dirname, 'xml_output', "%s-out.xml" % filename))

    sys.exit(reporting.summary())