def setUp(self): """The test fixture is a shape of one point""" self.points = (mapscript.pointObj(0.0, 1.0), ) self.lines = (mapscript.lineObj(), ) self.addPointToLine(self.lines[0], self.points[0]) self.shape = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) self.addLineToShape(self.shape, self.lines[0])
def testSetValue(self): so = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) so.initValues(4) so.setValue(0, 'Foo') assert so.numvalues == 4 assert so.getValue(0) == 'Foo' assert so.getValue(1) == ''
def testGetPointWKT(self): # Create new instance from class data po = mapscript.pointObj(self.point_xy[0], self.point_xy[1]) lo = mapscript.lineObj() lo.add(po) so = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) so.add(lo) # test output WKT wkt = so.toWKT() self.assertTrue(wkt == self.point_wkt, wkt)
def rqtest_2(): line = mapscript.lineObj() line.add( mapscript.pointObj( 35, 25 ) ) line.add( mapscript.pointObj( 45, 25 ) ) line.add( mapscript.pointObj( 45, 35 ) ) line.add( mapscript.pointObj( 35, 25 ) ) poly = mapscript.shapeObj( mapscript.MS_SHAPE_POLYGON ) poly.add( line ) pmstestlib.layer.queryByShape( pmstestlib.map, poly ) return 'success'
def ogr_query_2(): line = mapscript.lineObj() line.add(mapscript.pointObj(479000, 4763000)) line.add(mapscript.pointObj(480000, 4763000)) line.add(mapscript.pointObj(480000, 4764000)) line.add(mapscript.pointObj(479000, 4764000)) poly = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) poly.add(line) pmstestlib.layer.queryByShape(pmstestlib.map, poly) return 'success'
def testAddPointFeature(self): """adding a point to an inline feature works correctly""" inline_layer = self.map.getLayerByName('INLINE') assert inline_layer.connectiontype == mapscript.MS_INLINE p = mapscript.pointObj(0.2, 51.5) lyr = mapscript.lineObj() self.addPointToLine(lyr, p) shape = mapscript.shapeObj(inline_layer.type) shape.classindex = 0 self.addLineToShape(shape, lyr) inline_layer.addFeature(shape) msimg = self.map.draw() filename = 'testAddPointFeature.png' msimg.save(filename)
def ogr_query_2(): line = mapscript.lineObj() line.add(mapscript.pointObj(479000, 4763000)) line.add(mapscript.pointObj(480000, 4763000)) line.add(mapscript.pointObj(480000, 4764000)) line.add(mapscript.pointObj(479000, 4764000)) poly = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) poly.add(line) pmstestlib.layer.queryByShape(pmstestlib.map, poly) return "success"
def rqtest_2(): line = mapscript.lineObj() line.add(mapscript.pointObj(35, 25)) line.add(mapscript.pointObj(45, 25)) line.add(mapscript.pointObj(45, 35)) line.add(mapscript.pointObj(35, 25)) poly = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) poly.add(line) pmstestlib.layer.queryByShape(pmstestlib.map, poly) return 'success'
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 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 main(sf_path): if not sf_path.lower().endswith(".shp"): sf_path += ".shp" sf_obj = get_shapefile_object(sf_path) # create an empty Shapefile object s_obj = mapscript.shapeObj() # loop through each shape in the original Shapefile for i in range(sf_obj.numshapes): # get the object at index i sf_obj.get(i, s_obj) print("Shape %i has %i part%s" % (i, s_obj.numlines, plural(s_obj.numlines))) print("Bounds (%f, %f) (%f, %f)" % (s_obj.bounds.minx, s_obj.bounds.miny, s_obj.bounds.maxx, s_obj.bounds.maxy)) # loop through parts of each shape for j in range(s_obj.numlines): # get the jth part of the ith object part = s_obj.get(j) print("Part %i has %i point%s" % (j, part.numpoints, plural(part.numpoints))) # loop through points in each part for k in range(part.numpoints): # get the kth point of the jth part of the ith shape point = part.get(k) print("%i: %f, %f" % (k, point.x, point.y))
def ogr_query_6(): return 'skip' layer = pmstestlib.layer layer.open() ######################################################################### # Check first shape attributes. result = layer.getResult(0) s = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) layer.resultsGetShape(s, 9, 0) if pmstestlib.check_items(layer, s, [('EAS_ID', ' 170')]) == 0: return 'fail' layer.close() layer.close() # discard resultset. return 'success'
def ogr_query_6(): return "skip" layer = pmstestlib.layer layer.open() ######################################################################### # Check first shape attributes. result = layer.getResult(0) s = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) layer.resultsGetShape(s, 9, 0) if not check_EAS_ID_with_or_without_space(layer, s, " 170"): return "fail" layer.close() layer.close() # discard resultset. return "success"
def ogr_query_6(): return 'skip' layer = pmstestlib.layer layer.open() ######################################################################### # Check first shape attributes. result = layer.getResult(0) s = mapscript.shapeObj(mapscript.MS_SHAPE_POLYGON) layer.resultsGetShape(s, 9, 0) if not check_EAS_ID_with_or_without_space(layer, s, ' 170'): return 'fail' layer.close() layer.close() # discard resultset. return 'success'
def ogr_query_6(): return 'skip' layer = pmstestlib.layer layer.open() ######################################################################### # Check first shape attributes. result = layer.getResult( 0 ) s = mapscript.shapeObj( mapscript.MS_SHAPE_POLYGON ) layer.resultsGetShape( s, 9, 0 ) if pmstestlib.check_items( layer, s, [('EAS_ID',' 170')] ) == 0: return 'fail' layer.close() layer.close() # discard resultset. return 'success'
def getAllSymbolsForTTF(conf,inputs,outputs): import mapscript import sys,os mapfile=conf["main"]["dataPath"]+"/maps/project_"+inputs["map"]["value"]+".map" print >> sys.stderr,mapfile m=mapscript.mapObj(mapfile) for i in range(0,m.numlayers): m.removeLayer(0) from Cheetah.Template import Template if inputs.keys().count('ttf'): symbFile=conf["main"]["tmpPath"]+"/symbols_"+inputs["ttf"]["value"]+".sym" if inputs['ttf']['value']=="images": try: os.unlink(symbFile) except: pass try: f=open(symbFile,"r") except: t=Template(file=conf["main"]["templatesPath"]+"/Manager/Styler/Symbols.sym.tmpl",searchList={"conf": conf,"inputs": inputs,"outputs": outputs}) f=open(symbFile,"w") f.write(t.__str__()) f.close() m.setSymbolSet(symbFile) mapfile=conf["main"]["dataPath"]+"/maps/map4symbols_"+inputs["ttf"]["value"]+".map" else: mapfile=conf["main"]["dataPath"]+"/maps/map4symbols_default.map" images=[] print >> sys.stderr,mapfile print >> sys.stderr,m.getNumSymbols() i=0 while i < m.getNumSymbols(): m.symbolset.getSymbol(i) print >> sys.stderr,mapfile symb=m.symbolset.getSymbol(i) print >> sys.stderr,symb.name if symb.name is not None and symb.name.count('polygon_')==0: l=m.getLayerByName("Symbol_"+symb.name) print >> sys.stderr,l if l is None: layer=mapscript.layerObj(m) layer.type=mapscript.MS_LAYER_POINT feature=mapscript.shapeObj(mapscript.MS_SHAPE_POINT) layer.addFeature(feature.fromWKT("POINT(0.001 0.001)")) layer.connection=None print >> sys.stderr, symb.name layer.name="Symbol_"+symb.name 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="Symbol_"+symb.name+"0" tmpStyle=mapscript.styleObj(tmpClass) tmpStyle.updateFromString('STYLE COLOR 0 0 0 OUTLINECOLOR 225 225 225 SYMBOL "'+symb.name+'" SIZE 20 END') layer.status=True #img_name="Symbol_"+symb.name+".png" #m.setSize(24,24) #m.setExtent(0,0,0.002,0.002) #tmpImage=m.draw()# images+=[{"id": layer.name,"value": conf["main"]["mapserverAddress"]+"?map="+mapfile+"&LAYERS="+layer.name+"&SRS=EPSG%3A4326&FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&BBOX=0,0,0.002,0.002&WIDTH=32&HEIGHT=32&format=png"}] #tmpImage=tmpClass.createLegendIcon(m,layer,32,32) #tmpImage.write(conf["main"]["dataPath"]+"/maps/"+img_name) #print >> sys.stderr,conf["main"]["dataPath"]+"/maps/"+img_name i+=1 m.save(mapfile) t=Template(file=conf["main"]["templatesPath"]+"/Manager/Styler/SymbolChooser.tmpl",searchList={"images": images,"inputs":inputs}) outputs["Result"]["value"]=t.__str__() return 3
def testAddEmpty(self): """expect an error rather than segfault when adding an empty shape""" # See bug 1201 sf = mapscript.shapefileObj('testAddDud.shp', 1) so = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) self.assertRaises(mapscript.MapServerError, sf.add, so)
return '' # Make sure passing in filename argument. if len(sys.argv) != 2: usage() # Make sure can access .shp file, create shapefileObj. if os.access(sys.argv[1] + ".shp", os.F_OK): sf_obj = mapscript.shapefileObj(sys.argv[1], -1) else: print "Can't access shapefile" sys.exit(2) # Create blank shape object. s_obj = mapscript.shapeObj(-1) # Loop through each shape in the shapefile. for i in range(sf_obj.numshapes): # Get the ith object. sf_obj.get(i, s_obj) print "Shape %i has %i part%s." % (i, s_obj.numlines, plural( s_obj.numlines)) print "bounds (%f, %f) (%f, %f)" % (s_obj.bounds.minx, s_obj.bounds.miny, s_obj.bounds.maxx, s_obj.bounds.maxy) # Loop through parts of each shape. for j in range(s_obj.numlines): # Get the jth part of the ith object.
if os.access(sys.argv[1] + ".shp", os.F_OK): shp = mapscript.shapefileObj(sys.argv[1], -1) if not os.access(sys.argv[1] + ".dbf", os.F_OK): print "Error accessing associated dbf?" sys.exit(2) dbf = sys.argv[1] + ".dbf" elif os.access(sys.argv[1][:-4] + ".shp", os.F_OK): shp = mapscript.shapefileObj(sys.argv[1][:-4] + ".shp", -1) if not os.access(sys.argv[1][:-4] + ".dbf", F_OK): print "Error accessing associated dbf?" sys.exit(2) dbf = sys.argv[1][:-4] + ".dbf" else: print "Error accessing shapefile \"" + sys.argv[1] + "\"" shape = mapscript.shapeObj(-1) ofile = open("geoidx.db", "w") #HACK db = subprocess.Popen(['dbview', dbf], stdout=subprocess.PIPE).stdout for i in range(shp.numshapes): shp.get(i, shape) # Index entry ofile.write("geoidx: " + str(i) + "\n") # Country # HACK!! db.readline() # Cat db.readline() # Fips cntry country = db.readline().split(': ')[-1].strip()
def testNullValue(self): so = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) assert so.numvalues == 0 assert so.getValue(0) is None
def getAllSymbolsForTTF(conf, inputs, outputs): import mapscript import sys, os mapfile = conf["main"]["dataPath"] + "/maps/project_" + inputs["map"][ "value"] + ".map" print >> sys.stderr, mapfile m = mapscript.mapObj(mapfile) for i in range(0, m.numlayers): m.removeLayer(0) from Cheetah.Template import Template if inputs.keys().count('ttf'): symbFile = conf["main"]["tmpPath"] + "/symbols_" + inputs["ttf"][ "value"] + ".sym" if inputs['ttf']['value'] == "images": try: os.unlink(symbFile) except: pass try: f = open(symbFile, "r") except: t = Template(file=conf["main"]["templatesPath"] + "/Manager/Styler/Symbols.sym.tmpl", searchList={ "conf": conf, "inputs": inputs, "outputs": outputs }) f = open(symbFile, "w") f.write(t.__str__()) f.close() m.setSymbolSet(symbFile) mapfile = conf["main"]["dataPath"] + "/maps/map4symbols_" + inputs[ "ttf"]["value"] + ".map" else: mapfile = conf["main"]["dataPath"] + "/maps/map4symbols_default.map" images = [] i = 0 cnt = 0 while i < m.getNumSymbols(): m.symbolset.getSymbol(i) symb = m.symbolset.getSymbol(i) if symb.name is not None and symb.name.count('polygon_') == 0: l = m.getLayerByName("Symbol_" + symb.name) if l is None: layer = mapscript.layerObj(m) layer.type = mapscript.MS_LAYER_POINT feature = mapscript.shapeObj(mapscript.MS_SHAPE_POINT) layer.addFeature( feature.fromWKT("POINT(" + str(cnt) + ".001 0.001)")) #layer.addFeature(feature.fromWKT("POINT(0.001 0.001)")) layer.connection = None layer.name = "Symbol_" + symb.name 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 = "Symbol_" + symb.name + "0" tmpStyle = mapscript.styleObj(tmpClass) tmpStyle.updateFromString( 'STYLE COLOR 0 0 0 OUTLINECOLOR 225 225 225 SYMBOL "' + symb.name + '" SIZE 20 END') layer.status = True #img_name="Symbol_"+symb.name+".png" #m.setSize(24,24) #m.setExtent(0,0,0.002,0.002) #tmpImage=m.draw()# images += [{ "id": layer.name, "value": conf["main"]["mapserverAddress"] + "?map=" + mapfile + "&LAYERS=" + layer.name + "&SRS=EPSG%3A4326&FORMAT=image%2Fpng&SERVICE=WMS&VERSION=1.1.1&REQUEST=GetMap&STYLES=&EXCEPTIONS=application%2Fvnd.ogc.se_inimage&BBOX=" + str(cnt) + ",0," + str(cnt) + ".002,0.002&WIDTH=32&HEIGHT=32&format=png" }] cnt += 1 #tmpImage=tmpClass.createLegendIcon(m,layer,32,32) #tmpImage.write(conf["main"]["dataPath"]+"/maps/"+img_name) #print >> sys.stderr,conf["main"]["dataPath"]+"/maps/"+img_name i += 1 m.save(mapfile) t = Template(file=conf["main"]["templatesPath"] + inputs["tmpl"]["value"], searchList={ "images": images, "inputs": inputs, "mapfile": mapfile, "conf": conf }) outputs["Result"]["value"] = t.__str__() return 3
return '' # Make sure passing in filename argument. if len(sys.argv) != 2: usage() # Make sure can access .shp file, create shapefileObj. if os.access(sys.argv[1] + ".shp", os.F_OK): sf_obj = mapscript.shapefileObj(sys.argv[1], -1) else: print "Can't access shapefile" sys.exit(2) # Create blank shape object. s_obj = mapscript.shapeObj(-1) # Loop through each shape in the shapefile. for i in range(sf_obj.numshapes): # Get the ith object. sf_obj.get(i, s_obj) print "Shape %i has %i part%s." % (i, s_obj.numlines, plural(s_obj.numlines)) print "bounds (%f, %f) (%f, %f)" % (s_obj.bounds.minx, s_obj.bounds.miny, s_obj.bounds.maxx, s_obj.bounds.maxy) # Loop through parts of each shape. for j in range(s_obj.numlines): # Get the jth part of the ith object. part = s_obj.get(j) print "Part %i has %i point%s." % (j, part.numpoints, plural(part.numpoints))
UNITS METERS STATUS ON PROJECTION "init=epsg:4326" END CLASS STYLE COLOR 255 255 255 OUTLINECOLOR 60 80 80 SIZE 15 SYMBOL 7 WIDTH 2 END # STYLE END # CLASS END''') feature=mapscript.shapeObj(nl1.type) feature=feature.fromWKT("POINT("+inputs["lat"]["value"]+" "+inputs["lon"]["value"]+")") # Draw the image and save it print >> sys.stderr,"Draw" i=m.draw() print >> sys.stderr,"OK" import time savedImage=conf["main"]["tmpPath"]+"/print_"+conf["senv"]["MMID"]+"_"+str(time.clock()).split(".")[1]+".png" print >> sys.stderr,"OK" try: os.unlink(savedImage) except: pass
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