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 WMS_S2_Layers(mapObj, imageryShp): layerObj = mapscript.layerObj(mapObj) layerObj.name = "Imagery" layerObj.status = mapscript.MS_ON layerObj.type = mapscript.MS_LAYER_POLYGON layerObj.connectiontype = mapscript.MS_OGR layerObj.connection = imageryShp # needed layerObj.metadata.set('wms_title', 'Imagery') layerObj.metadata.set('wms_enable_request', 'GetCapabilities') layerObj.metadata.set('wms_srs', "EPSG:3857") layerObj.metadata.set('wms_format', 'image/png') layerObj.metadata.set('wms_abstract', "Sentinel 2 Imagery") layerObj.metadata.set('wms_attribution_title', "JRC,JEODPP,ESA,COPERNICUS") layerObj1 = mapscript.layerObj(mapObj) layerObj1.name = "Footprint" # layerObj.debug = 5 layerObj1.status = mapscript.MS_ON layerObj1.type = mapscript.MS_LAYER_POLYGON layerObj1.connectiontype = mapscript.MS_OGR layerObj1.connection = imageryShp # needed layerObj1.metadata.set('wms_title', 'Footprint') layerObj1.metadata.set('wms_enable_request', 'GetCapabilities') layerObj1.metadata.set('wms_srs', "EPSG:3857") layerObj1.metadata.set('wms_format', 'image/png') layerObj1.metadata.set('wms_abstract', "Sentinel 2 Footprints") layerObj1.metadata.set('wms_attribution_title', "JRC,JEODPP,ESA,COPERNICUS")
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 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 create_featuretypemodel(self, ft_name, ds_name, metadata={}): if self.has_featuretypemodel(ft_name, ds_name): raise KeyExists(ft_name) ft = FeatureTypeModel(mapscript.layerObj(self.mapfile.ms)) ft.update(self, ft_name, ds_name, metadata) return ft
def create_default_layer(): layer = mapscript.layerObj() layer.classitem = "fooitem" layer.data = "/path/to/shapefile" layer.dump = mapscript.MS_TRUE layer.filteritem = "foofilteritem" layer.setFilter("foofilter") layer.group = 'foogroup' layer.labelcache = mapscript.MS_OFF layer.labelitem = 'foolabelitem' layer.labelmaxscaledenom=1000 layer.labelminscaledenom=100 layer.maxscaledenom = 1000 layer.minscaledenom = 100 layer.metadata.set("fookey","foovalue") layer.name = "foobar" layer.offsite.setHex("#000001") layer.opacity=50 layer.postlabelcache = mapscript.MS_TRUE layer.setProjection("+init=epsg:27572") layer.sizeunits = mapscript.MS_MILES layer.status = mapscript.MS_OFF layer.template = "footemplate" layer.tileindex = "/path/to/shp" layer.tileitem = "footileitem" layer.type = mapscript.MS_LAYER_POINT layer.units = mapscript.MS_DD layer.insertClass(create_default_class()) return layer
def testLayerObj(self): self.initMap() layer = mapscript.layerObj(self.map) self.map = None assert str(layer.p_map).find('mapscript.mapObj') != -1 gc.collect() assert layer.map is not None, layer.map
def create_coveragemodel(self, c_name, cs_name, metadata={}): if self.has_coveragemodel(c_name, cs_name): raise KeyExists(c_name) c = CoverageModel(mapscript.layerObj(self.mapfile.ms)) c.update(self, c_name, cs_name, metadata) return c
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 addBgLayer(conf,m,size,zoomlevel,ext,typ="osm"): import json,mapscript,time,shutil delta=(100*(2**(18-zoomlevel))) ext0=json.dumps((float(ext[0])-delta,float(ext[3])+delta,float(ext[2])+delta,float(ext[1])-delta)).replace("[","").replace("]","").replace(" ","") hreq=conf["main"]["serverAddress"]+"?service=WPS&version=1.0.0&request=Execute&Identifier=raster-tools.translate&DataInputs=InputDSN=base_layers/mq-"+typ+".xml;OutputDSN=tmp_"+conf["senv"]["MMID"]+str(time.clock()).split(".")[1]+";Format=GTiff;OutSize="+str(size[0]*1.5)+","+str(size[1]*1.5)+";ProjWin="+ext0+"&RawDataOutput=Result&language="+conf["main"]["language"] import urllib2 u = urllib2.urlopen(hreq) fName=u.read() fName1=fName.replace(".tif",str(time.clock()).split(".")[1]+".tif") shutil.move(fName,fName1) nl=mapscript.layerObj(m) nl.updateFromString('''LAYER NAME "BaseLayerMap" TYPE RASTER UNITS METERS STATUS ON DATA "'''+fName1+'''" PROCESSING "RESAMPLE=AVERAGE" PROJECTION "init=epsg:900913" END END''') ordon=() ordon+=((m.numlayers-1),) for a in range(0,m.numlayers-1): ordon+=(a,) m.setLayerOrder(ordon)
def create_layermodel(self, st_type, store, name, metadata={}): if self.has_layermodel(st_type, store, name): raise KeyExists((st_type, store, name)) ft = self.__ms2model(mapscript.layerObj(self.ms), st_type=st_type) ft.update(store, name, metadata) return ft
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 wms(request): import mapscript image = None for field in ['IMAGE', 'COVERAGE', 'image', 'coverage', 'id', 'ID']: if field in request.GET: image = request.GET[field] try: image = int(image) obj = Map.objects.get(pk=image) filename = obj.warped except: filename = "%s" % image filename = "%s/%s" % (settings.MAP_PATH, os.path.basename(filename)) ows = mapscript.OWSRequest() for k, v in request.GET.items(): if k.lower() in ['image', 'coverage']: continue ows.setParameter(k, v) ows.setParameter("LAYERS", "image") ows.setParameter("COVERAGE", "image") map = mapscript.mapObj('%s/wms.map' % settings.BASE_PATH) raster = mapscript.layerObj(map) raster.name = 'image' raster.type = mapscript.MS_LAYER_RASTER raster.data = filename raster.status = mapscript.MS_DEFAULT raster.setProjection( "+init=epsg:4326" ) raster.dump = mapscript.MS_TRUE raster.metadata.set("wcs_formats", "GEOTIFF JPEG2000") mapscript.msIO_installStdoutToBuffer() contents = map.OWSDispatch(ows) content_type = mapscript.msIO_stripStdoutBufferContentType() content = mapscript.msIO_getStdoutBufferBytes() return HttpResponse(content, content_type = content_type)
def create_layer(self, model, l_name, l_enabled, l_metadata={}): if self.has_layer(l_name): raise KeyExists(l_name) # Create the layer. layer = Layer(mapscript.layerObj(self.ms)) # Add some default metadata. dflt_metadata = { "ows_title": l_name, "ows_abstract": l_name, "wms_srs": "EPSG:4326" } for k, v in dflt_metadata.iteritems(): l_metadata.setdefault(k, v) l_metadata["ows_name"] = l_name # Update layer. layer.update(l_name, l_enabled, l_metadata) # Configure the layer according to the model. model.configure_layer(layer, l_enabled) # Set default style. layer.set_default_style(self)
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 wms(request): import mapscript image = None for field in ['IMAGE', 'COVERAGE', 'image', 'coverage', 'id', 'ID']: if field in request.GET: image = request.GET[field] try: image = int(image) obj = Map.objects.get(pk=image) filename = obj.warped except: filename = "%s" % image filename = "%s/%s" % (settings.MAP_PATH, os.path.basename(filename)) ows = mapscript.OWSRequest() for k, v in request.GET.items(): if k.lower() in ['image', 'coverage']: continue ows.setParameter(k, v) ows.setParameter("LAYERS", "image") ows.setParameter("COVERAGE", "image") map = mapscript.mapObj('%s/wms.map' % settings.BASE_PATH) raster = mapscript.layerObj(map) raster.name = 'image' raster.type = mapscript.MS_LAYER_RASTER raster.data = filename raster.status = mapscript.MS_DEFAULT raster.setProjection("+init=epsg:4326") raster.dump = mapscript.MS_TRUE mapscript.msIO_installStdoutToBuffer() contents = map.OWSDispatch(ows) content_type = mapscript.msIO_stripStdoutBufferContentType() content = mapscript.msIO_getStdoutBufferBytes() return HttpResponse(content, content_type=content_type)
def __init__(self,parent,id,size): wx.InitAllImageHandlers() self.size = size #setup map object self.map = mapscript.mapObj() self.map.width = size[0] self.map.height = size[1] #self.map.setProjection('proj=latlong,ellps=WGS84') self.map.setProjection('proj=lcc,ellps=GRS80') # set the output format self.map.setOutputFormat(mapscript.outputFormatObj('GD/PNG') ) self.map.interlace = False #PIL can't handle interlaced PNGs topo=mapscript.layerObj(None) topo.name="topo" topo.type=mapscript.MS_LAYER_RASTER topo.connectiontype=mapscript.MS_RASTER topo.setProjection('proj=lcc,ellps=GRS80,datum=NAD83') topo.status = mapscript.MS_ON topo.tileindex="maps/index.shp" topo.tileitem="location" layerNum = self.map.insertLayer(topo) #fn = self.lookupTopoFilename(0) #self.loadRaster(fn) BufferedCanvas.__init__(self,parent,id)
def testLayerConstructorNoArg(self): """test layer constructor with no argument""" layer = mapscript.layerObj() assert layer.__class__.__name__ == "layerObj" assert layer.thisown == 1 assert layer.index == -1 assert layer.map is None, layer.map
def create_default_layer(): layer = mapscript.layerObj() layer.classitem = "fooitem" layer.data = "/path/to/shapefile" layer.dump = mapscript.MS_TRUE layer.filteritem = "foofilteritem" layer.setFilter("foofilter") layer.group = 'foogroup' layer.labelcache = mapscript.MS_OFF layer.labelitem = 'foolabelitem' layer.labelmaxscaledenom = 1000 layer.labelminscaledenom = 100 layer.maxscaledenom = 1000 layer.minscaledenom = 100 layer.metadata.set("fookey", "foovalue") layer.name = "foobar" layer.offsite.setHex("#000001") layer.opacity = 50 layer.postlabelcache = mapscript.MS_TRUE layer.setProjection("+init=epsg:27572") layer.sizeunits = mapscript.MS_MILES layer.status = mapscript.MS_OFF layer.template = "footemplate" layer.tileindex = "/path/to/shp" layer.tileitem = "footileitem" layer.type = mapscript.MS_LAYER_POINT layer.units = mapscript.MS_DD layer.insertClass(create_default_class()) 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 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 create_layermodel(self, st_type, store, name, metadata={}): if self.has_layermodel(st_type, store, name): raise KeyExists((st_type, store, name)) lm = self.__ms2model(mapscript.layerObj(self.ms), st_type=st_type) lm.update(store, name, metadata) return lm
def draw_map_wms(name, save=0): # print("making map in thread %s" % (name)) mo = mapscript.mapObj(TESTMAPFILE) # WFS layer lo = mapscript.layerObj() lo.name = 'jpl_wms' lo.setProjection('+init=epsg:4326') lo.connectiontype = mapscript.MS_WMS lo.connection = 'http://vmap0.tiles.osgeo.org/wms/vmap0?' lo.metadata.set('wms_service', 'WMS') lo.metadata.set('wms_server_version', '1.1.1') lo.metadata.set('wms_name', 'basic') lo.metadata.set('wms_style', 'visual') lo.metadata.set('wms_format', 'image/jpeg') lo.type = mapscript.MS_LAYER_RASTER lo.status = mapscript.MS_DEFAULT lo.debug = mapscript.MS_ON mo.insertLayer(lo) if not mo.web.imagepath: mo.web.imagepath = os.environ.get('TEMP', None) or INCOMING mo.debug = mapscript.MS_ON mo.selectOutputFormat('image/jpeg') im = mo.draw() if save: im.save('threadtest_wms_%s.jpg' % (name))
def test_raster_layer(): map = create_default_map() layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_RASTER layer.name = "test raster" layer.data = "path/to/file.tif" layer.offsite.setRGB(255, 0, 0) run_map(map)
def test_raster_layer(): map =create_default_map() layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_RASTER layer.name = "test raster" layer.data = "path/to/file.tif" layer.offsite.setRGB(255,0,0) run_map(map)
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 addLayerToMapfile(self, dataPath, layerName): layer = layerObj() layer.data = dataPath layer.type = MS_LAYER_RASTER layer.name = layerName layer.units = MS_PIXELS layer.status = MS_OFF layer.setProjection("init=epsg:4314") self.mapfile.insertLayer(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 testLayerConstructorMapArg(self): """test layer constructor with map argument""" layer = mapscript.layerObj(self.map) assert layer.__class__.__name__ == "layerObj" assert layer.thisown == 1 lyr = self.map.getLayer(self.map.numlayers-1) assert lyr is not None # assert str(layer) == str(lyr) # TODO - check why these are not equal assert layer.map is not None, layer.map
def setUp(self): self.mo = mapscript.mapObj() lo = mapscript.layerObj() lo.name = 'pg_layer' lo.type = mapscript.MS_LAYER_POLYGON lo.connectiontype = mapscript.MS_POSTGIS lo.connection = PG_CONNECTION_STRING lo.data = "the_geom from polygon" li = self.mo.insertLayer(lo) self.lo = self.mo.getLayer(li)
def setUp(self): self.mo = mapscript.mapObj() lo = mapscript.layerObj() lo.name = 'pg_sub_layer' lo.type = mapscript.MS_LAYER_POLYGON lo.connectiontype = mapscript.MS_POSTGIS lo.connection = PG_CONNECTION_STRING lo.data = "the_geom from (select * from polygon) as foo using unique gid using srid=4326" li = self.mo.insertLayer(lo) self.lo = self.mo.getLayer(li)
def testLayerClone(self): """Clone a layer""" layer = mapscript.layerObj() layer.name = 'sample' copy = layer.clone() assert layer.refcount == 1, layer.refcount assert copy.refcount == 1, copy.refcount assert layer.name == copy.name assert copy.map is None
def get_mapfile(self, classification=None): layerobj = mapscript.layerObj() layerobj.status = mapscript.MS_ON layerobj.type = mapscript.MS_LAYER_RASTER layerobj.name = self.name layerobj.data = self.gdal_source.GetDescription() projection = self.get_proj4() if projection is not None: layerobj.setProjection(projection) return mapserializer.layerobj_to_dict(layerobj, None)
def get_mapfile(self,classification = None): layerobj = mapscript.layerObj() layerobj.status = mapscript.MS_ON layerobj.type = mapscript.MS_LAYER_RASTER layerobj.name = self.name layerobj.data = self.gdal_source.GetDescription() projection = self.get_proj4() if projection is not None: layerobj.setProjection(projection) return mapserializer.layerobj_to_dict(layerobj,None)
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 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 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 build_layer(geo_query): layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_POLYGON layer.status = mapscript.MS_DEFAULT layer.name = self.name = name layer.connectiontype = mapscript.MS_POSTGIS layer.connection = "dbname=" + EAlGIS().dbname() layer.data = geo_query # layer.label = "[sa1_7digit]" layer.processing = "CLOSE_CONNECTION=DEFER" layer.labelitem = None return layer
def build_layer(geo_query): layer = mapscript.layerObj() layer.type = mapscript.MS_LAYER_POLYGON layer.status = mapscript.MS_DEFAULT layer.name = self.name = name layer.connectiontype = mapscript.MS_POSTGIS eal = EAlGIS() layer.connection = "host=%s port=%s dbname=%s user=%s password=%s" % (eal.dbhost(), eal.dbport(), eal.dbname(), eal.dbuser(), eal.dbpassword()) layer.data = geo_query # layer.label = "[sa1_7digit]" layer.processing = "CLOSE_CONNECTION=DEFER" layer.labelitem = None return layer
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 update_mapobj_from_dict(mapobj, map): if 'name' in map: mapobj.name = map['name'] if 'extent' in map: e = map['extent'] mapobj.setExtent(e['minx'], e['miny'], e['maxx'], e['maxy']) if 'projection' in map: mapobj.setProjection(map['projection']) if 'outputformats' in map: of = map['outputformats'][0] ofo = dict_to_outputformatobj(of) mapobj.appendOutputFormat(ofo) mapobj.selectOutputFormat(ofo.name) if 'imagetype' in map: mapobj.setImageType(map['imagetype']) if 'fontset' in map and map['fontset'] is not None: mapobj.setFontSet(map['fontset']) if 'web' in map: update_webobj_from_dict(mapobj.web, map['web']) if 'maxsize' in map: mapobj.maxsize = map['maxsize'] if 'resolution' in map: mapobj.resolution = map['resolution'] if 'symbolset' in map and map['symbolset'] is not None: mapobj.setSymbolSet(map['symbolset']) if 'units' in map: mapobj.units = mapscriptutils.units.lookup(map['units']) if 'height' in map and 'width' in map: mapobj.setSize(map['width'], map['height']) if 'imagecolor' in map: update_colorobj_from_dict(mapobj.imagecolor, map['imagecolor']) if 'layers' in map: for l in map['layers']: layerobj = mapscript.layerObj() update_layerobj_from_dict(layerobj, l, mapobj) mapobj.insertLayer(layerobj) return mapobj
def update_mapobj_from_dict(mapobj,map): if 'name' in map: mapobj.name = map['name'] if 'extent' in map: e = map['extent'] mapobj.setExtent(e['minx'],e['miny'],e['maxx'],e['maxy']) if 'projection' in map: mapobj.setProjection(map['projection']) if 'outputformats' in map: of = map['outputformats'][0] ofo = dict_to_outputformatobj(of) mapobj.appendOutputFormat(ofo) mapobj.selectOutputFormat(ofo.name) if 'imagetype' in map: mapobj.setImageType(map['imagetype']) if 'fontset' in map and map['fontset'] is not None: mapobj.setFontSet(map['fontset']) if 'web' in map: update_webobj_from_dict(mapobj.web, map['web']) if 'maxsize' in map: mapobj.maxsize = map['maxsize'] if 'resolution' in map: mapobj.resolution = map['resolution'] if 'symbolset' in map and map['symbolset'] is not None: mapobj.setSymbolSet(map['symbolset']) if 'units' in map: mapobj.units = mapscriptutils.units.lookup(map['units']) if 'height' in map and 'width' in map: mapobj.setSize(map['width'],map['height']) if 'imagecolor' in map: update_colorobj_from_dict(mapobj.imagecolor,map['imagecolor']) if 'layers' in map: for l in map['layers']: layerobj = mapscript.layerObj() update_layerobj_from_dict(layerobj,l,mapobj) mapobj.insertLayer(layerobj) return mapobj
def get_map_image_from_wms(wms_parameters=None, result_field=None, result_dao=None, filters=[], color_map={}): # Initialize mapscript map object from the habitat mapfile template. mapfile = "%s/results.map" % os.path.abspath(os.path.dirname(__file__)) ms_map = mapscript.mapObj(mapfile) layer = mapscript.layerObj() layer.name = "data" layer.setProjection('init=epsg:4326') layer.status = mapscript.MS_DEFAULT layer.setConnectionType(mapscript.MS_POSTGIS, '') connection_str = result_dao.get_mapserver_connection_string() layer.connection = connection_str layer.data = result_dao.get_mapserver_data_string(result_field=result_field, filters=filters) layer.type = mapscript.MS_LAYER_POLYGON # Get color range settings. num_classes = result_field.get('num_classes', 10) if not color_map: color_map = get_default_colormap() # Get color classes. color_classes = get_color_classes( attr='value_field', vmin = result_field.get('min', 0), vmax = result_field.get('max', 1), num_classes= result_field.get('num_classes', 10), color_map=color_map ) # Create classes for value ranges. for cc in color_classes: layer.insertClass(cc) 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 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 addLayerToMapfile(self, dataPath, layerName, georefTargetSRS): """ Function adds a layer to a mapfile :type dataPath: str :type layerName: str :type georefTargetSRS: int """ layer = layerObj() layer.data = dataPath layer.type = MS_LAYER_RASTER layer.name = layerName layer.units = MS_PIXELS layer.status = MS_OFF layer.setProjection("init=epsg:%s" % georefTargetSRS) self.mapfile.insertLayer(layer)
def testMapInsertLayerAtZero(self): """MapLayersTestCase.testMapInsertLayerAtZero: test insertion of a new layer at first index""" n = self.map.numlayers layer = mapscript.layerObj() layer.name = 'new' assert layer.map is None, layer.map index = self.map.insertLayer(layer, 0) assert layer.map is not None, layer.map assert index == 0, index assert self.map.numlayers == n + 1 names = [self.map.getLayer(i).name for i in range(self.map.numlayers)] assert names == ['new', 'RASTER', 'POLYGON', 'LINE', 'POINT', 'INLINE', 'INLINE-PIXMAP-RGBA', 'INLINE-PIXMAP-PCT'], names order = self.map.getLayerOrder() assert order == (0, 1, 2, 3, 4, 5, 6, 7), order