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 get_map(self, tile): import mapscript wms = MapServer.get_map(self, tile) bounds = tile.bounds() # XXX FIXME: I don't think this will work with other projections? scale = self.INCHES_PER_DEGREE * (bounds[2]-bounds[0])/tile.size()[0] sql = """SELECT dr.id, layername, data, type, min_scale, max_scale, srs, offsite, ds.name, description, attribution, url FROM view_datarecord dr, view_recordtypes rt, view_datasource ds WHERE type_id = rt.id AND datasource_id = ds.id AND bbox && 'BOX3D(%s %s, %s %s)'::box3d AND %f >= min_scale and %f <= max_scale AND active ORDER BY data_resolution DESC""" % (bounds + (scale, scale)) cursor = self.db.cursor() cursor.execute(sql) for id, name, data, type, min_scale, max_scale, srs, offsite, \ title, description, attribution, url in cursor: raster = mapscript.layerObj(wms) raster.name = "layer_%s" % id raster.group = "world" raster.type = mapscript.MS_LAYER_RASTER raster.status = mapscript.MS_DEFAULT if srs and type == "WMS": raster.setProjection( "+init=" + srs.lower() ) else: raster.setProjection( "+init=" + tile.layer.srs.lower() ) if offsite: offsite = map(int, offsite.split(" ")) raster.offsite = mapscript.colorObj(offsite[0], offsite[1], offsite[2]) else: raster.offsite = mapscript.colorObj(0,0,0) metadata = { "srs": "EPSG:4326", "format": "image/jpeg", "server_version": "1.1.1", "name": name, "title": title, "abstract": description, "attribution_title": attribution, "attribution_onlineresource": url } for key, val in metadata.items(): raster.metadata.set("wms_" + key, val) if type == "GeoTIFF": raster.data = os.path.join(self.image_path, data) elif type == "Tile Index": raster.tileindex = os.path.join(self.image_path, data) # XXX BUG: we don't set tileitem b/c it's not in the d/b elif type == "WMS": raster.connectiontype = mapscript.MS_WMS raster.connection = data return wms
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 SqliteTileIndexLayer(mapObj, imageryShp, layername, filters, Bands, Scale1, Scale2, Scale3): mapObj.shapepath = '' layerObj = mapscript.layerObj(mapObj) layerObj.name = 'raster_tindex' layerObj.status = mapscript.MS_OFF layerObj.type = mapscript.MS_LAYER_POLYGON # layerObj.setProjection("AUTO") layerObj.connectiontype = mapscript.MS_OGR layerObj.connection = imageryShp layerObj.data = 'select the_geom,src_srs,locationVRT as location from sentinel2 where ' + filters + ' GROUP BY MGRSID,Orbit HAVING MAX(RANK) ' layerObj1 = mapscript.layerObj(mapObj) layerObj1.name = layername layerObj1.status = mapscript.MS_ON #layerObj1.debug = 1 layerObj1.type = mapscript.MS_LAYER_RASTER layerObj1.setProjection("AUTO") layerObj1.tileindex = 'raster_tindex' layerObj1.tilesrs = "src_srs" layerObj1.tileitem = "location" layerObj1.setProcessingKey("BANDS", BandsToIndeces(Bands)) layerObj1.setProcessingKey("SCALE_1", Scale1) layerObj1.setProcessingKey("SCALE_2", Scale2) layerObj1.setProcessingKey("SCALE_3", Scale3) layerObj1.offsite = mapscript.colorObj(0, 0, 0) layerObj1.metadata.set('wms_title', 'Sentinel2b') layerObj1.metadata.set('wms_enable_request', 'GetMap') layerObj1.metadata.set('wms_srs', "EPSG:3857") layerObj1.metadata.set('wms_format', 'image/png')
def SqliteQuickLooksLayer(mapObj, imageryShp, filters, layername): mapObj.shapepath = '' layerObj = mapscript.layerObj(mapObj) layerObj.name = 'raster_tindex' layerObj.status = mapscript.MS_OFF layerObj.type = mapscript.MS_LAYER_POLYGON layerObj.connectiontype = mapscript.MS_OGR layerObj.connection = imageryShp layerObj.data = 'select the_geom,locationQKL as location from sentinel2 where ' + filters + ' GROUP BY MGRSID,Orbit HAVING MAX(RANK)' layerObj.metadata.set('wms_title', 'raster_tindex') layerObj.metadata.set('wms_enable_request', '*') layerObj.metadata.set('wms_srs', "EPSG:3857") layerObj.metadata.set('wms_format', 'image/png') layerObj1 = mapscript.layerObj(mapObj) layerObj1.name = layername layerObj1.status = mapscript.MS_ON #layerObj1.debug = 1 layerObj1.type = mapscript.MS_LAYER_RASTER layerObj1.tileindex = 'raster_tindex' layerObj1.tileitem = "location" layerObj1.offsite = mapscript.colorObj(0, 0, 0) layerObj1.metadata.set('wms_title', 'Image TOA Reflectance L1C') layerObj1.metadata.set('wms_enable_request', '*') layerObj1.metadata.set('wms_srs', "EPSG:3857") layerObj1.metadata.set('wms_format', 'image/png')
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 __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 build(self): """ Build a mapObj """ uri = reverse("wms_endpoint") m = mapscript.mapObj() m.name = self.name m.setProjection("init=epsg:{}".format(self.projection)) m.shapepath = "" m.units = self.units m.setMetaData("ows_title", self.name) m.setMetaData("ows_onlineresource", "http://{}{}".format(settings.HOST_NAME, uri)) m.setMetaData("wms_srs", "EPSG:{}".format(self.projection)) m.setMetaData("wms_enable_request", self.ows_enable_request) m.setMetaData("wms_encoding", "utf-8") m.imagetype = "png" m.extent = self.extent.build() m.setSize(*self.MAP_SIZE) if self.image_color is not None: m.imageColor = self.image_color.build() else: m.imageColor = mapscript.colorObj(255, 255, 255) for layer in self.layers.all(): m.insertLayer(layer.build()) return m
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 RasterClassLayer(mapObj, raster, layername): layerObj = mapscript.layerObj(mapObj) layerObj.name = layername layerObj.status = mapscript.MS_ON #layerObj.debug = 5 layerObj.type = mapscript.MS_LAYER_RASTER layerObj.setProjection("AUTO") layerObj.data = raster layerObj.offsite = mapscript.colorObj(0, 0, 0)
def testDrawPoints(self): """DrawProgrammedStylesTestCase.testDrawPoints: point drawing with styles works as advertised""" points = [mapscript.pointObj(-0.2, 51.6), mapscript.pointObj(0.0, 51.2), mapscript.pointObj(0.2, 51.6)] colors = [mapscript.colorObj(255, 0, 0), mapscript.colorObj(0, 255, 0), mapscript.colorObj(0, 0, 255)] img = self.map.prepareImage() layer = self.map.getLayerByName('POINT') # layer.draw(self.map, img) class0 = layer.getClass(0) for i in range(len(points)): style0 = class0.getStyle(0) style0.color = colors[i] # style0.color.pen = -4 assert style0.color.toHex() == colors[i].toHex() points[i].draw(self.map, layer, img, 0, "foo") img.save('test_draw_points.png')
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_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 __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 ClassificationLayer(mapObj, imageryShp, layername, filters): layerObj = mapscript.layerObj(mapObj) layerObj.name = layername layerObj.status = mapscript.MS_ON #layerObj.debug = 5 layerObj.type = mapscript.MS_LAYER_RASTER layerObj.setProjection("AUTO") layerObj.tileindex = imageryShp layerObj.tileitem = "LOCATION" layerObj.tilesrs = "src_srs" layerObj.setFilter(filters) layerObj.offsite = mapscript.colorObj(0, 0, 0)
def RasterLayer(mapObj, raster, layername, Bands, Scale1, Scale2, Scale3): layerObj = mapscript.layerObj(mapObj) layerObj.name = layername layerObj.status = mapscript.MS_ON #layerObj.debug = 1 layerObj.type = mapscript.MS_LAYER_RASTER layerObj.setProjection("AUTO") layerObj.data = raster layerObj.setProcessingKey("BANDS", BandsToIndeces(Bands)) layerObj.setProcessingKey("SCALE_1", Scale1) layerObj.setProcessingKey("SCALE_2", Scale2) layerObj.setProcessingKey("SCALE_3", Scale3) layerObj.offsite = mapscript.colorObj(0, 0, 0)
def testDrawPoints(self): """DrawProgrammedStylesTestCase.testDrawPoints: point drawing with styles works as advertised""" points = [ mapscript.pointObj(-0.2, 51.6), mapscript.pointObj(0.0, 51.2), mapscript.pointObj(0.2, 51.6) ] colors = [ mapscript.colorObj(255, 0, 0), mapscript.colorObj(0, 255, 0), mapscript.colorObj(0, 0, 255) ] img = self.map.prepareImage() layer = self.map.getLayerByName('POINT') # layer.draw(self.map, img) class0 = layer.getClass(0) for i in range(len(points)): style0 = class0.getStyle(0) style0.color = colors[i] # style0.color.pen = -4 assert style0.color.toHex() == colors[i].toHex() points[i].draw(self.map, layer, img, 0, "foo") img.save('test_draw_points.png')
def generate_map(self, in_t, minx, miny, maxx, maxy,lay): map = mapscript.mapObj() map.name = "Map" map.setSize(self.sizex,self.sizey) map.setImageType(self.outtype) map.imagecolor = mapscript.colorObj(0,0,0) map.units = mapscript.MS_METERS map.extent = mapscript.rectObj(minx,miny,maxx,maxy) map.web = mapscript.webObj() map.web.template = self.templatepath map.web.imagepath = self.imagespath map.web.imageurl = "/tmp" map.shapepath = DIRECTORIO_BASE+"maps/" map.insertLayer(lay) return map
def initMap(): """ Initialize a generic mapObj item """ #from datetime import datetime mapObj = mapscript.mapObj() # mapObj.debug = 5 # mapObj.setConfigOption("MS_ERRORFILE", GLOBALS['S2']['root_path']+"S2_scripts/ms_error.txt") #mapObj.name = 'map_'+datetime.utcnow().strftime('%Y%m%d%H%M%S%f') mapObj.name = 'Sentinel2_map' mapObj.transparent = mapscript.MS_TRUE mapObj.imagecolor = mapscript.colorObj(0, 0, 0) mapObj.maxsize = 2500 # mapObj.outputformat=mapscript.outputFormatObj("GD/JPEG") # mapObj.outputformat.mimetype="image/jpeg;" # mapObj.outputformat.name="JPEG" # mapObj.outputformat.driver="GD/JPEG" # mapObj.outputformat.extension="jpg" # mapObj.outputformat.setOption("QUALITY","90") # mapObj.outputformat.transparent = mapscript.MS_TRUE # mapObj.outputformat.imagemode= mapscript.MS_IMAGEMODE_RGBA mapObj.outputformat = mapscript.outputFormatObj("AGG/PNG") mapObj.outputformat.name = "PNG" mapObj.outputformat.mimetype = "image/png" mapObj.outputformat.driver = "AGG/PNG" mapObj.outputformat.extension = "png" mapObj.outputformat.setOption("COMPRESSION", "7") mapObj.outputformat.setOption("QUANTIZE_FORCE", "ON") mapObj.outputformat.transparent = mapscript.MS_TRUE mapObj.outputformat.imagemode = mapscript.MS_IMAGEMODE_RGBA # WMS mapObj.web.metadata.set('wms_title', 'Public API for Sentinel2 imagery') mapObj.web.metadata.set('wms_onlineresource', GLOBALS['mapserver_url'] + "wms_sentinel2.py?") #mapObj.web.metadata.set("wms_feature_info_mime_type","text/html") #webObj.metadata.set('wms_onlineresource','http://cidportal.jrc.ec.europa.eu/forobsdev/cgi-bin/mapserv?') mapObj.web.metadata.set('wms_enable_request', "*") mapObj.web.metadata.set('wms_srs', "EPSG:3857") mapObj.web.metadata.set('wms_abstract', "WMS serving Sentinel 2 full resolution imagery") return mapObj
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 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 get_mapObj(self, **kwargs): if kwargs.get('mapfile'): mapObj = ms.mapObj(kwargs['mapfile']) else: mapObj = ms.mapObj() if kwargs.has_key('extent'): mapObj.extent = self.get_rectObj(kwargs['extent']) else: if not mapObj.extent: mapObj.extent = self.get_rectObj() if kwargs.has_key('imagecolor'): mapObj.imagecolor = ms.colorObj(*kwargs['imagecolor']) if kwargs.has_key('projection'): mapObj.setProjection(kwargs['projection']) else: if not mapObj.getProjection(): mapObj.setProjection("init=epsg:4326") for attr in ['width', 'height']: if kwargs.has_key(attr): setattr(mapObj, attr, kwargs[attr]) if kwargs.get('apply_sld'): mapObj.applySLD(kwargs['apply_sld']) if kwargs.get('apply_sld_url'): mapObj.applySLDUrl(kwargs['apply_sld_url']) if not mapObj.name: mapObj.name = "MAP" if not mapObj.status: mapObj.status = ms.MS_ON if not mapObj.web.metadata.get('ows_enable_request'): mapObj.web.metadata.set('ows_enable_request', '*') return mapObj
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 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 add_layer_obj(self, map): """ Create mapserver layer object. The raster data for the layer is located at filename, which should be an absolute path on the local filesystem. """ # inspect data if we haven't yet self._inspect_data() # create a layer object layer = mapscript.layerObj() # configure layer # NAME layer.name = "DEFAULT" # TODO: filename?, real title? # TYPE layer.type = mapscript.MS_LAYER_RASTER # STATUS layer.status = mapscript.MS_ON # mark layer as queryable layer.template = "dummy" # anything non null and with length > 0 works here # CONNECTION_TYPE local|ogr? # layer.setConnectionType(MS_RASTER) MS_OGR? # DATA layer.data = self.filename.encode('utf-8') layer.tolerance = 10.0 # TODO: this should be dynamic based on zoom level # layer.toleranceunits = mapscript.MS_PIXELS # PROJECTION ... should we ste this properly? crs = self._data['crs'] layer.setProjection("init={}".format(crs)) # METADATA # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE layer.setMetaData("gml_include_items", "all") # allow raster queries layer.setMetaData("wms_include_items", "all") # projection to serve layer.setMetaData("wms_srs", "EPSG:4326 EPSG:3857") # title required for GetCapabilities layer.setMetaData("wms_title", "BCCVL Layer") # TODO: metadata # other things like title, author, attribution etc... # OPACITY # TODO: this should probably be up to the client? # layer.setOpacity(70) # If data type is not integer: if self._data['datatype'] not in (gdal.GDT_Byte, gdal.GDT_UInt16, gdal.GDT_Int16, gdal.GDT_UInt32, gdal.GDT_Int32): # mapservers does the right thing with these processing # instructions setting scale, skips the integer processing step and # reads the raster as float layer.addProcessing("SCALE=AUTO,AUTO") layer.addProcessing("NODATA=AUTO") # CLASSITEM, CLASS # TODO: if we have a STYLES parameter we should add a STYLES element # here if not (self.request.params.get('STYLES') or 'SLD' in self.request.params or 'SLD_BODY' in self.request.params): # set some default style if the user didn't specify any' # STYLE styleobj = mapscript.styleObj() styleobj.mincolor = mapscript.colorObj(255, 255, 255) styleobj.maxcolor = mapscript.colorObj(0, 128, 255) if self._data: styleobj.minvalue = self._data['min'] styleobj.maxvalue = self._data['max'] styleobj.rangeitem = "[pixel]" clsobj = mapscript.classObj() clsobj.name = "-" # clsobj.setExpression("([pixel]>0)") clsobj.insertStyle(styleobj) # layer.classitem = "[pixel]" layer.insertClass(clsobj) ret = map.insertLayer(layer) sld = self.request.params.get('SLD_BODY') sld_url = self.request.params.get('SLD') if sld_url: map.applySLDURL(sld_url) elif sld: map.applySLD(sld) if ((sld or sld_url) and (self._data['datatype'] == gdal.GDT_Byte and self._data['nodata'] is not None)): # if we have 8bit data, mapserver ignores the NODATA value, so # let's classify it as transparent styleobj = mapscript.styleObj() styleobj.color = mapscript.colorObj(0, 0, 0, 0) styleobj.rangeitem = "[pixel]" clsobj = mapscript.classObj() clsobj.name = 'NODATA' clsobj.setExpression( "([pixel] = {})".format(int(self._data['nodata']))) clsobj.insertStyle(styleobj) layer.insertClass(clsobj, 0) return ret
def testColorObjSetHexBadly(self): """invalid hex color string raises proper error""" c = mapscript.colorObj() self.assertRaises(mapscript.MapServerError, c.setHex, '#fffffg')
def _get_map(self): """ Generate a mapserver mapObj. """ # create a mapscript map from scratch map = mapscript.mapObj() # Configure the map # NAME map.name = "BCCVLMap" # EXTENT ... in projection units (we use epsg:4326) WGS84 map.extent = mapscript.rectObj(-180.0, -90.0, 180.0, 90.0) # map.extent = mapscript.rectObj(-20026376.39, -20048966.10, 20026376.39, 20048966.10) # UNITS ... in projection units map.units = mapscript.MS_DD # SIZE map.setSize(256, 256) # PROJECTION ... WGS84 map.setProjection("init=epsg:4326") # IMAGETYPE map.selectOutputFormat("PNG24") # PNG, PNG24, JPEG map.outputformat.imagemode = mapscript.MS_IMAGEMODE_RGBA map.outputformat.transparent = mapscript.MS_ON # TRANSPARENT ON map.transparent = mapscript.MS_ON # IMAGECOLOR 255 255 255 # map.imagecolor = mapscript.colorObj(255, 255, 255) ... initial color if transparent is on # SYMBOLSET (needed to draw circles for CSV points) self._update_symbol_set(map) # metadata: wms_feature_info_mime_type text/htm/ application/json # WEB # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE map.setMetaData("wms_enable_request", "*") map.setMetaData("wms_title", "BCCVL WMS Server") # allow reprojection to Web Mercator map.setMetaData("wms_srs", "EPSG:4326 EPSG:3857") # wms_enable_request enough? map.setMetaData("ows_enable_request", "*") onlineresource = urlparse.urlunsplit( (self.request.scheme, "{}:{}".format(self.request.host, self.request.host_port), self.request.path, urllib.urlencode((('DATA_URL', self.request.params.get('DATA_URL').encode('utf-8')), )), "")) map.setMetaData("wms_onlineresource", onlineresource) # TODO: metadata # title, author, xmp_dc_title # wms_onlineresource ... help to generate GetCapabilities request # ows_http_max_age ... WMS client caching hints http://www.mnot.net/cache_docs/#CACHE-CONTROL # ows_lsd_enabled ... if false ignore SLD and SLD_BODY # wms_attribution_xxx ... do we want attribution metadata? # SCALEBAR if False: # LABEL sbl = mapscript.labelObj() sbl.color = mapscript.colorObj(0, 0, 0) sbl.antialias = mapscript.MS_TRUE sbl.size = mapscript.MS_LARGE sb = mapscript.scalebarObj() sb.label = sbl sb.status = mapscript.MS_ON map.scalebar = sb # LEGEND if False: # LABEL legl = mapscript.labelObj() legl.color = mapscript.colorObj(64, 64, 64) legl.antialias = mapscript.MS_TRUE legl.offsetx = -23 legl.offsety = -1 leg = mapscript.legendObj() leg.keysizex = 32 leg.keysizey = 10 leg.keyspacingx = 5 leg.keyspacingy = -2 leg.status = mapscript.MS_ON map.legend = leg return map
def add_layer_obj(self, map): """Create mapserver layer object. The data is assumed to be a csv file with column 'lon' and 'lat' describing ponit features. """ # inspect data if we haven't yet self._inspect_data() # create a layer object layer = mapscript.layerObj() # configure layer # NAME layer.name = "DEFAULT" # TODO: filename?, real title? # TYPE # TODO: this supports only POINT datasets for now,... should detect # this somehow layer.type = mapscript.MS_LAYER_POINT # STATUS layer.status = mapscript.MS_ON # mark layer as queryable layer.template = "query" # anything non null and with length > 0 works here # CONNECTION_TYPE local|ogr? layer.setConnectionType(mapscript.MS_OGR, None) # TODO: the VRT source works fine, but maybe converting the VRT to a # real shapefile with ogr2ogr would spped up rendering? (or use a # sqlite/spatiallite datasource?) # TODO: check if GDAL dies and kills whole mapserver process in case # the csv file is not valid or contains broken values # layer.setConnectionType(MS_RASTER) MS_OGR? # TODO: other elements to consider: # Metadata ... on Datasource and LAyer # OpenOptions ... only gdal >= 2.0 # FID ... ?? # Style ... ??? # FeatureCount # ExtentXMien, ExtentXMax, ExtentYMin, ExtentYMax layer.connection = """\ <OGRVRTDataSource> <OGRVRTLayer name='{0}'> <SrcDataSource>{1}</SrcDataSource> <GeometryType>wkbPoint</GeometryType> <LayerSRS>EPSG:4326</LayerSRS> <GeometryField name='location' encoding='PointFromColumns' x='lon' y='lat'/> </OGRVRTLayer> </OGRVRTDataSource>""".format( escape(os.path.splitext(os.path.basename( self.filename))[0]).replace("'", "'"), escape(self.filename)) # PROJECTION ... should we ste this properly? # TODO: this always assume epsg:4326 layer.setProjection("init={}".format(self._data['crs'])) # METADATA # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE layer.setMetaData("gml_include_items", "all") layer.setMetaData("wms_include_items", "all") layer.setMetaData("wms_title", "BCCVL Occurrences") # can be a space separated list layer.setMetaData("wms_srs", self._data['crs']) # TODO: metadata # other things like title, author, attribution etc... if not (self.request.params.get('STYLES') or 'SLD' in self.request.params or 'SLD_BODY' in self.request.params): # set some default style if the user didn't specify any' # STYLE styleobj = mapscript.styleObj() styleobj.color = mapscript.colorObj(255, 50, 50) styleobj.minsize = 2 styleobj.maxsize = 50 styleobj.size = 5 styleobj.symbol = map.symbolset.index('circle') clsobj = mapscript.classObj() clsobj.name = "record" clsobj.insertStyle(styleobj) layer.insertClass(clsobj) ret = map.insertLayer(layer) # apply SLD if given sld = self.request.params.get('SLD_BODY') sld_url = self.request.params.get('SLD') if sld_url: map.applySLDURL(sld_url) elif sld: map.applySLD(sld) return ret
def testColorObjSetHexLower(self): """a color can be set using lower case hex""" c = mapscript.colorObj() c.setHex('#ffffff64') assert (c.red, c.green, c.blue, c.alpha) == (255, 255, 255, 100)
def get_colorObj(self, r=None, b=None, g=None): return ms.colorObj(int(r), int(b), int(g))
outputFormat=mapscript.outputFormatObj("GD/PNG") outputFormat.name="png24" outputFormat.setMimetype("image/png") outputFormat.imagemode=1 outputFormat.setExtension("png") mapobj.legend.status=1 mapobj.legend.keysizex=100 mapobj.legend.keysizey=30 mapobj.legend.keyspacingy=20 mapobj.legend.width=100 mapobj.setSize(600,1200) mapobj.setExtent(132771,447652,134477,451064) mapobj.setOutputFormat(outputFormat) style=mapscript.styleObj() style.symbolname="point5" style.color=mapscript.colorObj(225,0,0) cls=mapscript.classObj() cls.insertStyle(style) cls.name="testclass" cls.setExpression("(4 + 4)") mapobj.setSymbolSet('test_symbols.set') #! /usr/bin/python
def testColorObjConstructorArgs(self): """a color can be initialized with arguments""" c = mapscript.colorObj(1, 2, 3, 4) assert (c.red, c.green, c.blue, c.alpha) == (1, 2, 3, 4)
def testColorObjToHex(self): """a color can be outputted as hex""" c = mapscript.colorObj(255, 255, 255) assert c.toHex() == '#ffffff'
def _get_map(self): """ Generate a mapserver mapObj. """ # create a mapscript map from scratch map = mapscript.mapObj() # Configure the map # NAME map.name = "BCCVLMap" # EXTENT ... in projection units (we use epsg:4326) WGS84 map.extent = mapscript.rectObj(-180.0, -90.0, 180.0, 90.0) # map.extent = mapscript.rectObj(-20026376.39, -20048966.10, 20026376.39, 20048966.10) # UNITS ... in projection units map.units = mapscript.MS_DD # SIZE map.setSize(256, 256) # PROJECTION ... WGS84 map.setProjection("init=epsg:4326") # IMAGETYPE map.selectOutputFormat("PNG24") # PNG, PNG24, JPEG map.outputformat.imagemode = mapscript.MS_IMAGEMODE_RGBA map.outputformat.transparent = mapscript.MS_ON # TRANSPARENT ON map.transparent = mapscript.MS_ON # IMAGECOLOR 255 255 255 # map.imagecolor = mapscript.colorObj(255, 255, 255) ... initial color if transparent is on # SYMBOLSET (needed to draw circles for CSV points) self._update_symbol_set(map) # metadata: wms_feature_info_mime_type text/htm/ application/json # WEB # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE map.setMetaData("wms_enable_request", "*") map.setMetaData("wms_title", "BCCVL WMS Server") # allow reprojection to Web Mercator map.setMetaData("wms_srs", "EPSG:4326 EPSG:3857") # wms_enable_request enough? map.setMetaData("ows_enable_request", "*") onlineresource = urlparse.urlunsplit( (self.request.scheme, "{}:{}".format(self.request.host, self.request.host_port), self.request.path, urllib.urlencode( (('DATA_URL', self.request.params.get('DATA_URL')), )), "")) map.setMetaData("wms_onlineresource", onlineresource) # TODO: metadata # title, author, xmp_dc_title # wms_onlineresource ... help to generate GetCapabilities request # ows_http_max_age ... WMS client caching hints http://www.mnot.net/cache_docs/#CACHE-CONTROL # ows_lsd_enabled ... if false ignore SLD and SLD_BODY # wms_attribution_xxx ... do we want attribution metadata? # SCALEBAR if False: # LABEL sbl = mapscript.labelObj() sbl.color = mapscript.colorObj(0, 0, 0) sbl.antialias = mapscript.MS_TRUE sbl.size = mapscript.MS_LARGE sb = mapscript.scalebarObj() sb.label = sbl sb.status = mapscript.MS_ON map.scalebar = sb # LEGEND if False: # LABEL legl = mapscript.labelObj() legl.color = mapscript.colorObj(64, 64, 64) legl.antialias = mapscript.MS_TRUE legl.offsetx = -23 legl.offsety = -1 leg = mapscript.legendObj() leg.keysizex = 32 leg.keysizey = 10 leg.keyspacingx = 5 leg.keyspacingy = -2 leg.status = mapscript.MS_ON map.legend = leg return map
def testColorObjConstructorNoArgs(self): """a color can be initialized with no arguments""" c = mapscript.colorObj() assert (c.red, c.green, c.blue, c.alpha) == (0, 0, 0, 255)
def add_layer_obj(self, map): """Create mapserver layer object. The data is assumed to be a csv file with column 'lon' and 'lat' describing ponit features. """ # inspect data if we haven't yet self._inspect_data() # create a layer object layer = mapscript.layerObj() # configure layer # NAME layer.name = "DEFAULT" # TODO: filename?, real title? # TYPE # TODO: this supports only POINT datasets for now,... should detect # this somehow layer.type = mapscript.MS_LAYER_POINT # STATUS layer.status = mapscript.MS_ON # mark layer as queryable layer.template = "query" # anything non null and with length > 0 works here # CONNECTION_TYPE local|ogr? layer.setConnectionType(mapscript.MS_OGR, None) # TODO: the VRT source works fine, but maybe converting the VRT to a # real shapefile with ogr2ogr would spped up rendering? (or use a # sqlite/spatiallite datasource?) # TODO: check if GDAL dies and kills whole mapserver process in case # the csv file is not valid or contains broken values # layer.setConnectionType(MS_RASTER) MS_OGR? # TODO: other elements to consider: # Metadata ... on Datasource and LAyer # OpenOptions ... only gdal >= 2.0 # FID ... ?? # Style ... ??? # FeatureCount # ExtentXMien, ExtentXMax, ExtentYMin, ExtentYMax layer.connection = """\ <OGRVRTDataSource> <OGRVRTLayer name='{0}'> <SrcDataSource>{1}</SrcDataSource> <GeometryType>wkbPoint</GeometryType> <LayerSRS>EPSG:4326</LayerSRS> <GeometryField name='location' encoding='PointFromColumns' x='lon' y='lat'/> </OGRVRTLayer> </OGRVRTDataSource>""".format(escape(os.path.splitext(os.path.basename(self.filename))[0]).replace("'", "'"), escape(self.filename)) # PROJECTION ... should we ste this properly? # TODO: this always assume epsg:4326 layer.setProjection("init={}".format(self._data['crs'])) # METADATA # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE layer.setMetaData("gml_include_items", "all") layer.setMetaData("wms_include_items", "all") layer.setMetaData("wms_title", "BCCVL Occurrences") # can be a space separated list layer.setMetaData("wms_srs", self._data['crs']) # TODO: metadata # other things like title, author, attribution etc... if not (self.request.params.get('STYLES') or 'SLD' in self.request.params or 'SLD_BODY' in self.request.params): # set some default style if the user didn't specify any' # STYLE styleobj = mapscript.styleObj() styleobj.color = mapscript.colorObj(255, 50, 50) styleobj.minsize = 2 styleobj.maxsize = 50 styleobj.size = 5 styleobj.symbol = map.symbolset.index('circle') clsobj = mapscript.classObj() clsobj.name = "record" clsobj.insertStyle(styleobj) layer.insertClass(clsobj) ret = map.insertLayer(layer) # apply SLD if given sld = self.request.params.get('SLD_BODY') sld_url = self.request.params.get('SLD') if sld_url: map.applySLDURL(sld_url) elif sld: map.applySLD(sld) return ret
def createMapImage(self): import settings # Create a map object outputMap = mapscript.mapObj(settings.PRIVATE_MAPFILE) gd = mapscript.outputFormatObj('AGG/PNG') outputMap.setOutputFormat(gd) extent = self.fields['oldata']['extent'] outputMap.setExtent(extent['left'], extent['bottom'], extent['right'], extent['top']) outputMap.setSize(self.W,self.H) # Set all the layers initially off. i=0 layer = outputMap.getLayer(i) while layer: layer.status = mapscript.MS_OFF i = i + 1 layer = outputMap.getLayer(i) connection = "user=%s dbname=%s host=%s password=%s" % ( settings.DATABASE_USER, settings.DATABASE_NAME, (settings.DATABASE_HOST or "localhost"), settings.DATABASE_PASSWORD ) # Example for WMS layer building layers = self.fields['oldata']['mapLayers'] layerNames = "" for i,layer in enumerate(layers): subLayers = layer['params']['LAYERS'] if subLayers and (type(subLayers) != types.ListType): subLayers = list(subLayers) for subLayer in subLayers: mapFileLayer = outputMap.getLayerByName(subLayer) # use layer from mapfile directly. if mapFileLayer: # authenticate db connections. if "user=%s" % settings.DATABASE_USER in mapFileLayer.connection: mapFileLayer.connection = connection mapFileLayer.status = mapscript.MS_DEFAULT outputMap.insertLayer(mapFileLayer) # generate a custom layer dynamically. else: wmsLayer = mapscript.layerObj() wmsLayer.name = 'wms'+str(i) wmsLayer.connection = layer['url'].replace("..",settings.HOST) wmsLayer.connectiontype = mapscript.MS_WMS wmsLayer.status = mapscript.MS_DEFAULT wmsLayer.type = mapscript.MS_LAYER_RASTER #wmsLayer.setProjection("init="+layer['params']['SRS']) # By default take the first 'list' of any values wmsLayer.metadata.set("wms_name", subLayer) wmsLayer.metadata.set("wms_exceptions_format", "application/vnd.ogc.se_xml") wmsLayer.metadata.set("wms_format", "image/png") #layer['params']['FORMAT']) wmsLayer.metadata.set("wms_srs", layer['params']['SRS']) wmsLayer.metadata.set("wms_server_version", layer['params']['VERSION']) outputMap.insertLayer(wmsLayer) vectorLayers = self.fields['oldata']['vectorLayers'] if len(vectorLayers) > 0: dataString = "poly from (select id, poly from referrals_referralshape where " for i,vectorLayer in enumerate(vectorLayers): if i == 0: dataString = dataString + "id=" + str(vectorLayer) else: dataString = dataString + " OR id=" + str(vectorLayer) dataString = dataString + ") as foo using unique id using SRID=3005" userShapeLayer = outputMap.getLayerByName("user_shapes") userShapeLayer.connection = connection userShapeLayer.status = mapscript.MS_DEFAULT outputMap.insertLayer(userShapeLayer) userShapeLayer.data = dataString scalebarBG = mapscript.colorObj(255,255,255) outputMap.scalebar.status = mapscript.MS_EMBED outputMap.scalebar.outlinecolor = scalebarBG # Setup the default name for the output image # create a subdirectory in tmp in case it already isn't there (to keep it nice a tidy) os.popen("mkdir -p /tmp/terratruth_print_files").read() outputImageFile = '/tmp/terratruth_print_files/testmap%s.jpg'%time.time() # Save the image to temporary spot, in jpeg format (PNG was causing an error) outputMap.selectOutputFormat('JPEG') img = outputMap.draw() # save and reload because otherwise we don't have a real PIL image apparently. img.save(outputImageFile) img = Image.open(outputImageFile) if self.fields.get('confidential'): confImage = Image.open(os.path.join(settings.BASE_DIR,"media","images","confidential.gif")) img = watermark.watermark(img, confImage, (0, 0), 0.5) if self.fields.get('legendimages'): legend = self.createLegendImage() img = watermark.watermark(img, legend,(img.size[0]-legend.size[0], 0), 1) img.save(outputImageFile) # Can use the outputImageFile to pass back to be inserted into PDF # Can return the outputImageUrl that contains the URL to image image = ImageReader(outputImageFile) return image
def makeMap(self, mapfilename=None): mapobj = self.getMapObj(mapfilename) for layer in self.capabilities.FeatureTypeList.getchildren(): if layer.tag != "{http://www.opengis.net/wfs}FeatureType": continue name = layer.Name.text logging.debug("Creating layer %s" % name) layerDefFile = self.createLayerDefinitionFile( name, os.path.join(os.path.dirname(__file__), "templates", 'wfs.xml')) ds = ogr.Open(layerDefFile) lyrobj = mapscript.layerObj(mapobj) lyrobj.name = name lyrobj.title = layer.Title.text lyrobj.data = layerDefFile lyrobj.setMetaData("wms_title", layer.Title.text) lyrobj.setMetaData("wfs_typename", layer.Name.text) lyrobj.setMetaData("wfs_version", self.capabilities.attrib["version"]) if ds: ogrLayer = ds.GetLayerByName(name) if ogrLayer: feature = ogrLayer.GetNextFeature() if feature: geom = feature.GetGeometryRef() if geom: lyrobj.type = self.getGeomName( geom.GetGeometryName()) else: mapobj.removeLayer(mapobj.numlayers - 1) logging.debug("No ogrGeometry found") continue else: mapobj.removeLayer(mapobj.numlayers - 1) logging.debug("No ogrFeature found") continue else: mapobj.removeLayer(mapobj.numlayers - 1) logging.debug("No ogrLayer found") continue else: mapobj.removeLayer(mapobj.numlayers - 1) logging.debug("No ogrDataSource found") continue lyrobj.setProjection(layer.SRS.text) lyrobj.dump = mapscript.MS_TRUE lyrobj.template = "foo" cls = mapscript.classObj(lyrobj) style = mapscript.styleObj(cls) style.outlinecolor = mapscript.colorObj(134, 81, 0) style.color = mapscript.colorObj(238, 153, 0) style.size = 5 style.width = 5 self.saveMapfile(mapobj, mapfilename) return mapobj
def testColorObjSetRGB(self): """a color can be set using setRGB method""" c = mapscript.colorObj() c.setRGB(255, 255, 255, 100) assert (c.red, c.green, c.blue, c.alpha) == (255, 255, 255, 100)
def testColorObjSetHexUpper(self): """a color can be set using upper case hex""" c = mapscript.colorObj() c.setHex('#FFFFFF') assert (c.red, c.green, c.blue) == (255, 255, 255)
def build(self): return mapscript.colorObj(self.red, self.green, self.blue)
def testColorObjToHexBadly(self): """raise an error in the case of an undefined color""" c = mapscript.colorObj(-1, -1, -1) self.assertRaises(mapscript.MapServerError, c.toHex)
def add_layer_obj(self, map): """ Create mapserver layer object. The raster data for the layer is located at filename, which should be an absolute path on the local filesystem. """ # inspect data if we haven't yet self._inspect_data() # create a layer object layer = mapscript.layerObj() # configure layer # NAME layer.name = "DEFAULT" # TODO: filename?, real title? # TYPE layer.type = mapscript.MS_LAYER_RASTER # STATUS layer.status = mapscript.MS_ON # mark layer as queryable layer.template = "dummy" # anything non null and with length > 0 works here # CONNECTION_TYPE local|ogr? # layer.setConnectionType(MS_RASTER) MS_OGR? # DATA layer.data = self.filename layer.tolerance = 10.0 # TODO: this should be dynamic based on zoom level # layer.toleranceunits = mapscript.MS_PIXELS # PROJECTION ... should we ste this properly? crs = self._data['crs'] layer.setProjection("init={}".format(crs)) # METADATA # TODO: check return value of setMetaData MS_SUCCESS/MS_FAILURE layer.setMetaData("gml_include_items", "all") # allow raster queries layer.setMetaData("wms_include_items", "all") # projection to serve layer.setMetaData("wms_srs", "EPSG:4326 EPSG:3857") # title required for GetCapabilities layer.setMetaData("wms_title", "BCCVL Layer") # TODO: metadata # other things like title, author, attribution etc... # OPACITY # TODO: this should probably be up to the client? # layer.setOpacity(70) # If data type is not integer: if self._data['datatype'] not in (gdal.GDT_Byte, gdal.GDT_UInt16, gdal.GDT_Int16, gdal.GDT_UInt32, gdal.GDT_Int32): # mapservers does the right thing with these processing # instructions setting scale, skips the integer processing step and # reads the raster as float layer.addProcessing("SCALE=AUTO,AUTO") layer.addProcessing("NODATA=AUTO") # CLASSITEM, CLASS # TODO: if we have a STYLES parameter we should add a STYLES element # here if not (self.request.params.get('STYLES') or 'SLD' in self.request.params or 'SLD_BODY' in self.request.params): # set some default style if the user didn't specify any' # STYLE styleobj = mapscript.styleObj() styleobj.mincolor = mapscript.colorObj(255, 255, 255) styleobj.maxcolor = mapscript.colorObj(0, 128, 255) if self._data: styleobj.minvalue = self._data['min'] styleobj.maxvalue = self._data['max'] styleobj.rangeitem = "[pixel]" clsobj = mapscript.classObj() clsobj.name = "-" # clsobj.setExpression("([pixel]>0)") clsobj.insertStyle(styleobj) # layer.classitem = "[pixel]" layer.insertClass(clsobj) ret = map.insertLayer(layer) sld = self.request.params.get('SLD_BODY') sld_url = self.request.params.get('SLD') if sld_url: map.applySLDURL(sld_url) elif sld: map.applySLD(sld) if ((sld or sld_url) and (self._data['datatype'] == gdal.GDT_Byte and self._data['nodata'] is not None)): # if we have 8bit data, mapserver ignores the NODATA value, so # let's classify it as transparent styleobj = mapscript.styleObj() styleobj.color = mapscript.colorObj(0, 0, 0, 0) styleobj.rangeitem = "[pixel]" clsobj = mapscript.classObj() clsobj.name = 'NODATA' clsobj.setExpression("([pixel] = {})".format( int(self._data['nodata']))) clsobj.insertStyle(styleobj) layer.insertClass(clsobj, 0) return ret
def serializeColor(qColor): """Serialize a QColor() into a mapscript.colorObj()""" msColor = mapscript.colorObj(qColor.red(), qColor.green(), qColor.blue(), qColor.alpha()) return msColor
shapetypes = { mapscript.MS_SHAPEFILE_POINT:mapscript.MS_LAYER_POINT, mapscript.MS_SHAPEFILE_ARC:mapscript.MS_LAYER_LINE, mapscript.MS_SHAPEFILE_POLYGON:mapscript.MS_LAYER_POLYGON, mapscript.MS_SHAPEFILE_MULTIPOINT:mapscript.MS_LAYER_LINE } layer = mapscript.layerObj(m) layer.name = shapename layer.type = shapetypes[shp.type] layer.status = mapscript.MS_ON layer.data = shapename cls = mapscript.classObj(layer) style = mapscript.styleObj() color = mapscript.colorObj() color.red = 242 color.green = 239 color.blue = 249 style.color = color cls.insertStyle(style) color = mapscript.colorObj() color.red = 70 color.green = 130 color.blue = 80 m.imagecolor = color image = m.draw() image.save('world_mapscript_python.png')