示例#1
0
def serialize(xml, options):
    try:
        import mapnik2 as mapnik
    except:
        try:
            import mapnik
        except:
            sys.exit(
                color_text(
                    1,
                    'Error: saving xml requires Mapnik python bindings to be installed'
                ))
    m = mapnik.Map(1, 1)
    if options.from_string:
        mapnik.load_map_from_string(m, xml, True)
    else:
        mapnik.load_map(m, xml, True)
    if options.output:
        mapnik.save_map(m, options.output)
    else:
        if hasattr(mapnik,
                   'mapnik_version') and mapnik.mapnik_version() >= 700:
            print mapnik.save_map_to_string(m)
        else:
            sys.exit(
                color_text(
                    1,
                    'Minor error: printing XML to stdout requires Mapnik >=0.7.0, please provide a second argument to save the output to a file'
                ))
示例#2
0
def serialize(xml, options):
    try:
        try:
            import mapnik2 as mapnik
        except ImportError:
            import mapnik
    except ImportError:
        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",
                )
            )
def test_adding_datasource_to_layer():
    map_string = '''<?xml version="1.0" encoding="utf-8"?>
<Map>

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

</Map>
'''
    m = mapnik2.Map(256, 256)
    
    try:
        mapnik2.load_map_from_string(m, map_string)
        
        # validate it loaded fine
        eq_(m.layers[0].styles[0],'world_borders_style')
        eq_(m.layers[0].styles[1],'point_style')
        eq_(len(m.layers),1)
        
        # also assign a variable reference to that layer
        # below we will test that this variable references
        # the same object that is attached to the map
        lyr = m.layers[0]
    
        # ensure that there was no datasource for the layer...
        eq_(m.layers[0].datasource,None)
        eq_(lyr.datasource,None)
        
        # also note that since the srs was black it defaulted to wgs84
        eq_(m.layers[0].srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        eq_(lyr.srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
        
        # now add a datasource one...
        ds = mapnik2.Shapefile(file='../data/shp/world_merc.shp')
        m.layers[0].datasource = ds
        
        # now ensure it is attached
        eq_(m.layers[0].datasource.name(),"shape")
        eq_(lyr.datasource.name(),"shape")
        
        # and since we have now added a shapefile in spherical mercator, adjust the projection
        lyr.srs = '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
        
        # test that assignment
        eq_(m.layers[0].srs,'+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
        eq_(lyr.srs,'+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(e)
示例#4
0
文件: tile.py 项目: skripkar/noc
 def run(self):
     self.log("Loading map XML")
     self.m = mapnik2.Map(TS, TS)
     try:
         mapnik2.load_map_from_string(self.m, self.xml)
     except RuntimeError, why:
         logging.error("Cannot load map: %s" % why)
         os._exit(1)
示例#5
0
def test_adding_datasource_to_layer():
    map_string = '''<?xml version="1.0" encoding="utf-8"?>
<Map>

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

</Map>
'''
    m = mapnik2.Map(256, 256)
    
    mapnik2.load_map_from_string(m, map_string)
    
    # validate it loaded fine
    eq_(m.layers[0].styles[0],'world_borders_style')
    eq_(m.layers[0].styles[1],'point_style')
    eq_(len(m.layers),1)
    
    # also assign a variable reference to that layer
    # below we will test that this variable references
    # the same object that is attached to the map
    lyr = m.layers[0]

    # ensure that there was no datasource for the layer...
    eq_(m.layers[0].datasource,None)
    eq_(lyr.datasource,None)
    
    # also note that since the srs was black it defaulted to wgs84
    eq_(m.layers[0].srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    eq_(lyr.srs,'+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs')
    
    # now add a datasource one...
    ds = mapnik2.Shapefile(file='../data/shp/world_merc.shp')
    m.layers[0].datasource = ds
    
    # now ensure it is attached
    eq_(m.layers[0].datasource.name(),"shape")
    eq_(lyr.datasource.name(),"shape")
    
    # and since we have now added a shapefile in spherical mercator, adjust the projection
    lyr.srs = '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs'
    
    # test that assignment
    eq_(m.layers[0].srs,'+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
    eq_(lyr.srs,'+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs')
    
    
    
示例#6
0
def assert_loads_successfully(file):
    m = mapnik2.Map(512, 512)

    strict = True
    mapnik2.load_map(m, file, strict)
    
    # libxml2 is not smart about paths, and clips the last directory off
    # of a path if it does not end in a trailing slash
    base_path = os.path.dirname(file) + '/'
    mapnik2.load_map_from_string(m,open(file,'rb').read(),strict,base_path)
示例#7
0
def assert_loads_successfully(file):
    m = mapnik2.Map(512, 512)

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

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

    try:
        strict = True
        mapnik2.load_map(m, file, strict)
        
        # libxml2 is not smart about paths, and clips the last directory off
        # of a path if it does not end in a trailing slash
        base_path = os.path.dirname(file) + '/'
        mapnik2.load_map_from_string(m,open(file,'rb').read(),strict,base_path)
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(e)
示例#9
0
def test_load_save_load_map():
    map = mapnik2.Map(256,256)
    in_map = "../data/good_maps/glyph_symbolizer.xml"
    mapnik2.load_map(map, in_map)
    style = map.find_style('arrows')
    sym = style.rules[0].symbols[0]
    assert isinstance(sym, mapnik2.GlyphSymbolizer)
    assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH

    out_map = mapnik2.save_map_to_string(map).decode('utf8')
    map = mapnik2.Map(256,256)
    mapnik2.load_map_from_string(map, out_map.encode('utf8'))
    assert 'GlyphSymbolizer' in out_map
    # make sure non-ascii characters are well supported since most interesting
    # glyphs for symbology are usually in that range
    assert u'í' in out_map, out_map
示例#10
0
def test_load_save_load_map():
    map = mapnik2.Map(256, 256)
    in_map = "../data/good_maps/glyph_symbolizer.xml"
    mapnik2.load_map(map, in_map)
    style = map.find_style('arrows')
    sym = style.rules[0].symbols[0]
    assert isinstance(sym, mapnik2.GlyphSymbolizer)
    assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH

    out_map = mapnik2.save_map_to_string(map).decode('utf8')
    map = mapnik2.Map(256, 256)
    mapnik2.load_map_from_string(map, out_map.encode('utf8'))
    assert 'GlyphSymbolizer' in out_map
    assert 'RasterColorizer' in out_map
    # make sure non-ascii characters are well supported since most interesting
    # glyphs for symbology are usually in that range
    assert u'í' in out_map, out_map
示例#11
0
def test_filter_init():
    m = mapnik2.Map(1, 1)
    mapnik2.load_map_from_string(m, map_)
    filters = []
    filters.append(mapnik2.Filter("([region]>=0) and ([region]<=50)"))
    filters.append(mapnik2.Filter("(([region]>=0) and ([region]<=50))"))
    filters.append(mapnik2.Filter("((([region]>=0) and ([region]<=50)))"))
    filters.append(mapnik2.Filter('((([region]>=0) and ([region]<=50)))'))
    filters.append(mapnik2.Filter('''((([region]>=0) and ([region]<=50)))'''))
    filters.append(
        mapnik2.Filter('''
    ((([region]>=0)
    and
    ([region]<=50)))
    '''))
    filters.append(
        mapnik2.Filter('''
    ([region]>=0)
    and
    ([region]<=50)
    '''))
    filters.append(
        mapnik2.Filter('''
    ([region]
    >=
    0)
    and
    ([region]
    <= 
    50)
    '''))

    s = m.find_style('s')

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

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

    s = m.find_style('s2')

    eq_(s.filter_mode, mapnik2.filter_mode.FIRST)
示例#12
0
def test_filter_init():    
    m = mapnik2.Map(1,1)
    mapnik2.load_map_from_string(m,map_)
    filters = []
    filters.append(mapnik2.Filter("([region]>=0) and ([region]<=50)"))
    filters.append(mapnik2.Filter("(([region]>=0) and ([region]<=50))"))
    filters.append(mapnik2.Filter("((([region]>=0) and ([region]<=50)))"))
    filters.append(mapnik2.Filter('((([region]>=0) and ([region]<=50)))'))
    filters.append(mapnik2.Filter('''((([region]>=0) and ([region]<=50)))'''))
    filters.append(mapnik2.Filter('''
    ((([region]>=0)
    and
    ([region]<=50)))
    '''))
    filters.append(mapnik2.Filter('''
    ([region]>=0)
    and
    ([region]<=50)
    '''))
    filters.append(mapnik2.Filter('''
    ([region]
    >=
    0)
    and
    ([region]
    <= 
    50)
    '''))
    
    s = m.find_style('s')
    
    for r in s.rules:
        filters.append(r.filter)
    
    first = filters[0]
    for f in filters:
        eq_(str(first),str(f))
    
    s = m.find_style('s2')
    
    eq_(s.filter_mode,mapnik2.filter_mode.FIRST)
def test_load_save_load_map():
    map = mapnik2.Map(256,256)
    in_map = "../data/good_maps/glyph_symbolizer.xml"
    try:
        mapnik2.load_map(map, in_map)
        style = map.find_style('arrows')
        sym = style.rules[0].symbols[0]
        assert isinstance(sym, mapnik2.GlyphSymbolizer)
        assert sym.angle_mode == mapnik2.angle_mode.AZIMUTH
    
        out_map = mapnik2.save_map_to_string(map).decode('utf8')
        map = mapnik2.Map(256,256)
        mapnik2.load_map_from_string(map, out_map.encode('utf8'))
        assert 'GlyphSymbolizer' in out_map
        # make sure non-ascii characters are well supported since most interesting
        # glyphs for symbology are usually in that range
        assert u'í' in out_map, out_map
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(e)
示例#14
0
def test_map_init_from_string():
    map_string = '''<Map background-color="steelblue" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">
     <Style name="My Style">
      <Rule>
       <PolygonSymbolizer>
        <CssParameter name="fill">#f2eff9</CssParameter>
       </PolygonSymbolizer>
       <LineSymbolizer>
        <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter>
        <CssParameter name="stroke-width">0.1</CssParameter>
       </LineSymbolizer>
      </Rule>
     </Style>
     <Layer name="boundaries">
      <StyleName>My Style</StyleName>
       <Datasource>
        <Parameter name="type">shape</Parameter>
        <Parameter name="file">../../demo/data/boundaries</Parameter>
       </Datasource>
      </Layer>
    </Map>'''

    m = mapnik2.Map(600, 300)
    
    mapnik2.load_map_from_string(m, map_string)
    mapnik2.load_map_from_string(m, map_string, False, "")
    mapnik2.load_map_from_string(m, map_string, True, "")
    raise(Todo("Need to write more map property tests in 'object_test.py'..."))
示例#15
0
def test_map_init_from_string():
    map_string = '''<Map background-color="steelblue" base="./" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">
     <Style name="My Style">
      <Rule>
       <PolygonSymbolizer>
        <CssParameter name="fill">#f2eff9</CssParameter>
       </PolygonSymbolizer>
       <LineSymbolizer>
        <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter>
        <CssParameter name="stroke-width">0.1</CssParameter>
       </LineSymbolizer>
      </Rule>
     </Style>
     <Layer name="boundaries">
      <StyleName>My Style</StyleName>
       <Datasource>
        <Parameter name="type">shape</Parameter>
        <Parameter name="file">../../demo/data/boundaries</Parameter>
       </Datasource>
      </Layer>
    </Map>'''

    m = mapnik2.Map(600, 300)
    eq_(m.base, '')
    try:
        mapnik2.load_map_from_string(m, map_string)
        eq_(m.base, './')
        mapnik2.load_map_from_string(m, map_string, False, "") # this "" will have no effect
        eq_(m.base, './')
        try:
            mapnik2.load_map_from_string(m, map_string, False, "/tmp")
        except RuntimeError:
            pass # runtime error expected because shapefile path should be wrong and datasource will throw
        eq_(m.base, '/tmp') # /tmp will be set despite the exception because load_map mostly worked
        m.base = 'foo'
        mapnik2.load_map_from_string(m, map_string, True, ".")
        eq_(m.base, '.')
        raise(Todo("Need to write more map property tests in 'object_test.py'..."))
    except RuntimeError, e:
        # only test datasources that we have installed
        if not 'Could not create datasource' in str(e):
            raise RuntimeError(e)
示例#16
0
def test_map_init_from_string():
    map_string = '''<Map background-color="steelblue" base="./" srs="+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs">
     <Style name="My Style">
      <Rule>
       <PolygonSymbolizer>
        <CssParameter name="fill">#f2eff9</CssParameter>
       </PolygonSymbolizer>
       <LineSymbolizer>
        <CssParameter name="stroke">rgb(50%,50%,50%)</CssParameter>
        <CssParameter name="stroke-width">0.1</CssParameter>
       </LineSymbolizer>
      </Rule>
     </Style>
     <Layer name="boundaries">
      <StyleName>My Style</StyleName>
       <Datasource>
        <Parameter name="type">shape</Parameter>
        <Parameter name="file">../../demo/data/boundaries</Parameter>
       </Datasource>
      </Layer>
    </Map>'''

    m = mapnik2.Map(600, 300)
    eq_(m.base, '')
    mapnik2.load_map_from_string(m, map_string)
    eq_(m.base, './')
    mapnik2.load_map_from_string(m, map_string, False,
                                 "")  # this "" will have no effect
    eq_(m.base, './')
    try:
        mapnik2.load_map_from_string(m, map_string, False, "/tmp")
    except RuntimeError:
        pass  # runtime error expected because shapefile path should be wrong and datasource will throw
    eq_(
        m.base, '/tmp'
    )  # /tmp will be set despite the exception because load_map mostly worked
    m.base = 'foo'
    mapnik2.load_map_from_string(m, map_string, True, ".")
    eq_(m.base, '.')
    raise (
        Todo("Need to write more map property tests in 'object_test.py'..."))
示例#17
0
def metadata_image(bboxes, mapfile):
    """Create a metadata image"""

    from json import dumps as tojson
    import mapnik2 as mapnik

    features = []

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

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

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

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

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

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

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

    return image
示例#18
0
文件: tilep2.py 项目: amilna/iyo
def main(argv):
	b = "-180,-90,180,90"	
	i = ""
	o = ""
	l = "-1"
	   
	try:
	  opts, args = getopt.getopt(argv,"hb:i:o:l:",["bbox","inputXml","output","layerGrid"])
	except getopt.GetoptError:
	  print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>'
	  sys.exit(2)	  	
	  
	for opt, arg in opts:
	  if opt == '-h':
		 print 'tilep.py -b <bbox> -i <inputXml> -o <output> -l <layerGrid>'
		 sys.exit()
	  elif opt in ("-b", "--bbox"):
		 b = arg	  
	  elif opt in ("-i", "--inputXml"):
		 i = arg      
	  elif opt in ("-o", "--output"):
		 o = arg   			
	  elif opt in ("-l", "--layerGrid"):
		 l = arg   				 				
	
	box = []
	for s in b.split(",") :
		box.append(float(s))
		
	geo_extent = Box2d(box[0],box[1],box[2],box[3])		
	
	geo_proj = Projection('+init=epsg:4326')
	merc_proj = Projection('+init=epsg:3857')	

	transform = ProjTransform(geo_proj,merc_proj)
	merc_extent = transform.forward(geo_extent)	
	
	mp = mapnik2.Map(256,256)	
	
	#sys.exit(i)		
	
	if i.find('http') >= 0:				
		xmlurl=urllib2.urlopen(i)
		xmlstr=xmlurl.read()		
		mapnik2.load_map_from_string(mp,xmlstr)		
		xmldoc = minidom.parseString(xmlstr)
	else:
		mapnik2.load_map(mp, i)	
		xmldoc = minidom.parse(i)		
		
		
	mp.zoom_to_box(merc_extent)
	
	printed = 0	
	if o == 'png':			
		im = Image(mp.width,mp.height)		
		mapnik2.render(mp,im)
		fd, path = tempfile.mkstemp()		
					    
		os.write(fd,im.tostring('png'))
		os.fsync(fd)		
		print path								
	elif o == 'json':	
		printed = 1				
	else:			
		image = o+".png"
		if not os.path.exists(os.path.dirname(image)):
			try:
				os.makedirs(os.path.dirname(image))
			except:
				pass					
		mapnik2.render_to_file(mp, image)
		if l == '-1':
			print image
	
	lgrids = []	
	if l != '-1':
		for s in l.split(",") :
			lgrids.append(int(s))
	else:
		sys.exit()
				
	itemlist = xmldoc.getElementsByTagName('Layer') 
	
	fields = []
	resolution = 4 #Pixel resolution of output.   
	printed = 0
	for ly in lgrids :	
		dat = itemlist[ly].getElementsByTagName('Datasource')[0] 
		par = dat.getElementsByTagName('Parameter')	
		for s in par :
			if s.attributes['name'].value == 'fields':			
				text = s.childNodes[0].nodeValue.encode("utf-8")			
				#print "fields "+text
				fields = text.split(",")				
			if s.attributes['name'].value == 'resolution':			
				res = s.childNodes[0].nodeValue.encode("utf-8")			
				#print "resolution "+res
				resolution = int(res)	
						
		layer_index = ly #First layer on the map - index in m.layers
		key = "__id__"  #Field used for the key in mapnik2 (should probably be unique)		
		
		enfix = ""
		if ly > 0:
			enfix = "_"+str(ly)
			
		d = mapnik2.render_grid(mp, layer_index, key, resolution, fields) #returns a dictionary		
		d = "grid("+json.dumps(d)+")"
		
		if o == 'json' and printed == 0:				
			print d
			printed = 1
		elif o == 'png':
			printed = 1				
		else:				
			print d
			f = open(o+enfix+".json",'wb')
			f.write(d)	
			f.close()