def import_csv(fn, orig, datatext=None): # Lat Lon yy = orig.split(',') origin = (float(yy[0]), float(yy[1])) data = [] if len(datatext) != 0: lines = datatext.split('\n') for l in lines: pp = re.split("( )+", l) if len(pp) == 1: continue if len(pp) < 3: raise Exception("Syntax error in 'direct Data input'") data.append([str(pp[0]), str(pp[2])]) print(data) else: with open(fn, 'r') as csvfile: reader = csv.reader(csvfile, delimiter=';') print(reader) for row in reader: data.append(row) tm = TransverseMercator() tm.lat = origin[0] tm.lon = origin[1] center = tm.fromGeographic(tm.lat, tm.lon) points = [] for p in data: lat, lon = p[0], p[1] ll = tm.fromGeographic(float(lat), float(lon)) points.append(FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0.0)) points.append(points[0]) Draft.makeWire(points) po = FreeCAD.ActiveDocument.ActiveObject po.ViewObject.LineColor = (1.0, 0.0, 0.0) po.MakeFace = False FreeCAD.activeDocument().recompute() FreeCADGui.SendMsgToActiveView("ViewFit")
def import_osm2(b, l, bk, progressbar, status, elevation): if progressbar: progressbar.setValue(0) if status: status.setText("get data from openstreetmap.org ...") FreeCADGui.updateGui() content = '' bk = 0.5 * bk dn = FreeCAD.ConfigGet("UserAppData") + "geodat3/" fn = dn + str(b) + '-' + str(l) + '-' + str(bk) import os if not os.path.isdir(dn): os.makedirs(dn) try: say("I try to read data from cache file ... ") say(fn) f = open(fn, "r") content = f.read() except: sayW("no cache file, so I connect to openstreetmap.org...") lk = bk b1 = b - bk / 1113 * 10 l1 = l - lk / 713 * 10 b2 = b + bk / 1113 * 10 l2 = l + lk / 713 * 10 source = 'http://api.openstreetmap.org/api/0.6/map?bbox=' + str( l1) + ',' + str(b1) + ',' + str(l2) + ',' + str(b2) say(source) import requests response = requests.get(source) data = response.text lines = response.text.split('\n') FreeCAD.t = response f = open(fn, "w") if response.status_code == 200: with open(fn, 'wb') as f: for chunk in response.iter_content(1024): f.write(chunk) f.close() if elevation: baseheight = getHeight(b, l) else: baseheight = 0 if debug: say("-------Data---------") say(content) if status: status.setText("parse data ...") FreeCADGui.updateGui() say("------------------------------") say(fn) tree = my_xmlparser.getData(fn) if debug: say(json.dumps(sd, indent=4)) if status: status.setText("transform data ...") FreeCADGui.updateGui() relations = tree.getiterator('relation') nodes = tree.getiterator('node') ways = tree.getiterator('way') bounds = tree.getiterator('bounds')[0] # center of the scene minlat = float(bounds.params['minlat']) minlon = float(bounds.params['minlon']) maxlat = float(bounds.params['maxlat']) maxlon = float(bounds.params['maxlon']) tm = TransverseMercator() tm.lat = 0.5 * (minlat + maxlat) tm.lon = 0.5 * (minlon + maxlon) center = tm.fromGeographic(tm.lat, tm.lon) corner = tm.fromGeographic(minlat, minlon) size = [center[0] - corner[0], center[1] - corner[1]] # map all points to xy-plane points = {} nodesbyid = {} for n in nodes: nodesbyid[n.params['id']] = n ll = tm.fromGeographic(float(n.params['lat']), float(n.params['lon'])) points[str(n.params['id'])] = FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0.0) if status: status.setText("create visualizations ...") FreeCADGui.updateGui() App.newDocument("OSM Map") say("Datei erzeugt") area = App.ActiveDocument.addObject("Part::Plane", "area") obj = FreeCAD.ActiveDocument.ActiveObject say("grundflaeche erzeugt") try: viewprovider = obj.ViewObject root = viewprovider.RootNode myLight = coin.SoDirectionalLight() myLight.color.setValue(coin.SbColor(0, 1, 0)) root.insertChild(myLight, 0) say("beleuchtung auf grundobjekt eingeschaltet") except: sayexc("Beleuchtung 272") cam = '''#Inventor V2.1 ascii OrthographicCamera { viewportMapping ADJUST_CAMERA orientation 0 0 -1.0001 0.001 nearDistance 0 farDistance 10000000000 aspectRatio 100 focalDistance 1 ''' x = 0 y = 0 height = 200 * bk * 10000 / 0.6 cam += '\nposition ' + str(x) + ' ' + str(y) + ' 999\n ' cam += '\nheight ' + str(height) + '\n}\n\n' FreeCADGui.activeDocument().activeView().setCamera(cam) FreeCADGui.activeDocument().activeView().viewAxonometric() say("Kamera gesetzt") area.Length = size[0] * 2 area.Width = size[1] * 2 area.Placement = FreeCAD.Placement( FreeCAD.Vector(-size[0], -size[1], 0.00), FreeCAD.Rotation(0.00, 0.00, 0.00, 1.00)) say("Area skaliert") wn = -1 coways = len(ways) starttime = time.time() refresh = 1000 for w in ways: wid = w.params['id'] building = False landuse = False highway = False wn += 1 nowtime = time.time() if wn != 0 and (nowtime - starttime) / wn > 0.5: say(("way ---- # " + str(wn) + "/" + str(coways) + " time per house: " + str(round( (nowtime - starttime) / wn, 2)))) if progressbar: progressbar.setValue(int(0 + 100.0 * wn / coways)) st = "" st2 = "" nr = "" h = 0 ci = "" for t in w.getiterator('tag'): try: if str(t.params['k']) == 'building': building = True if st == '': st = 'building' if str(t.params['k']) == 'landuse': landuse = True st = t.params['k'] nr = t.params['v'] if str(t.params['k']) == 'highway': highway = True st = t.params['k'] if str(t.params['k']) == 'addr:city': ci = t.params['v'] if str(t.params['k']) == 'name': nr = t.params['v'] if str(t.params['k']) == 'ref': nr = t.params['v'] + " /" if str(t.params['k']) == 'addr:street': st2 = " " + t.params['v'] if str(t.params['k']) == 'addr:housenumber': nr = str(t.params['v']) if str(t.params['k']) == 'building:levels': if h == 0: h = int(str(t.params['v'])) * 1000 * 3 if str(t.params['k']) == 'building:height': h = int(str(t.params['v'])) * 1000 except: sayErr( "unexpected error ######################################################" ) name = str(st) + st2 + " " + str(nr) if name == ' ': name = 'landuse xyz' if debug: say(("name ", name)) # Generate pointlist of the way polis = [] height = None llpoints = [] for n in w.getiterator('nd'): m = nodesbyid[n.params['ref']] llpoints.append( [n.params['ref'], m.params['lat'], m.params['lon']]) if elevation: say("get heights for " + str(len(llpoints))) heights = getHeights(llpoints) for n in w.getiterator('nd'): p = points[str(n.params['ref'])] if building and elevation: if not height: try: height = heights[m.params['lat'] + ' ' + m.params['lon']] * 1000 - baseheight except: sayErr("---no height available for " + m.params['lat'] + ' ' + m.params['lon']) height = 0 p.z = height polis.append(p) # Create 2D map pp = Part.makePolygon(polis) Part.show(pp) z = App.ActiveDocument.ActiveObject z.Label = "w_" + wid if name == ' ': g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z g.ViewObject.ShapeColor = (1.00, 1.00, 0.00) g.Dir = (0, 0, 10) g.Solid = True g.Label = 'way ex ' if building: g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z g.ViewObject.ShapeColor = (1.00, 1.00, 1.00) if h == 0: h = 10000 g.Dir = (0, 0, h) g.Solid = True g.Label = name obj = FreeCAD.ActiveDocument.ActiveObject inventortools.setcolors2(obj) if landuse: g = App.ActiveDocument.addObject("Part::Extrusion", name) g.Base = z if nr == 'residential': g.ViewObject.ShapeColor = (1.00, 0.60, 0.60) elif nr == 'meadow': g.ViewObject.ShapeColor = (0.00, 1.00, 0.00) elif nr == 'farmland': g.ViewObject.ShapeColor = (0.80, 0.80, 0.00) elif nr == 'forest': g.ViewObject.ShapeColor = (1.0, 0.40, 0.40) g.Dir = (0, 0, 0.1) g.Label = name g.Solid = True if highway: g = App.ActiveDocument.addObject("Part::Extrusion", "highway") g.Base = z g.ViewObject.LineColor = (0.00, 0.00, 1.00) g.ViewObject.LineWidth = 10 g.Dir = (0, 0, 0.2) g.Label = name refresh += 1 if os.path.exists("/tmp/stop"): sayErr("notbremse gezogen") FreeCAD.w = w raise Exception("Notbremse Manager main loop") if refresh > 3: FreeCADGui.updateGui() refresh = 0 FreeCADGui.updateGui() FreeCAD.activeDocument().recompute() if status: status.setText("import finished.") if progressbar: progressbar.setValue(100) organize() endtime = time.time() say(("running time ", int(endtime - starttime), " count ways ", coways)) return True
def import_latlon(filename,orig,hi): global sd # content=trackstring # fn='/home/microelly2/FCB/b202_gmx_tracks/im_haus.gpx' # filename='/home/microelly2/FCB/b202_gmx_tracks/neufang.gpx' f=open(filename,"r") c1=f.read() import re #content = re.sub('^\<\?[^\>]+\?\>', '', c1) tm=TransverseMercator() # outdoor inn ... tm.lat,tm.lon = 50.3736049,11.191643 if orig != 'auto': yy=orig.split(' ') say(yy) origin=(float(yy[0]),float(yy[1])) tm.lat=origin[0] tm.lon=origin[1] center=tm.fromGeographic(tm.lat,tm.lon) FreeCAD.c=c1 vals=np.array([float(c) for c in c1.split()]) #vals=vals.reshape(len(vals)/3,3) ''' points=[] points2=[] points0=[] px=[] py=[] pz=[] pt=[] startx=None starty=None starth=None FreeCAD.sd=sd seg=sd['gpx']['trk']['trkseg'] try: seg['trkpt'] ss=seg seg=[ss] except: pass ''' lats=[] lons=[] points=[] for v in vals: lats.append(float(v[0])) lons.append(float(v[1])) ll=tm.fromGeographic(float(v[0]),float(v[1])) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(v[2])))) print (min(lats),max(lats)) print (min(lons),max(lons)) print ((max(lats)+min(lats))/2,(max(lons)+min(lons))/2) print ((max(lats)-min(lats))/2,(max(lons)-min(lons))/2) import Draft Draft.makeWire(points) return if orig == 'auto': tm.lat, tm.lon = (max(lats)+min(lats))/2,(max(lons)+min(lons))/2 print ("origin:") print(tm.lat,tm.lon) print ("----------") for s in seg: trkpts=s['trkpt'] n=trkpts[0] center=tm.fromGeographic(tm.lat,tm.lon) # print(trkpts) # for p in trkpts: # print(p) # map all points to xy-plane for n in trkpts: # print(n['@lat'],n['@lon']) lats.append(float(n['@lat'])) lons.append(float(n['@lon'])) ll=tm.fromGeographic(float(n['@lat']),float(n['@lon'])) h=n['ele'] # print(h) tim=n['time'] t2=re.sub('^.*T', '', tim) t3=re.sub('Z', '', t2) t4=t3.split(':') timx=int(t4[0])*3600+int(t4[1])*60+int(t4[2]) pt.append(timx) if starth == None: starth=float(h) starth=0 points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth))) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0)) points.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth))) points2.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],1000*(float(h)-starth)+20000)) points0.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],0)) px.append(ll[0]-center[0]) py.append(ll[1]-center[1]) pz.append(1000*(float(h)-starth)) # print(ll) if 1: import Draft if 0: #close path points.append(points[0]) Draft.makeWire(points0) Draft.makeWire(points) po=App.ActiveDocument.ActiveObject po.ViewObject.LineColor=(1.0,.0,0.0) po.MakeFace = False po.Placement.Base.z= float(hi) *1000 po.Label="My Track" Draft.makeWire(points2) po2=App.ActiveDocument.ActiveObject po2.ViewObject.LineColor=(.0,.0,1.0) po2.ViewObject.PointSize=5 po2.ViewObject.PointColor=(.0,1.0,1.0) po2.Placement.Base.z= float(hi)*1000 po2.Label="Track + 20m" App.activeDocument().recompute() Gui.SendMsgToActiveView("ViewFit") # break #------------------------------------------------ # data for postprocessing try: import numpyNode import mathplotlibNode t=mathplotlibNode.createMPL() t.Label="My Track raw Data" # hier werte bereitstellen t.countSources=4 t.source1Values=px t.source2Values=py t.source3Values=pz t.source4Values=pt t.source1Data="px" t.source2Data="py" t.source3Data="pz" t.source4Data="pt" t.useOut1=True t.useOut2=True t.useOut3=True t.useOut4=True # werte umrechnen t2=numpyNode.createNP() t2.Label="My Track data processed" t2.sourceObject=t t2.expression1="in1/np.max(np.abs(in1))" t2.label1 = "x relative" t2.expression2="in2/np.max(np.abs(in2))" t2.label2 = "y relative" t2.expression3="in3/np.max(np.abs(in3))" t2.label3 = "z relative" t2.expression4="-1+2*(in4-np.min(in4))/(np.max(in4)-np.min(in4))" t2.label4 = "time relative" # werte grafisch darstellen t3=mathplotlibNode.createMPL() t3.Label="My Track Data visualization" t3.record=False t3.useNumpy=True t3.sourceNumpy=t2 t3.useOut1=True t3.useOut2=True t3.useOut3=True t3.useOut4=True t4=numpyNode.createNP() t4.Label="My Track Data xy" t4.sourceObject=t t4.expression2="in2" t4.label2 = "path xy" t4.expressionTime="in1" t5=mathplotlibNode.createMPL() t5.Label="My Track Data xy Map" t5.record=False t5.useNumpy=True t5.sourceNumpy=t4 t5.useOut2=True FreeCAD.ActiveDocument.recompute() except: sayexc() print("!",orig,"!") return (str(tm.lat)+','+str(tm.lon)) return px,py
def runfile(fn, xw, xe, ys, yn, ox=0, oy=0): f = 100000000 tm = TransverseMercator() tm.lat = 0.5*(yn+ys) tm.lon = 0.5*(xw+xe) center = tm.fromGeographic(tm.lat, tm.lon) xw *= f xe *= f ys *= f yn *= f ox *= f oy *= f pts = [] poss = {} nds = [] elev = -1 c = 0 #Gui.ActiveDocument.ActiveView.setAnimationEnabled(False) pb=createProgressBar(label="create Elevations " + os.path.basename(fn) ) # file = open('/home/microelly2/Downloads/Lat50Lon11Lat51Lon12.osm', 'r') file =open(fn) # pb.pb.setValue(10) for line in file.readlines(): c += 1 # if c == 100000: break pb.pb.setValue((c/100)%100) m = re.match(r'.*<node id="([^"]+)" lat="([^"]+)" lon="([^"]+)".*', line) if m: y=float(m.group(2))*f x=float(m.group(3))*f id=m.group(1) poss[id]=(x,y) continue m = re.match(r'.*<nd ref="([^"]+)".*', line) if m: nds.append(m.group(1)) continue m = re.match(r'.*<tag k="ele" v="([^"]+)".*', line) if m: elev=float(m.group(1)) continue m = re.match(r'.*/way.*', line) if m: for nd in nds: x=poss[nd][0] y=poss[nd][1] if xw<x and x<xe and ys<y and y<yn: ll=tm.fromGeographic(y/f,x/f) pts.append(FreeCAD.Vector(ll[0]-center[0],ll[1]-center[1],elev*1000)) # if len(pts)>2: # d=Draft.makeWire(pts) # if len(pts)==1: # d=Draft.makePoint(pts[0]) c +=1 poss={} elev=0 nds=[] continue pb.hide() return pts
'''import heights''' # -*- coding: utf-8 -*- #------------------------------------------------- #-- google heights importer #-- #-- microelly 2016 v 0.3 #-- #-- GNU Lesser General Public License (LGPL) #------------------------------------------------- import FreeCAD, FreeCADGui, Draft from GeoDataWB.transversmercator import TransverseMercator from GeoDataWB.say import * tm = TransverseMercator() ## get the height of point # @param b latitude # @param l longitude ''' f='https://maps.googleapis.com/maps/api/elevation/json?locations=50.3377879,11.2104096' response = urllib2.urlopen(f) ''' def getheight(b, l): source = "https://api.open-elevation.com/api/v1/lookup?locations=" + str( b) + ',' + str(l) say(source) print(source)
def import_gpx(filename, orig, hi): """ Import a gpx trackfile """ global sd f = open(filename, "r") c1 = f.read() content = re.sub('^\<\?[^\>]+\?\>', '', c1) print(content) tm = TransverseMercator() # outdoor inn ... tm.lat, tm.lon = 50.3736049, 11.191643 if orig != 'auto': yy = orig.split(',') origin = (float(yy[0]), float(yy[1])) tm.lat = origin[0] tm.lon = origin[1] sd = parse(content) if debug: print(json.dumps(sd, indent=4)) points = [] points2 = [] points0 = [] px = [] py = [] pz = [] pt = [] startx = None starty = None starth = None FreeCAD.sd = sd seg = sd['gpx']['trk']['trkseg'] try: seg['trkpt'] ss = seg seg = [ss] except: pass lats = [] lons = [] for s in seg: trkpts = s['trkpt'] for n in trkpts: lats.append(float(n['@lat'])) lons.append(float(n['@lon'])) print(min(lats), max(lats)) print(min(lons), max(lons)) print((max(lats) + min(lats)) / 2, (max(lons) + min(lons)) / 2) print((max(lats) - min(lats)) / 2, (max(lons) - min(lons)) / 2) if orig == 'auto': tm.lat, tm.lon = (max(lats) + min(lats)) / 2, (max(lons) + min(lons)) / 2 print("origin:") print(tm.lat, tm.lon) print("----------") for s in seg: trkpts = s['trkpt'] n = trkpts[0] center = tm.fromGeographic(tm.lat, tm.lon) # map all points to xy-plane for n in trkpts: lats.append(float(n['@lat'])) lons.append(float(n['@lon'])) ll = tm.fromGeographic(float(n['@lat']), float(n['@lon'])) h = n['ele'] tim = n['time'] t2 = re.sub('^.*T', '', tim) t3 = re.sub('Z', '', t2) t4 = t3.split(':') timx = int(t4[0]) * 3600 + int(t4[1]) * 60 + int(t4[2]) pt.append(timx) if starth == None: starth = float(h) starth = 0 points.append( FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 1000 * (float(h) - starth))) points.append( FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0)) points.append( FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 1000 * (float(h) - starth))) points2.append( FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 1000 * (float(h) - starth) + 20000)) points0.append( FreeCAD.Vector(ll[0] - center[0], ll[1] - center[1], 0)) px.append(ll[0] - center[0]) py.append(ll[1] - center[1]) pz.append(1000 * (float(h) - starth)) Draft.makeWire(points0) Draft.makeWire(points) po = FreeCAD.ActiveDocument.ActiveObject po.ViewObject.LineColor = (1.0, 0.0, 0.0) po.MakeFace = False po.Placement.Base.z = float(hi) * 1000 po.Label = "My Track" Draft.makeWire(points2) po2 = FreeCAD.ActiveDocument.ActiveObject po2.ViewObject.LineColor = (0.0, 0.0, 1.0) po2.ViewObject.PointSize = 5 po2.ViewObject.PointColor = (0.0, 1.0, 1.0) po2.Placement.Base.z = float(hi) * 1000 po2.Label = "Track + 20m" FreeCAD.activeDocument().recompute() FreeCADGui.SendMsgToActiveView("ViewFit") return str(tm.lat) + ',' + str(tm.lon)