def tiles(layersObj, tcLayer, bbox=None, levels=None, dataProjectionString=None, tilesProjectionString=None): dataProj = None if (dataProjectionString != None): print("Data projection: %s"%dataProjectionString) dataProj = mapscript.projectionObj(dataProjectionString) tilesProj = None if (tilesProjectionString != None): print("Tiles projection: %s"%tilesProjectionString) tilesProj = mapscript.projectionObj(tilesProjectionString) elif (tcLayer.srs != None and tcLayer.srs != ""): print("Tiles projection: %s"%tcLayer.srs) tilesProj = mapscript.projectionObj("+init=" + tcLayer.srs.lower()) """ yield all non empty tiles indexes (x, y, z) """ pad = pack('x') done = {} for layerObj in layersObj: if (dataProj == None and layerObj.map.getProjection() != ""): print("Data projection: %s"%layerObj.map.getProjection()) dataProj = mapscript.projectionObj(layerObj.map.getProjection()) for shapeObj in shapes(layerObj, projectArray(bbox, tilesProj, dataProj)): # reprojet bbox tiles -> data for x, y, z in tcLayer.range(projectRect(shapeObj.bounds, dataProj, tilesProj), levels): # first filter using shapes bbox, reprojet bounds data -> tiles key = pack('3i', x, y, z) if key not in done: tile = MetaTile(tcLayer, x, y, z) # FIXME: handle metaSize rect = mapscript.rectObj(*tile.bufferbounds()) if intersects(shapeObj, projectRect(rect, tilesProj, dataProj)): # second filter using shapes geometry, reprojet bufferbounds tiles -> data done[key] = pad yield layerObj, shapeObj, x, y, z
def get_latlon_extent(self): rect = mapscript.rectObj(*self.get_extent()) rect.project( mapscript.projectionObj(self.get_proj4()), mapscript.projectionObj( "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")) return Extent(rect.minx, rect.miny, rect.maxx, rect.maxy)
def main(input_file, x_field_idx, y_field_idx, input_proj, output_proj): # set input and output projections proj_in = mapscript.projectionObj(input_proj) proj_out = mapscript.projectionObj(output_proj) # open file with open(input_file, encoding='utf-8') as f: # read csv csv_in = csv.reader(f) headers = next(csv_in) # setup output csv_out = csv.writer(sys.stdout) csv_out.writerow(headers) for row in csv_in: # set pointObj point = mapscript.pointObj(float(row[x_field_idx]), float(row[y_field_idx])) # project point.project(proj_in, proj_out) # update with reprojected coordinates row[x_field_idx] = point.x row[y_field_idx] = point.y csv_out.writerow(row)
def WGSbounds(self): x = self.bounds.minx y = self.bounds.miny p = ms.pointObj(x,y) assert p.project(GMERC,ms.projectionObj(WGS84)) == 0 X = self.bounds.maxx Y = self.bounds.maxy P = ms.pointObj(X,Y) assert P.project(GMERC,ms.projectionObj(WGS84)) == 0 return {'minx':p.x,'miny':p.y,'maxx':P.x,'maxy':P.y}
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 testWellKnownGEOGCS(self): self.map.setWKTProjection('WGS84') proj4 = self.map.getProjection() assert proj4.find('+proj=longlat') != -1, proj4 assert proj4.find('+datum=WGS84') != -1, proj4 assert ( mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_METERS
def testWellKnownGEOGCS(self): self.map.setWKTProjection('WGS84') proj4 = self.map.getProjection() assert ('+proj=longlat' in proj4 and '+datum=WGS84' in proj4) or proj4 == '+init=epsg:4326', proj4 assert ( mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_METERS
def testOGCWKT(self): self.map.setWKTProjection('PROJCS["unnamed", PROJECTION["Albers_Conic_Equal_Area"], ' 'PARAMETER["standard_parallel_1", 65], PARAMETER["standard_parallel_2", 55], ' 'PARAMETER["latitude_of_center", 0], PARAMETER["longitude_of_center", -153], ' 'PARAMETER["false_easting", -4943910.68], PARAMETER["false_northing", 0]]') proj4 = self.map.getProjection() assert proj4.find('+proj=aea') != -1 assert proj4.find('+ellps=WGS84') != -1 assert (mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_DD
def save_to_mapfile(self,out_path): path = self.__pathToShapeFile shapePath, shapeName = os.path.split(path) shapeName = shapeName.split('.')[0] shpfile = ms.shapefileObj(path,-1) # "value of -1 to open an existing shapefile"-ms.docs #print self.projection src_prj = ms.projectionObj(self.projection) shpfile.bounds.project(src_prj,self.targetProj) mapobj = ms.fromstring(MAPFILE%{'shapePath':shapePath,'shapeName':shapeName,'color':'[dtmValue]','projString':self.projection,'size':self.size}) mapobj.extent = shpfile.bounds mapobj.save(out_path)
def testOGCWKT(self): self.map.setWKTProjection( 'PROJCS["unnamed", PROJECTION["Albers_Conic_Equal_Area"], ' 'PARAMETER["standard_parallel_1", 65], PARAMETER["standard_parallel_2", 55], ' 'PARAMETER["latitude_of_center", 0], PARAMETER["longitude_of_center", -153], ' 'PARAMETER["false_easting", -4943910.68], PARAMETER["false_northing", 0]]' ) proj4 = self.map.getProjection() assert proj4.find('+proj=aea') != -1 assert proj4.find('+ellps=WGS84') != -1 assert (mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_DD
def testESRIWKT(self): self.map.setWKTProjection('ESRI::PROJCS["Pulkovo_1995_GK_Zone_2", GEOGCS["GCS_Pulkovo_1995", ' 'DATUM["D_Pulkovo_1995", SPHEROID["Krasovsky_1940", 6378245, 298.3]], ' 'PRIMEM["Greenwich", 0], ' 'UNIT["Degree", 0.017453292519943295]], PROJECTION["Gauss_Kruger"], ' 'PARAMETER["False_Easting", 2500000], ' 'PARAMETER["False_Northing", 0], PARAMETER["Central_Meridian", 9], ' 'PARAMETER["Scale_Factor", 1], ' 'PARAMETER["Latitude_Of_Origin", 0], UNIT["Meter", 1]]') proj4 = self.map.getProjection() assert proj4.find('+proj=tmerc') != -1 assert proj4.find('+ellps=krass') != -1 assert (mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_DD
def __getMapObj(self): path = self.__pathToShapeFile shapePath, shapeName = os.path.split(path) shapeName = shapeName.split('.')[0] shpfile = ms.shapefileObj(path,-1) # "value of -1 to open an existing shapefile"-ms.docs #print self.projection src_prj = ms.projectionObj(self.projection) shpfile.bounds.project(src_prj,self.targetProj) if not self.idVar: mapobj = ms.fromstring(MAPFILE%{'shapePath':shapePath,'shapeName':shapeName,'color':DEFAULT_COLOR,'projString':self.projection,'size':self.size}) else: mapobj = ms.fromstring(MAPFILE%{'shapePath':self.__workSpace,'shapeName':'dtm','color':'[dtmValue]','projString':self.projection,'size':self.size}) mapobj.extent = shpfile.bounds return mapobj
def testOGCWKT(self): self.map.setWKTProjection('''PROJCS["unnamed",GEOGCS["WGS 84",DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563]], PRIMEM["Greenwich",0], UNIT["Degree",0.0174532925199433]], PROJECTION["Albers_Conic_Equal_Area"], PARAMETER["standard_parallel_1", 65], PARAMETER["standard_parallel_2", 55], PARAMETER["latitude_of_center", 0], PARAMETER["longitude_of_center", -153], PARAMETER["false_easting", -4943910.68], PARAMETER["false_northing", 0], UNIT["metre",1.0] ]''') proj4 = self.map.getProjection() assert proj4.find('+proj=aea') != -1 assert proj4.find('+datum=WGS84') != -1 assert mapscript.projectionObj(proj4).getUnits() != mapscript.MS_DD
def get_latlon_extent(self): rect = mapscript.rectObj(*self.get_extent()) res = rect.project(mapscript.projectionObj(self.get_proj4()), mapscript.projectionObj('+init=epsg:4326')) return Extent(rect.minx, rect.miny, rect.maxx, rect.maxy)
import sys import zlib import math import struct import base64 ### Custom Imports, these need to be installed. import mapscript as ms assert ms.msGetVersionInt() >= 50200 #require 5.2.0 or above assert 'OUTPUT=PNG' in ms.msGetVersion() #require PNG support assert 'INPUT=SHAPEFILE' in ms.msGetVersion() #require PNG support ### Local imports. included from common import SPHEREMERC_GROUND_SIZE,MAPFILE WGS = ms.projectionObj('init=epsg:4326') #GMERC = ms.projectionObj('init=epsg:900913') GMERC = ms.projectionObj('init=epsg:3857') ID_OFFSET = 2 # 0==background,1==borders class Tiler: def __init__(self,mapobj): if issubclass(type(mapobj),basestring): mapobj = ms.mapObj(mapobj) self.map = mapobj def getScales(self): #print "Zoom: " scales = [] for i in range(20): leftx,boty,rightx,topy,zoom = self.gTileBounds(zoom=i) scales.append((zoom,int((rightx+1-leftx)*(boty+1-topy))))
# Custom from gws_lib import db, config, s3_util, s3_multipart # DynTM Imports from dynTileMapper import mapTools from dynTileMapper.tileMaker.tiler import Tiler from dynTileMapper.pypng import png from dynTileMapper.pypng.optTile import optTile ID_OFFSET = 2 # background and borders LOCAL_SHAPEFILE_PATH = "/var/shapefiles/" AWS_SHP_BUCKET = "shapefiles" BLANK = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xb4\x00\x00\x00\x00IEND\xaeB`\x82" SPHEREMERC_GROUND_SIZE = 20037508.34 * 2 WGS84 = mapscript.projectionObj("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ") GMERC = mapscript.projectionObj("init=epsg:3857") import polygon_util # Self Installing. Make sure LOCAL_SHAPEFILE_PATH exists or that we have permission to create it. if not os.path.exists(LOCAL_SHAPEFILE_PATH): try: os.mkdir(LOCAL_SHAPEFILE_PATH) except OSError, e: try: old = LOCAL_SHAPEFILE_PATH LOCAL_SHAPEFILE_PATH = "/var/tmp/shapefiles" if not os.path.exists(LOCAL_SHAPEFILE_PATH): os.mkdir(LOCAL_SHAPEFILE_PATH) print "WARNING: could not create LOCAL_SHAPEFILE_PATH: %s\n\tUsed alternate path: %s" % ( old,
# example invocation # ./reproj.py ./foo.csv 2 3 EPSG:32619 EPSG:4326 # check input parameters if (len(sys.argv) != 6): print sys.argv[0] + \ " <csvfile> <x_col> <y_col> <epsg_code_in> <epsg_code_out>" sys.exit(1) else: # set x and y indices x = int(sys.argv[2]) y = int(sys.argv[3]) # set input and output projections projObjIn = mapscript.projectionObj("init="+sys.argv[4].lower()) projObjOut = mapscript.projectionObj("init="+sys.argv[5].lower()) # open file fCsv = open(sys.argv[1], 'r') # read csv csvIn = csv.reader(fCsv) # setup output csvOut = csv.writer(sys.stdout) for aRow in csvIn: # each record # set pointObj point = mapscript.pointObj(float(aRow[x]), float(aRow[y])) # project point.project(projObjIn, projObjOut)
# example invocation # ./reproj.py ./foo.csv 2 3 EPSG:32619 EPSG:4326 # check input parameters if (len(sys.argv) != 6): print sys.argv[0] + \ " <csvfile> <x_col> <y_col> <epsg_code_in> <epsg_code_out>" sys.exit(1) else: # set x and y indices x = int(sys.argv[2]) y = int(sys.argv[3]) # set input and output projections projObjIn = mapscript.projectionObj("init=" + sys.argv[4].lower()) projObjOut = mapscript.projectionObj("init=" + sys.argv[5].lower()) # open file fCsv = open(sys.argv[1], 'r') # read csv csvIn = csv.reader(fCsv) # setup output csvOut = csv.writer(sys.stdout) for aRow in csvIn: # each record # set pointObj point = mapscript.pointObj(float(aRow[x]), float(aRow[y])) # project point.project(projObjIn, projObjOut)
os.putenv('PROJ_LIB',os.path.join(sys.prefix,'PROJ','NAD')) import tempfile,atexit ### Custom Imports, these need to be installed. import mapscript as ms assert ms.msGetVersionInt() >= 50200 #require 5.2.0 or above assert 'OUTPUT=PNG' in ms.msGetVersion() #require PNG support assert 'INPUT=SHAPEFILE' in ms.msGetVersion() #require SHAPEFILE support from osgeo import osr import pysal ### Local imports. included from tileMaker.common import MAPFILE from tileMaker.classifier import Classifier from tileMaker.tiler import Tiler #GMERC = ms.projectionObj('init=epsg:900913') GMERC = ms.projectionObj('init=epsg:3857') WGS84 = '+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ' UTM31 = '+proj=utm +zone=31 +ellps=WGS84 +datum=WGS84 +units=m +no_defs ' DEFAULT_SOURCE_PROJ = WGS84 ID_OFFSET = 2 # 0==background,1==borders DEFAULT_COLOR = '128 60 200' class MapScriptObj(object): """ A Pythonic API for working with shapefiles in mapscript, >>> m = MapScriptObj('path/to/file.shp') >>> m.projection '+proj=utm +zone=12 +ellps=clrk66 +units=m +no_defs ' >>> m.png '\x89PNG\r\n\x1a\n\x00\x00\x00\r....' """ def __init__(self, shpfile, size=(256,256), idVariable=None):
def testWellKnownGEOGCS(self): self.map.setWKTProjection('WGS84') proj4 = self.map.getProjection() assert proj4.find('+proj=longlat') != -1, proj4 assert proj4.find('+datum=WGS84') != -1, proj4 assert (mapscript.projectionObj(proj4)).getUnits() != mapscript.MS_METERS
def WGScenter(self): center = self.bounds.getCenter() center.project(GMERC,ms.projectionObj(WGS84)) return {'lng':center.x,'lat':center.y}
def __setTargetProj(self,value): try: self.__targetProj = ms.projectionObj(value) except: raise TypeError,"%s, is not a valid projection string!"%(str(value))
def get_latlon_extent(self): rect = mapscript.rectObj(*self.get_extent()) rect.project(mapscript.projectionObj(self.get_proj4()), mapscript.projectionObj("+init=epsg:4326")) return stores.Extent(rect.minx, rect.miny, rect.maxx, rect.maxy)
from math import floor,ceil # 3rd Party import numpy import pysal import mapscript ID_OFFSET = 2 #background and borders SPHEREMERC_GROUND_SIZE = (20037508.34*2) WGS84 = mapscript.projectionObj('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ') GMERC = mapscript.projectionObj('init=epsg:3857') def drop_colin(pts): i = len(pts)-3 bad = [] while i: a,b,c = numpy.array(pts[i:i+3]) if numpy.cross(a-b,c-b) == 0: bad.append(i+1) i-=1 pts = [pts[i] for i in range(len(pts)) if i not in bad] bad = [] return pts def clean_poly(pts,zoom): zoomfactor = 2**zoom tilesize = SPHEREMERC_GROUND_SIZE / zoomfactor clean_pts = [] prev_pt = None for pt in pts: x = 256*((pt.x+(SPHEREMERC_GROUND_SIZE/2.0))/tilesize) y = 256*((-1*(pt.y-(SPHEREMERC_GROUND_SIZE / 2.0)))/tilesize) vert = (int(round(x)),int(round(y)))
def toMapScript(self): return mapscript.projectionObj(self.__str__())
def get_latlon_extent(self): rect = mapscript.rectObj(*self.get_extent()) res = rect.project(mapscript.projectionObj(self.get_proj4()), mapscript.projectionObj("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")) return Extent(rect.minx, rect.miny, rect.maxx, rect.maxy)