def main: map = mapscript.mapObj() map.name = 'Test Map' map.setSize(300, 300) map.setExtent(-180.0,-90.0,180.0,90.0) map.imagecolor.setRGB(80, 180, 80) map.units = mapscript.MS_DD layer = mapscript.layerObj(map) layer.name = "regioni" layer.type = mapscript.MS_LAYER_POLYGON layer.status = mapscript.MS_DEFAULT layer.data = os.getcwd() + '/../data/regioni' class1 = mapscript.classObj(layer) class1.name = "Regioni" style = mapscript.styleObj(class1) style.outlinecolor.setRGB(100, 100, 100) style.color.setRGB(200, 200, 200) extent = layer.getExtent() map.setExtent(extent.minx, extent.miny, extent.maxx, extent.maxy) mapimage = map.draw() mapimage.save(os.getcwd() + '/../images/mapscript_map.png')
def set_cartography(self, layer): """ Sets the cartograhy for this layer TODO: This currently sets cartograpy to None, but should be a lookup to a set of cartographies or be a dynamically created one """ # Select cartograpy or use default one carto_requested = self.request.GET.get("cartography", "") if carto_requested: self.cartograpy = None # Class and style settings if self.cartography: for cart in self.cartography: # Set categorization category = mapscript.classObj(layer) category.setExpression(cart["expression"]) category.name = cart["name"] # Set category style style = mapscript.styleObj(category) style.color.setHex(to_hex(cart["color"])) else: category = mapscript.classObj(layer) category.name = layer.name style = mapscript.styleObj(category) style.color.setHex("#FF00FF") return layer
def set_cartography(self, layer): """ Sets the cartograhy for this layer TODO: This currently sets cartograpy to None, but should be a lookup to a set of cartographies or be a dynamically created one """ # Select cartograpy or use default one carto_requested = self.request.GET.get('cartography', '') if carto_requested: self.cartograpy = None # Class and style settings if self.cartography: for cart in self.cartography: # Set categorization category = mapscript.classObj(layer) category.setExpression(cart['expression']) category.name = cart['name'] # Set category style style = mapscript.styleObj(category) style.color.setHex(to_hex(cart['color'])) else: category = mapscript.classObj(layer) category.name = layer.name style = mapscript.styleObj(category) style.color.setHex('#FF00FF') return layer
def get_vector_layer(self, field_name): """ Connect this layer to a vector data model. """ # Get base layer layer = self.get_base_layer() layer.type = self.layer_types[field_name] # Set connection to DB layer.setConnectionType(mapscript.MS_POSTGIS, '') connection_template = ( 'host={host} dbname={dbname} user={user} ' 'port={port} password={password}' ) layer.connection = connection_template.format( host=settings.DATABASES['default']['HOST'], dbname=settings.DATABASES['default']['NAME'], user=settings.DATABASES['default']['USER'], port=settings.DATABASES['default']['PORT'], password=settings.DATABASES['default']['PASSWORD'] ) # Select data column layer.data = 'geom FROM {0}'.format(self.model._meta.db_table) # Set class item if self.classitem: layer.classitem = self.classitem # Cartography settings if self.cartography: for cart in self.cartography: # Set categorization and name category = mapscript.classObj(layer) category.setExpression(cart.get('expression', '')) category.name = cart.get('name', cart.get('expression', '')) # Set category style style = mapscript.styleObj(category) style.color.setHex(to_hex(cart.get('color', '#777777'))) style.outlinecolor.setHex(to_hex(cart.get('outlinecolor', '#000000'))) style.width = cart.get('width', 1) # Set symbol name now, this will be linked to the map level # symbolset when registering layers in map. if cart.has_key('symbol'): style.symbolname = cart.get('symbol') else: category = mapscript.classObj(layer) category.name = layer.name style = mapscript.styleObj(category) style.color.setHex('#777777') style.outlinecolor.setHex('#000000') style.width = 1 return layer
def get_classObj(self, layerObj=None, **kwargs): if layerObj: classObj = ms.classObj(layerObj) else: classObj = ms.classObj() if kwargs.get('expression'): classObj.setExpression(kwargs['expression']) if kwargs.get('style'): styleObj = self.get_styleObj(classObj=classObj, **kwargs['style']) return classObj
def get_vector_layer(self, field_name): """ Connect this layer to a vector data model. """ # Get base layer layer = self.get_base_layer() layer.type = self.layer_types[field_name] # Set connection to DB layer.setConnectionType(mapscript.MS_POSTGIS, '') connection_template = ('host={host} dbname={dbname} user={user} ' 'port={port} password={password}') layer.connection = connection_template.format( host=settings.DATABASES['default']['HOST'], dbname=settings.DATABASES['default']['NAME'], user=settings.DATABASES['default']['USER'], port=settings.DATABASES['default']['PORT'], password=settings.DATABASES['default']['PASSWORD']) # Select data column layer.data = 'geom FROM {0}'.format(self.model._meta.db_table) # Set class item if self.classitem: layer.classitem = self.classitem # Cartography settings if self.cartography: for cart in self.cartography: # Set categorization and name category = mapscript.classObj(layer) category.setExpression(cart.get('expression', '')) category.name = cart.get('name', cart.get('expression', '')) # Set category style style = mapscript.styleObj(category) style.color.setHex(to_hex(cart.get('color', '#777777'))) style.outlinecolor.setHex( to_hex(cart.get('outlinecolor', '#000000'))) style.width = cart.get('width', 1) # Set symbol name now, this will be linked to the map level # symbolset when registering layers in map. if cart.has_key('symbol'): style.symbolname = cart.get('symbol') else: category = mapscript.classObj(layer) category.name = layer.name style = mapscript.styleObj(category) style.color.setHex('#777777') style.outlinecolor.setHex('#000000') style.width = 1 return layer
def get_vector_layer(self, field_name): """ Connect this layer to a vector data model. """ # Get base layer layer = self.get_base_layer() layer.type = self.layer_types[field_name] # Set connection to DB layer.setConnectionType(mapscript.MS_POSTGIS, "") layer.connection = "host={host} dbname={dbname} user={user} " "port={port} password={password}".format( host=settings.DATABASES["default"]["HOST"], dbname=settings.DATABASES["default"]["NAME"], user=settings.DATABASES["default"]["USER"], port=settings.DATABASES["default"]["PORT"], password=settings.DATABASES["default"]["PASSWORD"], ) # Select data column layer.data = "geom FROM {0}".format(self.model._meta.db_table) # Set class item if self.classitem: layer.classitem = self.classitem # Cartography settings if self.cartography: for cart in self.cartography: # Set categorization and name category = mapscript.classObj(layer) category.setExpression(cart.get("expression", "")) category.name = cart.get("name", cart.get("expression", "")) # Set category style style = mapscript.styleObj(category) style.color.setHex(to_hex(cart.get("color", "#777777"))) style.outlinecolor.setHex(to_hex(cart.get("outlinecolor", "#000000"))) style.width = cart.get("width", 1) # Set symbol name now, this will be linked to the map level # symbolset when registering layers in map. if cart.has_key("symbol"): style.symbolname = cart.get("symbol") else: category = mapscript.classObj(layer) category.name = layer.name style = mapscript.styleObj(category) style.color.setHex("#777777") style.outlinecolor.setHex("#000000") style.width = 1 return layer
def get_vector_layer(data, name, group, crs=None): """ Mapscript Layer для векторных данных. """ layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_POLYGON layer.status = mapscript.MS_ON # mapscript.MS_DEFAULT layer.name = name layer.group = group layer.setProjection('EPSG:4326') layer.metadata.set('wms_srs', 'EPSG:4326') layer.metadata.set('wms_title', name) for polygon in data: shape = mapscript.shapeObj_fromWKT(polygon.wkt) layer.addFeature(shape) # layer.setExtent({'minx': 3, 'miny': 3, 'maxx': 3, 'maxy': 3}) # layer.setExtent(1, 2, 3, 4) # layer.setProjection('EPSG:4326') # layer.setProcessing("SCALE=0,255") # layer.setProcessing("DITHER=YES") # layer.setProcessing("RESAMPLE=BILINEAR") # BILINEAR, AVERAGE, NEAREST # layer.setProcessing("EXTENT_PRIORITY=WORLD") # layer.setProcessing("LOAD_FULL_RES_IMAGE=NO") # layer.setProcessing("LOAD_WHOLE_IMAGE=NO") c = mapscript.classObj(layer) style = mapscript.styleObj(c) fill_color = mapscript.colorObj(0, 255, 0) out_color = mapscript.colorObj(0, 0, 255) style.color = fill_color style.outlinecolor = out_color style.opacity = 50 layer.opacity = 50 return layer
def testConstructorWithArg(self): lyr = mapscript.layerObj() lyr.name = 'foo' c = mapscript.classObj(lyr) assert c.thisown == 1 assert c.layer.name == lyr.name assert c.numstyles == 0
def testDrawMapWithSecondPolygon(self): """draw a blue polygon and a red polygon""" p = self.map.getLayerByName('POLYGON') ip = mapscript.layerObj(self.map) ip.type = mapscript.MS_LAYER_POLYGON ip.status = mapscript.MS_DEFAULT c0 = mapscript.classObj(ip) # turn off first polygon layer's color p.getClass(0).getStyle(0).color.setRGB(-1, -1, -1) # copy this style to inline polygon layer, then change outlinecolor c0.insertStyle(p.getClass(0).getStyle(0)) st0 = c0.getStyle(0) st0.outlinecolor.setRGB(255, 0, 0) # pull out the first feature from polygon layer, shift it # and use this as an inline feature in new layer p.open() p.template = "FAKE" # set a template so the layer can be queried p.queryByIndex(self.map, -1, 0, mapscript.MS_TRUE) res = p.getResult(0) s0 = p.getShape(res) p.close() r0 = s0.bounds r1 = mapscript.rectObj(r0.minx - 0.1, r0.miny - 0.1, r0.maxx - 0.1, r0.maxy - 0.1) s1 = r1.toPolygon() ip.addFeature(s1) img = self.map.draw() img.save('test_drawmapw2ndpolygon.png')
def __agregar_simbologia_basica__(layer): class1 = mapscript.classObj(layer) class1.name = 'Default' style = mapscript.styleObj(class1) if layer.type == mapscript.MS_LAYER_POINT: style.symbolname = 'circle' style.size = 8 style.minsize = 8 style.maxsize = 10 style.maxwidth = 2 style.outlinecolor.setRGB(30, 30, 30) style.color.setRGB(31, 120, 180) elif layer.type == mapscript.MS_LAYER_POLYGON: style.outlinecolor.setRGB(126, 109, 83) style.color.setRGB(210, 182, 138) elif layer.type == mapscript.MS_LAYER_LINE: style.color.setRGB(76, 38, 0) style.width = 4 style.minwidth = 4 style.maxwidth = 6 style2 = mapscript.styleObj(class1) style2.color.setRGB(255, 206, 128) style2.width = 2 style2.minwidth = 2 style2.maxwidth = 4 elif layer.type == mapscript.MS_LAYER_RASTER: layer.offsite = mapscript.colorObj(0, 0, 0)
def serializeSingleSymbolRenderer(self, renderer): """Serialize a QGis single symbol renderer into a MapServer class""" msClass = mapscript.classObj(self.msLayer) for sym in renderer.symbols(): SymbolLayerSerializer(sym, msClass, self.msLayer, self.msMap)
def testDrawMapWithSecondPolygon(self): """draw a blue polygon and a red polygon""" p = self.map.getLayerByName('POLYGON') ip = mapscript.layerObj(self.map) ip.type = mapscript.MS_LAYER_POLYGON ip.status = mapscript.MS_DEFAULT c0 = mapscript.classObj(ip) # turn off first polygon layer's color p.getClass(0).getStyle(0).color.setRGB(-1, -1, -1) # copy this style to inline polygon layer, then change outlinecolor c0.insertStyle(p.getClass(0).getStyle(0)) st0 = c0.getStyle(0) st0.outlinecolor.setRGB(255, 0, 0) # pull out the first feature from polygon layer, shift it # and use this as an inline feature in new layer p.open() p.template = "FAKE" # set a template so the layer can be queried p.queryByIndex(self.map, -1, 0, mapscript.MS_TRUE) res = p.getResult(0) s0 = p.getShape(res) p.close() r0 = s0.bounds r1 = mapscript.rectObj(r0.minx-0.1, r0.miny-0.1, r0.maxx-0.1, r0.maxy-0.1) s1 = r1.toPolygon() ip.addFeature(s1) img = self.map.draw() img.save('test_drawmapw2ndpolygon.png')
def build(self): cl = mapscript.classObj() cl.name = self.name cl.setExpression(self.expression) for style in self.styleobj_set.all(): cl.insertStyle(style.build()) return cl
def testCloneClass(self): """check attributes of a cloned class""" c = mapscript.classObj() c.minscaledenom = 5.0 clone = c.clone() assert clone.thisown == 1 assert clone.minscaledenom == 5.0
def _get_unique_mapfile(self, classification): layerobj = self._get_layer_stub() attribute = classification['attribute'] column = self._get_column(attribute) if column is None: raise ValueError("column %s not found in datasource %s" % (attribute, self.name)) values = self.get_distinct_values(attribute) layerobj.classitem = attribute theme = self._get_theme(classification, len(values)) for value in values: color = theme.pop(0) classobj = mapscript.classObj() layerobj.insertClass(classobj) styleobj = self._get_default_style() styleobj.color.setRGB(color[0], color[1], color[2]) classobj.insertStyle(styleobj) if column['type'] == 'numeric': classobj.name = '%s' % (value) classobj.setExpression('([%s]==%s)' % (attribute, value)) else: classobj.name = '%s' % (value) classobj.setExpression('("[%s]"=="%s")' % (attribute.encode('utf8'), value)) return mapserializer.layerobj_to_dict(layerobj, None)
def testClassObj(self): self.initMap() layer = mapscript.layerObj(self.map) clazz = mapscript.classObj(layer) self.map = None layer = None assert str(clazz.p_layer).find('mapscript.layerObj') != -1 gc.collect() assert clazz.layer is not None, clazz.layer
def testClassInsert(self): """classObj insert at end""" self.initMap() clazz = mapscript.classObj() clazz.minscaledenom = 666 assert clazz.refcount == 1, clazz.refcount idx = self.map.getLayer(1).insertClass(clazz) assert clazz.refcount == 2, clazz.refcount assert self.map.getLayer(1).getClass(idx).refcount == 3, self.map.getLayer(1).getClass(idx).refcount assert self.map.getLayer(1).getClass(idx).minscaledenom == 666, self.map.getLayer(1).getClass(idx).minscaledenom
def create_default_class(): c = mapscript.classObj() c.setExpression("fooexpression") create_default_label(c.label) c.maxscaledenom = 2000 c.minscaledenom = 100 c.name = "fooname" c.setText("[footext]") c.title = "footitle" c.insertStyle(create_default_style()) return c
def get_map_image_from_wms(wms_parameters=None, habitat_dao=None, filters=None): # Initialize mapscript map object from the habitat mapfile template. mapfile = "%s/habitat.map" % os.path.abspath(os.path.dirname(__file__)) ms_map = mapscript.mapObj(mapfile) layer = mapscript.layerObj() layer.name = "habitat" layer.setProjection('init=epsg:4326') layer.status = mapscript.MS_DEFAULT layer.setConnectionType(mapscript.MS_POSTGIS, '') connection_str = habitat_dao.get_mapserver_connection_string() layer.connection = connection_str layer.data = habitat_dao.get_mapserver_data_string(filters=filters) layer.type = mapscript.MS_LAYER_POLYGON # Create classes for types of substrates. substrate_styles= [ {'name': 'S1', 'color': '8DD3C7'}, {'name': 'S2', 'color': 'FFFFB3'}, {'name': 'S3', 'color': 'BEBADA'}, {'name': 'S4', 'color': 'FB8072'}, {'name': 'S5', 'color': '80B1D3'}, ] for ss in substrate_styles: clz = mapscript.classObj() clz.name = ss['name'] expression = "('[substrate_id]' eq '%s')" % ss['name'] clz.setExpression(expression) style = mapscript.styleObj() rgb_color = hex_to_rgb(ss['color']) style.color= mapscript.colorObj(*rgb_color) clz.insertStyle(style) layer.insertClass(clz) ms_map.insertLayer(layer) # Build WMS request from parameters. wms_request = mapscript.OWSRequest() for k, v in wms_parameters: wms_request.setParameter(k,v) # Load the parameters into the map. ms_map.loadOWSParameters(wms_request) # Draw the map. ms_image = ms_map.draw() # Return the raw image. return ms_image.getBytes()
def _get_default_mapfile_excerpt(self): """ Given an OGR string, an OGR connection and an OGR layer, create and return a representation of a MapFile LAYER block. """ layerobj = self._get_layer_stub() classobj = mapscript.classObj() layerobj.insertClass(classobj) styleobj = self._get_default_style() classobj.insertStyle(styleobj) return mapserializer.layerobj_to_dict(layerobj,None)
def ShapefileLayer(mapObj, imageryShp, filters, rgb): layerObj = mapscript.layerObj(mapObj) layerObj.name = "Sentinel2Shapefile" layerObj.status = mapscript.MS_ON layerObj.type = mapscript.MS_LAYER_POLYGON layerObj.setProjection("AUTO") layerObj.data = imageryShp layerObj.setFilter(filters) classObj = mapscript.classObj(layerObj) styleObj = mapscript.styleObj(classObj) styleObj.outlinecolor = mapscript.colorObj(rgb[0], rgb[1], rgb[2])
def _get_default_mapfile_excerpt(self): """ Given an OGR string, an OGR connection and an OGR layer, create and return a representation of a MapFile LAYER block. """ layerobj = self._get_layer_stub() classobj = mapscript.classObj() layerobj.insertClass(classobj) styleobj = self._get_default_style() classobj.insertStyle(styleobj) return mapserializer.layerobj_to_dict(layerobj, None)
def testLayerInsertClassAtZero(self): """insert class at index 0""" n = self.layer.numclasses new_class = mapscript.classObj() new_class.name = 'foo' new_index = self.layer.insertClass(new_class, 0) assert new_index == 0 assert self.layer.numclasses == n + 1 c = self.layer.getClass(new_index) assert c.thisown == 1 assert c.name == new_class.name
def __init__(self,datasource,extent,layername,layerftype): #from mapscript import * import mapscript from time import time tmap = mapscript.mapObj() print "checkpoint 1" map.setSize(400,400) #ext = rectObj(-180,-90,180,90) ext = mapscript.rectObj(extent[0],extent[2],extent[1],extent[3]) # some trouble with some bad extents in my test data map.extent = ext map.units = mapscript.MS_DD # should be programmatically set lay = mapscript.layerObj(map) lay.name = "Autolayer" lay.units = mapscript.MS_DD if (layerftype == 'RASTER'): lay.data = datasource.GetDescription() else: lay.data = datasource.GetName() print lay.data lay.status = mapscript.MS_DEFAULT cls = mapscript.classObj(lay) sty = mapscript.styleObj() col = mapscript.colorObj(0,0,0) # symPoint = mapscript.symbolObj map.setSymbolSet("symbols/symbols_basic.sym") if (layerftype == 'POINT'): lay.type = mapscript.MS_LAYER_POINT sty.setSymbolByName = "achteck" sty.width = 100 sty.color = col elif (layerftype == 'LINE'): lay.type = mapscript.MS_LAYER_LINE sty.setSymbolByName = "punkt" sty.width = 5 sty.color = col elif (layerftype == 'POLYGON'): lay.type = mapscript.MS_LAYER_POLYGON sty.setSymbolByName = "circle" sty.width = 10 sty.outlinecolor = col elif (layerftype == 'RASTER'): lay.type = mapscript.MS_LAYER_RASTER sty.setSymbolByName = "squares" sty.size = 10 sty.color = col #sty.setSymbolByName(map,symname) #sty.size = symsize cls.insertStyle(sty) try: img = map.draw() img.save(str(time()) + "auto.gif") map.save(str(time()) + "auto.map") except MapServerError: return None
def testClassInsertAtMiddle(self): """classObj insert at pos. 1""" self.initMap() clazz = mapscript.classObj() clazz.minscaledenom = 666 assert clazz.refcount == 1, clazz.refcount idx = self.map.getLayer(1).insertClass(clazz, 1) assert idx == 1, idx assert clazz.refcount == 2, clazz.refcount assert self.map.getLayer(1).getClass(idx).refcount == 3, self.map.getLayer(1).getClass(idx).refcount assert self.map.getLayer(1).getClass(idx).thisown, self.map.getLayer(1).getClass(idx).thisown assert self.map.getLayer(1).getClass(idx).minscaledenom == 666, self.map.getLayer(1).getClass(idx).minscaledenom
def testClassInsert(self): """classObj insert at end""" self.initMap() clazz = mapscript.classObj() clazz.minscaledenom = 666 assert clazz.refcount == 1, clazz.refcount idx = self.map.getLayer(1).insertClass(clazz) assert clazz.refcount == 2, clazz.refcount assert self.map.getLayer(1).getClass( idx).refcount == 3, self.map.getLayer(1).getClass(idx).refcount assert self.map.getLayer(1).getClass( idx).minscaledenom == 666, self.map.getLayer(1).getClass( idx).minscaledenom
def default_class_style(self, col_name): # return a default class for styling based on the value of a specified # column styleobj = mapscript.styleObj() styleobj.mincolor = mapscript.colorObj(255, 255, 255) styleobj.maxcolor = mapscript.colorObj(0, 128, 255) if 'min' in self._data and 'max' in self._data: styleobj.minvalue = self._data['min'] styleobj.maxvalue = self._data['max'] styleobj.rangeitem = col_name clsobj = mapscript.classObj() clsobj.name = "-" clsobj.insertStyle(styleobj) return clsobj
def addPlaneSymbol(self,position): """Adds the plane symbol at the indicated position""" pt = mapscript.pointObj() pt.x = position[0] #lat pt.y = position[1] #lon # project our point into the mapObj's projection #ddproj = mapscript.projectionObj('proj=latlong,ellps=WGS84') #http://www.mass.gov/mgis/dd-over.htm ddproj = mapscript.projectionObj('proj=lcc,ellps=GRS80') origproj = mapscript.projectionObj(self.map.getProjection()) pt.project(ddproj,origproj) # create the symbol using the image planeSymbol = mapscript.symbolObj('from_img') planeSymbol.type = mapscript.MS_SYMBOL_PIXMAP planeImg = mapscript.imageObj('images/map-plane-small.png','GD/PNG') #TODO: need to rotate plane to current heading planeSymbol.setImage(planeImg) symbol_index = self.map.symbolset.appendSymbol(planeSymbol) # create a shapeObj out of our location point so we can # add it to the map. self.routeLine = mapscript.lineObj() self.routeLine.add(pt) routeShape=mapscript.shapeObj(mapscript.MS_SHAPE_POINT) routeShape.add(self.routeLine) routeShape.setBounds() # create our inline layer that holds our location point self.planeLayer = mapscript.layerObj(None) self.planeLayer.addFeature(routeShape) self.planeLayer.setProjection(self.map.getProjection()) self.planeLayer.name = "plane" self.planeLayer.type = mapscript.MS_LAYER_POINT self.planeLayer.connectiontype=mapscript.MS_INLINE self.planeLayer.status = mapscript.MS_ON self.planeLayer.transparency = mapscript.MS_GD_ALPHA # add the image symbol we defined above to the inline layer. planeClass = mapscript.classObj(None) planeClass.name='plane' style = mapscript.styleObj(None) style.symbol = self.map.symbolset.index('from_img') planeClass.insertStyle(style) self.planeLayer.insertClass(planeClass) self.map.insertLayer(self.planeLayer) if debug: print "added plane layer, layerorder=",self.map.getLayerOrder()
def getStyle(): style_obj = styleObj() style_obj.rangeitem = "pixel" style_obj.maxcolor = colorObj(175, 240, 233) style_obj.mincolor = colorObj(255, 255, 179) style_obj.maxvalue = 1 style_obj.minvalue = -47 clz_obj = classObj() clz_obj.setExpression("([pixel] >= -47 AND [pixel] <= 1)") clz_obj.insertStyle(style_obj) return clz_obj
def testClassInsertAtMiddle(self): """classObj insert at pos. 1""" self.initMap() clazz = mapscript.classObj() clazz.minscaledenom = 666 assert clazz.refcount == 1, clazz.refcount idx = self.map.getLayer(1).insertClass(clazz, 1) assert idx == 1, idx assert clazz.refcount == 2, clazz.refcount assert self.map.getLayer(1).getClass( idx).refcount == 3, self.map.getLayer(1).getClass(idx).refcount assert self.map.getLayer(1).getClass(idx).thisown, self.map.getLayer( 1).getClass(idx).thisown assert self.map.getLayer(1).getClass( idx).minscaledenom == 666, self.map.getLayer(1).getClass( idx).minscaledenom
def testSettingFonts(self): mo = mapscript.mapObj() assert mo.fontset.numfonts == 0 mo.fontset.fonts.set('Vera', os.path.join(TESTS_PATH, 'vera', 'Vera.ttf')) # NB: this does *not* increment the fonset.numfonts -- new bug mo.setSize(300, 300) mo.setExtent(-1.0, -1.0, 1.0, 1.0) lo = mapscript.layerObj() lo.type = mapscript.MS_LAYER_POINT lo.connectiontype = mapscript.MS_INLINE lo.status = mapscript.MS_DEFAULT co = mapscript.classObj() lbl = mapscript.labelObj() lbl.type = mapscript.MS_TRUETYPE lbl.font = 'Vera' lbl.size = 10 lbl.color.setHex('#000000') co.addLabel(lbl) so = mapscript.styleObj() so.symbol = 0 so.color.setHex('#000000') co.insertStyle(so) lo.insertClass(co) li = mo.insertLayer(lo) lo = mo.getLayer(li) point = mapscript.pointObj(0, 0) line = mapscript.lineObj() line.add(point) shape = mapscript.shapeObj(lo.type) shape.add(line) shape.setBounds() shape.text = 'Foo' shape.classindex = 0 lo.addFeature(shape) im = mo.draw() # im = mo.prepareImage() # shape.draw(mo, lo, im) im.save('testSettingFonts.png')
def draw_map_wfs(name, save=0): # print("making map in thread %s" % (name)) mo = mapscript.mapObj(TESTMAPFILE) # WFS layer lo = mapscript.layerObj() lo.name = 'cheapo_wfs' lo.setProjection('+init=epsg:4326') lo.connectiontype = mapscript.MS_WFS lo.connection = 'http://zcologia.com:9001/mapserver/members/features.rpy?' lo.metadata.set('wfs_service', 'WFS') lo.metadata.set('wfs_typename', 'users') lo.metadata.set('wfs_version', '1.0.0') lo.type = mapscript.MS_LAYER_POINT lo.status = mapscript.MS_DEFAULT lo.labelitem = 'zco:mid' so1 = mapscript.styleObj() so1.color.setHex('#FFFFFF') so1.size = 9 so1.symbol = 1 # mo.symbolset.index('circle') so2 = mapscript.styleObj() so2.color.setHex('#333333') so2.size = 7 so2.symbol = 1 # mo.symbolset.index('circle') co = mapscript.classObj() co.label.type = mapscript.MS_BITMAP co.label.size = mapscript.MS_SMALL co.label.color.setHex('#000000') co.label.outlinecolor.setHex('#FFFFFF') co.label.position = mapscript.MS_AUTO co.insertStyle(so1) co.insertStyle(so2) lo.insertClass(co) mo.insertLayer(lo) if not mo.web.imagepath: mo.web.imagepath = os.environ.get('TEMP', None) or INCOMING mo.debug = mapscript.MS_ON im = mo.draw() if save: im.save('threadtest_wfs_%s.png' % (name))
def testPointDraw(self): """Can create a point, add to a layer, and draw it directly""" map_string = """ MAP EXTENT 0 0 90 90 SIZE 500 500 SYMBOL NAME "circle" TYPE ELLIPSE POINTS 1 1 END FILLED true END LAYER NAME "punkt" STATUS ON TYPE POINT END END""" test_map = mapscript.fromstring(map_string) layer = test_map.getLayerByName('punkt') cls = mapscript.classObj() style = mapscript.styleObj() style.outlinecolor.setHex('#00aa00ff') style.size = 10 style.setSymbolByName(test_map, 'circle') cls.insertStyle(style) class_idx = layer.insertClass(cls) point = mapscript.pointObj(45, 45) img = test_map.prepareImage() point.draw(test_map, layer, img, class_idx, "test") filename = 'testDrawPoint.png' with open(filename, 'wb') as fh: img.write(fh) if have_image: pyimg = Image.open(filename) assert pyimg.size == (500, 500)
def get_pg_layer(data, name, group, connection, query_filter=None, crs=None, fill_color=None, out_color=None, opacity=None): """ Mapscript Layer для векторных данных, хранящихся в Postgres. """ layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_POLYGON layer.status = mapscript.MS_ON # mapscript.MS_DEFAULT layer.name = name layer.group = group layer.setProjection('EPSG:4326') layer.metadata.set('wms_srs', 'EPSG:4326') layer.metadata.set('wms_title', name) layer.connectiontype = mapscript.MS_POSTGIS layer.connection = connection layer.data = data # "geom from data" # status = layer.setFilter(query_filter) # "id = 123" # layer.setExtent({'minx': 3, 'miny': 3, 'maxx': 3, 'maxy': 3}) # layer.setExtent(1, 2, 3, 4) # layer.setProjection('EPSG:4326') # layer.setProcessing("SCALE=0,255") # layer.setProcessing("DITHER=YES") # layer.setProcessing("RESAMPLE=BILINEAR") # BILINEAR, AVERAGE, NEAREST # layer.setProcessing("EXTENT_PRIORITY=WORLD") # layer.setProcessing("LOAD_FULL_RES_IMAGE=NO") # layer.setProcessing("LOAD_WHOLE_IMAGE=NO") c = mapscript.classObj(layer) style = mapscript.styleObj(c) if fill_color: fill_color = mapscript.colorObj(*fill_color) style.color = fill_color if out_color: out_color = mapscript.colorObj(*out_color) style.outlinecolor = out_color if opacity: # style.opacity = opacity layer.opacity = opacity return layer
def get_color_class(attr=None, cmin=None, cmax=None, hsv=None): clz = mapscript.classObj() clz.name = "{} to {}".format(cmin, cmax) style = mapscript.styleObj() rgb = [int(c) for c in colorsys.hsv_to_rgb(*hsv)] style.color= mapscript.colorObj(*rgb) clz.insertStyle(style) criteria = [] if cmin != None: criteria.append("[{}] >= {}".format(attr, cmin)) if cmax != None: criteria.append("[{}] < {}".format(attr, cmax)) if criteria: expression = "({})".format(' AND '.join(criteria)) clz.setExpression(expression) return clz
def _get_quantile_mapfile(self,classification): layerobj = self._get_layer_stub() intervals = int(classification['intervals']) attribute = classification['attribute'] bounds = self._get_classification_bounds(attribute, intervals) theme = self._get_theme(classification, len(bounds)+1) for i in range(0, len(bounds)+1): color = theme[i] classobj = mapscript.classObj() layerobj.insertClass(classobj) if i<len(bounds): classobj.setExpression('([%s]<%s)'%(attribute, _nice_float(bounds[i]))) classobj.name = '%s < %s'%(attribute, _nice_float(bounds[i])) else: classobj.name = '%s >= %s'%(attribute, _nice_float(bounds[i-1])) styleobj = mapscript.styleObj() styleobj.color.setRGB(color[0],color[1],color[2]) classobj.insertStyle(styleobj) return mapserializer.layerobj_to_dict(layerobj,None)
def _add_north_arrow(self, msmap, map_height): north_arrow_layer = mapscript.layerObj() north_arrow_layer.transform = False north_arrow_layer.name = 'north_arrow' north_arrow_layer.type = mapscript.MS_LAYER_POINT north_arrow_layer.status = 1 new_class = mapscript.classObj() new_style = mapscript.styleObj() new_style.setSymbolByName(msmap, 'northarrow1') li = msmap.insertLayer(north_arrow_layer) ci = msmap.getLayer(li).insertClass(new_class) si = msmap.getLayer(li).getClass(ci).insertStyle(new_style) point = mapscript.pointObj() #place north arrow at the bottom of the image: point.x = 30 point.y = map_height-30 north_arrow_layer.addFeature(point.toShape())
def serializeCategorizedSymbolRenderer(self, renderer): """Serialize a QGis categorized symbol renderer into MapServer classes""" attr = renderer.usedAttributes()[0] i = 0 for cat in renderer.categories(): msClass = mapscript.classObj(self.msLayer) # XXX: type(cat.value()) differs whether the script is being run in QGis or as # a standalone PyQGis application, so we convert it accordingly. cv = cat.value() cv = cv.toString() if isinstance(cv, QVariant) else unicode(cv) msClass.setExpression((u'("[%s]" = "%s")' % (attr, cv)).encode('utf-8')) SymbolLayerSerializer(renderer.symbols()[i], msClass, self.msLayer, self.msMap) #add number to class name msClass.name+='_'+str(i) i = i + 1
def generate_layer(self,tipo, num): lay = mapscript.layerObj() lay.name = "lay1" lay.status = mapscript.MS_DEFAULT #defaul # lay.data = self.image.path lay.data = self.image if tipo == "tiff": lay.type = mapscript.MS_LAYER_RASTER self.bandset(lay, num) elif tipo == "polygon": st = mapscript.styleObj() #st.outlinecolor = mapscript.colorObj(100,100,100) st.color = mapscript.colorObj(255,255,255) cl = mapscript.classObj() cl.insertStyle(st) lay.type = mapscript.MS_LAYER_LINE lay.insertClass(cl) return lay
def _draw_extents_as_rectangle(self, msmap): #generate a new temporary layer and draw a polygon on it: new_layer = mapscript.layerObj() new_layer.name = 'temp' new_layer.type = mapscript.MS_LAYER_POLYGON new_layer.status = 1 new_class = mapscript.classObj() #generate a new style object: new_style = mapscript.styleObj() c = mapscript.colorObj() c.red = 50 #218 c.green = 50 #124 c.blue = 50 #12 new_style.outlinecolor = c new_style.width = 2 li = msmap.insertLayer(new_layer) ci = msmap.getLayer(li).insertClass(new_class) si = msmap.getLayer(li).getClass(ci).insertStyle(new_style) box = mapscript.rectObj(self.west, self.south, self.east, self.north) new_layer.addFeature(box.toPolygon())
def _get_quantile_mapfile(self, classification): layerobj = self._get_layer_stub() intervals = int(classification['intervals']) attribute = classification['attribute'] bounds = self._get_classification_bounds(attribute, intervals) theme = self._get_theme(classification, len(bounds) + 1) for i in range(0, len(bounds) + 1): color = theme[i] classobj = mapscript.classObj() layerobj.insertClass(classobj) if i < len(bounds): classobj.setExpression('([%s]<%s)' % (attribute, _nice_float(bounds[i]))) classobj.name = '%s < %s' % (attribute, _nice_float(bounds[i])) else: classobj.name = '%s >= %s' % (attribute, _nice_float(bounds[i - 1])) styleobj = mapscript.styleObj() styleobj.color.setRGB(color[0], color[1], color[2]) classobj.insertStyle(styleobj) return mapserializer.layerobj_to_dict(layerobj, None)
def testGetSetAttributes(self): c = mapscript.classObj() val = '/tmp/legend.png' c.keyimage = val assert c.keyimage == val c.debug = mapscript.MS_TRUE assert c.debug == mapscript.MS_TRUE val = 'Group1' c.group = val assert c.group == val val = 10000 c.maxscaledenom = val assert c.maxscaledenom == val val = 3 c.minfeaturesize = val assert c.minfeaturesize == val val = 1000 c.minscaledenom = val assert c.minscaledenom == val val = 'Class1' c.name = val assert c.name == val c.status = mapscript.MS_OFF assert c.status == mapscript.MS_OFF val = 'template.html' c.template = val assert c.template == val val = 'Title1' c.title = val assert c.title == val
def serializeGraduatedSymbolRenderer(self, renderer): """Serialize a QGis graduated symbol renderer into MapServer classes""" attr = unicode(renderer.usedAttributes()[0]) i = 0 for range in renderer.ranges(): msClass = mapscript.classObj(self.msLayer) # We use '>=' instead of '>' when defining the first class to also include the lowest # value of the range in the expression. msClass.setExpression((u'(([%s] %s %f) And ([%s] <= %f))' % ( \ attr, \ '>=' if (i == 0) else '>', \ range.lowerValue(), \ attr, \ range.upperValue() \ )).encode('utf-8')) SymbolLayerSerializer(renderer.symbols()[i], msClass, self.msLayer, self.msMap) #add number to class name msClass.name+='_'+str(i) i = i + 1
def SqliteLayer(mapObj, imageryShp, filters, rgb): layerObj = mapscript.layerObj(mapObj) layerObj.name = "Footprint" # layerObj.debug = 5 layerObj.status = mapscript.MS_ON layerObj.type = mapscript.MS_LAYER_POLYGON #layerObj.setProjection("AUTO") # layerObj.setProjection("init=epsg:3857") layerObj.connectiontype = mapscript.MS_OGR layerObj.connection = imageryShp # layerObj.setGeomTransform("( generalize([shape],[map_cellsize]*10 ))") layerObj.data = 'select the_geom from sentinel2 where ' + filters layerObj.metadata.set('wms_title', 'Footprint') layerObj.metadata.set('wms_enable_request', '*') layerObj.metadata.set('wms_srs', "EPSG:3857") layerObj.metadata.set('wms_format', 'image/png') layerObj.metadata.set('wms_abstract', "Sentinel 2 Footprints") layerObj.metadata.set('wms_attribution_title', "JRC,JEODPP,ESA,COPERNICUS") classObj = mapscript.classObj(layerObj) styleObj = mapscript.styleObj(classObj) styleObj.outlinecolor = mapscript.colorObj(rgb[0], rgb[1], rgb[2])
def setUp(self): # Inline feature layer self.ilayer = mapscript.layerObj() self.ilayer.type = mapscript.MS_LAYER_POLYGON self.ilayer.status = mapscript.MS_DEFAULT self.ilayer.connectiontype = mapscript.MS_INLINE cs = 'f7fcfd, e5f5f9, ccece6, 99d8c9, 66c2a4, 41ae76, 238b45, 006d2c, 00441b' colors = ['#' + h for h in cs.split(', ')] for i in range(9): # Make a class for feature ci = self.ilayer.insertClass(mapscript.classObj()) co = self.ilayer.getClass(ci) si = co.insertStyle(mapscript.styleObj()) so = co.getStyle(si) so.color.setHex(colors[i]) li = co.addLabel(mapscript.labelObj()) lbl = co.getLabel(li) lbl.color.setHex('#000000') lbl.outlinecolor.setHex('#FFFFFF') lbl.type = mapscript.MS_BITMAP lbl.size = mapscript.MS_SMALL # The shape to add is randomly generated xc = 4.0*(random() - 0.5) yc = 4.0*(random() - 0.5) r = mapscript.rectObj(xc-0.25, yc-0.25, xc+0.25, yc+0.25) s = r.toPolygon() # Classify s.classindex = i s.text = "F%d" % (i) # Add to inline feature layer self.ilayer.addFeature(s)
def warp(self): """Warp given URL and SRS Returns: mapscript.ImageObj """ if not self.url or not self.sourceSRS: return self.map = mapscript.mapObj() self.map.setSize(int(self.url.getArgument("width")),int(self.url.getArgument("height"))) (minx,miny,maxx,maxy) = map(lambda x: float(x), self.url.getArgument("bbox").split(",")) self.map.extent = mapscript.rectObj(minx,miny,maxx,maxy) self.map.web.imagepath=tempfile.mkdtemp() self.map.setProjection(self.targetSRS.__str__()) self.layer = mapscript.layerObj(self.map) self.layer.type = mapscript.MS_LAYER_RASTER self.layer.connection = self.url.getConnection() self.layer.status = mapscript.MS_DEFAULT self.layer.setConnectionType(mapscript.MS_WMS,None) self.layer.setMetaData("wms_srs",self.sourceSRS.__str__()) self.layer.setMetaData("wms_name", self.url.getArgument("layers")) self.layer.setMetaData("wms_server_version",self.url.getArgument("version")) # WMS 1.3.0 is not supported by MapServer < 6.0 # http://trac.osgeo.org/mapserver/ticket/3039 if self.url.getArgument("version") == "1.3.0": self.layer.setMetaData("wms_server_version","1.1.1") if self.sourceSRS.authority == "CRS" and self.sourceSRS.code == "84": self.layer.setMetaData("wms_srs","EPSG:4326") self.layer.setMetaData("wms_exceptions_format",self.url.getArgument("exceptions")) self.layer.setMetaData("wms_formatlist",self.url.getArgument("format")) self.layer.setMetaData("wms_style",self.url.getArgument("style")) self.layer.setMetaData("wms_transparent",self.url.getArgument("transparent")) self.layer.setProjection(self.sourceSRS.__str__()) self.layer.debug = 5 if self.url.getArgument("format") == "image/png": self.map.outputformat.imagemode = mapscript.MS_IMAGEMODE_RGBA if self.url.getArgument("format") == "image/jpg": self.layer.setMetaData("wms_formatlist","image/jpeg") self.map.selectOutputFormat("image/jpeg") else: self.map.selectOutputFormat(self.url.getArgument("format")) self.map.outputformat.transparent= 1 try: # draw the map #self.map.save("/tmp/pokus2.map") image = self.map.draw() if image: return image except : # something failed during the layer drawing. try to print the # error to stderr as well as generate new image with the error # message exc_type, exc_value, exc_traceback = sys.exc_info() traceback.print_exc(file=sys.stderr) traceback.print_tb(exc_traceback, limit=1, file=sys.stderr) self.map.removeLayer(0) self.map.setFontSet(os.path.join(os.path.abspath(os.path.dirname(__file__)),"fonts.txt")) self.map.outputformat.transparent= 0 self.layer = mapscript.layerObj(self.map) self.layer.type = mapscript.MS_LAYER_ANNOTATION #self.layer.transform = mapscript.MS_OFF line = mapscript.lineObj() line.add(mapscript.pointObj(minx+(maxx-minx)/2.,miny+(maxy-miny)/2.)) feature = mapscript.shapeObj() feature.add(line) self.layer.addFeature(feature) self.layer.labelcache = mapscript.MS_TRUE classobj = mapscript.classObj(self.layer) text = "" ## try to guess, where the problem is for i in textwrap.wrap(str(exc_value),70): text += i+"\n" classobj.setText(text) classobj.label.font = "sans" classobj.label.type = mapscript.MS_TRUETYPE classobj.label.antialias = mapscript.MS_FALSE classobj.label.size = 12 classobj.label.position = mapscript.MS_CC #classobj.label.partials = mapscript.MS_FALSE classobj.label.force = mapscript.MS_TRUE self.layer.status = mapscript.MS_ON #self.map.save("/tmp/pokus3.map") image = self.map.draw() return image
"name": zoo._("Drawn line") } } filename=conf["main"]["tmpPath"]+"/result_"+conf["senv"]["MMID"]+".json" fileo=open(filename,"w") fileo.write(json.dumps(geojson)) fileo.close() layer.connection=None #layer.setConnectionType(mapscript.MS_OGR,filename) #layer.data="OGRGeoJSON" layer.data=None layer.tileitem=None layer.units=mapscript.MS_PIXELS layer.sizeunits=mapscript.MS_PIXELS layer.toleranceunits=mapscript.MS_PIXELS tmpClass=mapscript.classObj(layer) tmpClass.name=zoo._("Drawn line") tmpStyle=mapscript.styleObj(tmpClass) tmpStyle.updateFromString('STYLE COLOR 255 202 75 WIDTH 2 END') layer.setProjection("+init=epsg:4326") layer.status=mapscript.MS_ON layer.updateFromString("LAYER CONNECTIONTYPE OGR CONNECTION \""+filename+"\" END") # Fix extent based on zoom Level if not(inputs.has_key("zoom")): import math n0=math.log((((20037508.34*2)*csize[0])/(256*(float(ext[2])-float(ext[0])))),2) m0=math.log(((20037508.34*csize[1])/(256*(float(ext[3])-float(ext[1])))),2) print >> sys.stderr,"+++++++++++++++++++++++++++++++++++++" if n0 > m0: zl=n0