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

Python mapnik.save_map函数代码示例

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

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



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

示例1: main

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 [email protected]'
    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
开发者ID:AppleHolic,项目名称:mapnik-utils,代码行数:27,代码来源:cascadenik-compile.py


示例2: import_style_mml

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)
开发者ID:chiahsuy,项目名称:koadstation,代码行数:26,代码来源:populate.py


示例3: main

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 [email protected]'
    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
开发者ID:seanlee928,项目名称:Cascadenik,代码行数:27,代码来源:cascadenik-compile.py


示例4: test_gen_map

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


示例5: test_gen_map

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


示例6: get_paired_images

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    
开发者ID:mojodna,项目名称:debian-mapnik,代码行数:15,代码来源:render_test.py


示例7: main

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
开发者ID:umidev,项目名称:mapnik-utils,代码行数:16,代码来源:cascadenik-compile.py


示例8: serialize

def serialize(xml,options):
    try:
        import mapnik
    except:
        sys.exit(color_text(1,'Error: saving xml requires Mapnik python bindings to be installed'))
    m = mapnik.Map(1,1)
    if options.from_string:
        mapnik.load_map_from_string(m,xml,True)
    else:
        mapnik.load_map(m,xml,True)
    if options.output:
        mapnik.save_map(m,options.output)
    else:
        if hasattr(mapnik,'mapnik_version') and mapnik.mapnik_version() >= 700:
            print mapnik.save_map_to_string(m)
        else:
            sys.exit(color_text(1,'Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file'))
开发者ID:ParveenArora,项目名称:MeraMap,代码行数:17,代码来源:generate_xml.py


示例9: import_style_tdcfg

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)
开发者ID:chiahsuy,项目名称:koadstation,代码行数:44,代码来源:populate.py


示例10: compare_map

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))
开发者ID:Nobis99,项目名称:openstreetmap-tiles-docker,代码行数:19,代码来源:save_map_test.py


示例11: compare_map

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


示例12: render_tile

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'}
开发者ID:sjsafranek,项目名称:TileServer,代码行数:22,代码来源:tileserver.py


示例13: buildMapnikXML

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")
开发者ID:Ericsonwong,项目名称:maps4mac,代码行数:36,代码来源:loaddb.py


示例14: render_raster_tile

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 [email protected] +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 [email protected] +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 [email protected] +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'}
开发者ID:sjsafranek,项目名称:TileServer,代码行数:36,代码来源:tileserver.py


示例15: test

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
开发者ID:craton-,项目名称:php_mapnik,代码行数:24,代码来源:save_map_test.py


示例16: tileMapConfig


#.........这里部分代码省略.........
                    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)
开发者ID:DemersM,项目名称:Basqui,代码行数:101,代码来源:tms.py


示例17: len

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


示例18:

#!/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 ''
开发者ID:blwoods,项目名称:MappingExperiments,代码行数:21,代码来源:make_map.py


示例19: render_layer

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='nix',
                      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
开发者ID:nix,项目名称:mapsaw,代码行数:64,代码来源:render.py


示例20: build

    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
开发者ID:hitzi,项目名称:nik2img,代码行数:93,代码来源:composer.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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