Пример #1
0
 def index(self):
     when,valid,fct=gfs_weather.get_prognosis(datetime.utcnow())
     lat=59.45862
     lon=17.70680
     c.qnh=1013
     c.winddir=0
     c.windvel=0
     
     c.defaddata=self.load_ad_json(extra_airfields.frolunda)
     c.field=u"Frölunda"
     c.searchurl=h.url_for(controller='sufperformance',action='search')
     c.airport_load_url=h.url_for(controller='sufperformance',action='load')
     metar=metartaf.get_metar('ESSA')
     print "metar:",metar
     try:
         c.temp,dew=re.match(r".*\b(\d{2})/(\d{2})\b.*",metar.text).groups()
         print "c.temp:",c.temp
         if c.temp.startswith("M"):
             c.temp=-int(c.temp[1:])
         else:
             c.temp=int(c.temp)
     except:
         c.temp=15
     try:
         c.qnh=fct.get_qnh(lat,lon)
         if c.qnh<10:        
             c.qnh=1013
         c.winddir,c.windvel=fct.get_surfacewind(lat,lon)
         c.winddir=int(c.winddir)
         c.windvel=int(c.windvel)
     except:
         print traceback.format_exc()
         pass
     
     return render('/sufperformance.mako')
Пример #2
0
    def index(self):
        when, valid, fct = gfs_weather.get_prognosis(datetime.utcnow())
        lat = 59.45862
        lon = 17.70680
        c.qnh = 1013
        c.winddir = 0
        c.windvel = 0

        c.defaddata = self.load_ad_json(extra_airfields.frolunda)
        c.field = u"Frölunda"
        c.searchurl = h.url_for(controller='sufperformance', action='search')
        c.airport_load_url = h.url_for(controller='sufperformance',
                                       action='load')
        metar = metartaf.get_metar('ESSA')
        print "metar:", metar
        try:
            c.temp, dew = re.match(r".*\b(\d{2})/(\d{2})\b.*",
                                   metar.text).groups()
            print "c.temp:", c.temp
            if c.temp.startswith("M"):
                c.temp = -int(c.temp[1:])
            else:
                c.temp = int(c.temp)
        except:
            c.temp = 15
        try:
            c.qnh = fct.get_qnh(lat, lon)
            if c.qnh < 10:
                c.qnh = 1013
            c.winddir, c.windvel = fct.get_surfacewind(lat, lon)
            c.winddir = int(c.winddir)
            c.windvel = int(c.windvel)
        except:
            print traceback.format_exc()
            pass

        return render('/sufperformance.mako')
Пример #3
0
    def get_airspaces(self):
        print "Get airspaces called"

        getsectors = int(request.params.get("sectors", "0"))

        out = []
        if 1:
            for space in extracted_cache.get_airspaces(
            ) + get_notam_objs_cached(
            )['areas'] + extracted_cache.get_aip_sup_areas():
                lat, lon = mapper.from_str(space['points'][0])
                #if lat<57 or lat>62:
                #    continue
                if getsectors == 0 and space.get('type', None) == 'sector':
                    continue
                name = space['name']
                if space['type'] == "notamarea":
                    name = "NOTAM:" + name
                clnd = cleanup_poly(
                    [mapper.from_str(x) for x in space['points']], name)
                if not clnd:
                    print "Skipped area", name, space
                    continue
                out.append(
                    dict(
                        name=name,
                        freqs=space['freqs'] if space.get('freqs', "") else [],
                        floor=space.get('floor', ""),
                        type=space['type'],
                        ceiling=space.get('ceiling', ""),
                        points=[dict(lat=p[0], lon=p[1]) for p in clnd]))

        aiptexts = []
        points = []
        version = request.params.get("version", None)
        getaiptext = int(request.params.get("aip", "0"))
        print "version", version
        if version and int(version.strip()) >= 5:
            user_aipgen = request.params.get("aipgen", "")
        else:
            user_aipgen = ""
        for airp in extracted_cache.get_airfields():
            lat, lon = mapper.from_str(airp['pos'])
            if lat < 54 or lon < 4 or lon >= 30.5:
                try:
                    if not version or int(version.strip()) <= 7:
                        continue
                except:
                    continue

            #if lat<58.5 or lat>60.5:
            #    continue
            aname = airp['name']

            notams = []
            icao = None
            taf = None
            metar = None
            kind = 'field'
            if airp.get('icao', 'zzzz').lower() != 'zzzz':
                icao = airp['icao']
                notams = notam_geo_search.get_notam_for_airport(icao)
                metar = metartaf.get_metar(icao)
                taf = metartaf.get_taf(icao)
                kind = 'port'

            ap = dict(name=aname,
                      lat=lat,
                      lon=lon,
                      kind=kind,
                      notams=notams,
                      remark=airp.get('remark', ''),
                      alt=float(airp.get('elev', 0)))
            if 'runways' in airp:
                ap['runways'] = airp['runways']
            if icao:
                ap['icao'] = icao
                if taf.text:
                    ap['taf'] = taf.text
                if metar.text:
                    ap['metar'] = metar.text

                if getaiptext and 'aiptext' in airp:
                    for aiptext in airp['aiptext']:
                        if aip_text_documents.check_doc(
                                aiptext['icao'], aiptext['category'],
                                aiptext['checksum']):
                            #^^^Okay, this really needs an explanation^^^
                            #Nominally, each aiptext item in aipdata.cache (from which the get_airfields() function
                            #ultimately gets all its data, should always have its corresponding aiptext in html format
                            #available on disk. Now, if the on-disk file is deleted (should never happen), we will
                            #get an exception later down where we try to send this data (with the checksum we have here)
                            #over http to the client. Unfortunately, the routine that sends the data is not at liberty
                            #to modify "what was sent", so the entire sync operation fails. This hack here makes the
                            #failure happen earlier, and in that case the given aiptext-document is suppressed
                            #completely, meaning that the sync operation succeeds, albeit without one specific document
                            #(hey, better than nothing!).
                            #
                            #Of course, the real question is why a document may be missing. A bug of some sort right now,
                            #2012-08-28, makes this bug occur every now and then. Investigation is ongoing.
                            aiptexts.append(
                                dict(name=icao + "_" + aiptext['category'],
                                     icao=icao,
                                     data=aiptext))

            if 'adcharts' in airp and '' in airp['adcharts'] and airp[
                    'adcharts'][""]['blobname']:
                ret = airp['adcharts'][""]
                try:
                    cksum = ret['checksum']
                    try:
                        aprojmatrix = get_proj(cksum).matrix
                    except Exception:
                        #print traceback.format_exc()
                        #print "Using 0-proj for ",aname
                        aprojmatrix = [0 for x in xrange(6)]

                    ap['adchart_matrix'] = list(aprojmatrix)
                    ap['adchart_width'] = ret['render_width']
                    ap['adchart_height'] = ret['render_height']
                    ap['adchart_name'] = ret['blobname']
                    ap['adchart_checksum'] = cksum
                    ap['adchart_url'] = ret['url']
                except Exception, cause:
                    print "Couldn't get projection for airport %s (%s)" % (
                        aname, cause)

            points.append(ap)
Пример #4
0
    def get_airspaces(self):
        print "Get airspaces called"
        
        getsectors=int(request.params.get("sectors","0"))
        
        out=[]
        if 1:
            for space in extracted_cache.get_airspaces()+get_notam_objs_cached()['areas']+extracted_cache.get_aip_sup_areas():
                lat,lon=mapper.from_str(space['points'][0])
                #if lat<57 or lat>62:
                #    continue
                if getsectors==0 and space.get('type',None)=='sector':
                    continue
                name=space['name']
                if space['type']=="notamarea":
                    name="NOTAM:"+name
                clnd=cleanup_poly([mapper.from_str(x) for x in space['points']],name)
                if not clnd:
                    print "Skipped area",name,space 
                    continue
                out.append(dict(
                    name=name,
                    freqs=space['freqs'] if space.get('freqs',"") else [],
                    floor=space.get('floor',""),
                    type=space['type'],
                    ceiling=space.get('ceiling',""),
                    points=[dict(lat=p[0],lon=p[1]) for p in clnd]))
            
        aiptexts=[]
        points=[]
        version=request.params.get("version",None)
        getaiptext=int(request.params.get("aip","0"))
        print "version",version
        if version and int(version.strip())>=5:
            user_aipgen=request.params.get("aipgen","")
        else:
            user_aipgen=""
        for airp in extracted_cache.get_airfields():
            lat,lon=mapper.from_str(airp['pos'])
            if lat<54 or lon<4 or lon>=30.5:
                try:
                    if not version or int(version.strip())<=7:
                        continue
                except:
                    continue

            #if lat<58.5 or lat>60.5:
            #    continue
            aname=airp['name']
            
            notams=[]
            icao=None
            taf=None
            metar=None
            kind='field'
            if airp.get('icao','zzzz').lower()!='zzzz':
                icao=airp['icao']
                notams=notam_geo_search.get_notam_for_airport(icao)
                metar=metartaf.get_metar(icao)
                taf=metartaf.get_taf(icao)
                kind='port'
                
            ap=dict(
                name=aname,
                lat=lat,
                lon=lon,
                kind=kind,
                notams=notams,
                remark=airp.get('remark',''),
                alt=float(airp.get('elev',0)))
            if 'runways' in airp:
                ap['runways']=airp['runways']
            if icao:
                ap['icao']=icao
                if taf.text:
                    ap['taf']=taf.text
                if metar.text:
                    ap['metar']=metar.text
            
                if getaiptext and 'aiptext' in airp:
                    for aiptext in airp['aiptext']:
                        if aip_text_documents.check_doc(aiptext['icao'],aiptext['category'],aiptext['checksum']):
                            #^^^Okay, this really needs an explanation^^^
                            #Nominally, each aiptext item in aipdata.cache (from which the get_airfields() function
                            #ultimately gets all its data, should always have its corresponding aiptext in html format
                            #available on disk. Now, if the on-disk file is deleted (should never happen), we will
                            #get an exception later down where we try to send this data (with the checksum we have here)
                            #over http to the client. Unfortunately, the routine that sends the data is not at liberty
                            #to modify "what was sent", so the entire sync operation fails. This hack here makes the
                            #failure happen earlier, and in that case the given aiptext-document is suppressed
                            #completely, meaning that the sync operation succeeds, albeit without one specific document
                            #(hey, better than nothing!).
                            #
                            #Of course, the real question is why a document may be missing. A bug of some sort right now,
                            #2012-08-28, makes this bug occur every now and then. Investigation is ongoing.
                            aiptexts.append(
                                dict(name=icao+"_"+aiptext['category'],
                                     icao=icao,
                                     data=aiptext))
                        
            if 'adcharts' in airp and '' in airp['adcharts'] and airp['adcharts'][""]['blobname']:
                ret=airp['adcharts'][""]
                try:
                    cksum=ret['checksum']
                    try:
                        aprojmatrix=get_proj(cksum).matrix
                    except Exception:
                        #print traceback.format_exc()
                        #print "Using 0-proj for ",aname
                        aprojmatrix=[0 for x in xrange(6)]
                        
                    ap['adchart_matrix']=list(aprojmatrix)
                    ap['adchart_width']=ret['render_width']
                    ap['adchart_height']=ret['render_height']
                    ap['adchart_name']=ret['blobname']
                    ap['adchart_checksum']=cksum
                    ap['adchart_url']=ret['url']                    
                except Exception,cause:
                    print "Couldn't get projection for airport %s (%s)"%(aname,cause)
            
            points.append(ap)            
Пример #5
0
    def get_airspace(self):
        utcnow = datetime.utcnow()
        try:
            zoomlevel = int(request.params['zoom'])
        except Exception:
            zoomlevel = session.get('zoom', 5)
        lat = float(request.params.get('lat'))
        lon = float(request.params.get('lon'))
        clickmerc = mapper.latlon2merc((lat, lon), zoomlevel)
        user = session.get('user', None)
        out = []
        spaces = chain(get_airspaces(lat, lon),
                       userdata.get_airspaces(lat, lon, user))
        print "Spaces:", spaces

        def anydate(s):
            if not 'date' in s: return ""
            d = s['date']
            age = utcnow - d
            if age > timedelta(367):
                return "<span style=\"font-size:10px\">[%d]</span>" % (
                    d.year, )
            if age > timedelta(2):
                return "<span style=\"font-size:10px\">[%d%02d%02d]</span>" % (
                    d.year, d.month, d.day)
            return ""

        spacelist = spaces
        spaces = u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>" %
                          (space['name'], anydate(space), space['floor'],
                           space['ceiling'], format_freqs(space['freqs']))
                          for space in sorted(spacelist, key=sort_airspace_key)
                          if space['type'] != 'sector')

        #sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
        #        space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
        #            spacelist,key=sort_airspace_key) if space['type']=='sectoasdfr')

        try:
            sectors = u"".join(
                u"<li><b>%s</b>%s: %s - %s%s</li>" %
                (space['name'], anydate(space), space['floor'],
                 space['ceiling'], format_freqs(space['freqs']))
                for space in sorted(spacelist, key=sort_airspace_key)
                if space['type'] == 'sector')
            if sectors != "":
                sectors = "<b>Sectors:</b><ul>" + sectors + "</ul>"
        except:
            print traceback.format_exc()
            sectors = ""

        if spaces == "":
            spaces = "No airspace found"

        mapviewurl = h.url_for(controller="mapview", action="index")

        notamlist = chain(get_notam_areas(lat, lon),
                          get_notampoints(lat, lon, zoomlevel))
        notams = dict([(n['notam'].strip(), (n['notam_ordinal'],
                                             n['notam_line']))
                       for n in notamlist])

        notamareas = "".join(
            "<li>%s <b><u><a href=\"javascript:navigate_to('%s#notam')\">Link</a></u></b></li>"
            % (text,
               h.url_for(controller="notam",
                         action="show_ctx",
                         backlink=mapviewurl,
                         notam=notam,
                         line=line)) for text, (notam, line) in notams.items())
        if notamareas != "":
            notamareas = "<b>Area Notams:</b><ul>" + notamareas + "</ul>"

        aip_sup_strs = "".join([
            "<li>%s <a href=\"%s\">link</a></li>" %
            (x['name'], x['url'].replace(" ", "%20"))
            for x in get_aip_sup_areas(lat, lon)
        ])
        if aip_sup_strs:
            aip_sup_strs = "<b>AIP SUP:</b><ul>" + aip_sup_strs + "</ul>"

        obstbytype = dict()
        for obst in chain(get_obstacles(lat, lon, zoomlevel),
                          userdata.get_obstacles(lat, lon, zoomlevel, user)):
            obstbytype.setdefault(obst['kind'], []).append(obst)
            print "processing", obst
        obstacles = []
        if len(obstbytype):
            for kind, obsts in sorted(obstbytype.items()):
                obstacles.append("<b>" + kind + ":</b>")
                obstacles.append(u"<ul>")
                for obst in obsts:
                    obstacles.append(u"<li><b>%s</b>: %s ft</li>" %
                                     (obst['name'], obst['elev']))
                obstacles.append(u"</ul>")

        tracks = []
        if session.get('showtrack', None) != None:
            track = session.get('showtrack')
            #print "%d points"%(len(track.points))
            mindiff = 1e30
            found = dict()
            hdg = 0
            speed = 0
            clickvec = Vertex(int(clickmerc[0]), int(clickmerc[1]))
            if len(track.points) > 0 and len(track.points[0]) == 2:
                pass  #Old style track, not supported anymore
            else:
                for a, b in izip(track.points, track.points[1:]):
                    merc = mapper.latlon2merc(a[0], zoomlevel)
                    nextmerc = mapper.latlon2merc(b[0], zoomlevel)
                    l = Line(Vertex(int(merc[0]), int(merc[1])),
                             Vertex(int(nextmerc[0]), int(nextmerc[1])))
                    diff = l.approx_dist(clickvec)

                    if diff < mindiff:
                        mindiff = diff
                        found = (a, b)

                if mindiff < 10:
                    tracks.append(
                        u"<b>GPS track:</b><ul><li>%(when)s - %(altitude)d ft hdg:%(heading)03d spd: %(speed)d kt</li></ul>"
                        % (get_stats(*found)))

        airports = []
        fields = list(
            chain(get_airfields(lat, lon, zoomlevel),
                  userdata.get_airfields(lat, lon, zoomlevel, user)))
        if len(fields):
            airports.append("<b>Airfield:</b><ul>")
            for airp in fields:
                #print "clicked on ",airp
                linksstr = ""
                links = []
                if 'flygkartan_id' in airp:
                    links.append(('http://www.flygkartan.se/0%s' %
                                  (airp['flygkartan_id'].strip(), ),
                                  'www.flygkartan.se'))
                if 'aiptexturl' in airp:
                    links.append((airp['aiptexturl'], 'AIP Text'))
                if 'aipvacurl' in airp:
                    links.append(
                        (airp['aipvacurl'], 'AIP Visual Approach Chart'))

                if False and 'aipsup' in airp:
                    #Using AIP SUP for opening hours has stopped.
                    links.append((extracted_cache.get_se_aip_sup_hours_url(),
                                  "AIP SUP Opening Hours"))
                weather = ""
                if airp.get('icao', 'ZZZZ').upper() != 'ZZZZ':
                    icao = airp['icao'].upper()
                    metar = metartaf.get_metar(icao)
                    taf = metartaf.get_taf(icao)
                    weather = "<table>"

                    def colorize(item, colfac=1):
                        if item == None:
                            col = "ffffff"
                            agestr = ""
                        else:
                            age = metartaf.get_data_age(item)
                            if age == None:
                                col = "ffffff"
                                agestr = ""
                            elif age < timedelta(0, 60 * 35 * colfac):
                                col = "c5c5c5"
                                agestr = "%d minutes" % (int(age.seconds / 60))
                            elif age < timedelta(0, 60 * 60 * colfac):
                                col = "ffff30"
                                agestr = "%d minutes" % (int(age.seconds / 60))
                            else:
                                col = "ff3030"
                                if age < timedelta(2):
                                    if age < timedelta(0, 3600 * 1.5):
                                        agestr = "%d minutes" % int(
                                            age.seconds / 60)
                                    else:
                                        agestr = "%d hours" % int(
                                            0.5 + (age.seconds) / 3600.0)
                                else:
                                    agestr = "%d days" % (int(age.days))

                        return "style=\"background:#" + col + "\" title=\"" + agestr + " old.\""

                    if taf and taf.text:
                        weather += "<tr valign=\"top\"><td>TAF:</td><td " + colorize(
                            taf, 5) + ">" + taf.text + "</td></tr>"
                    if metar and metar.text:
                        weather += "<tr valign=\"top\"><td>METAR:</td><td " + colorize(
                            metar) + ">" + metar.text + "</td></tr>"

                    ack_cnt = meta.Session.query(
                        NotamAck.appearnotam, NotamAck.appearline,
                        sa.func.count('*').label('acks')).filter(
                            NotamAck.user == session.get(
                                'user', None)).group_by(
                                    NotamAck.appearnotam,
                                    NotamAck.appearline).subquery()
                    notams = meta.Session.query(
                        NotamUpdate, ack_cnt.c.acks, Notam.downloaded
                    ).outerjoin(
                        (ack_cnt,
                         sa.and_(
                             NotamUpdate.appearnotam == ack_cnt.c.appearnotam,
                             NotamUpdate.appearline == ack_cnt.c.appearline))
                    ).outerjoin(
                        (Notam,
                         Notam.ordinal == NotamUpdate.appearnotam)).order_by(
                             sa.desc(Notam.downloaded)).filter(
                                 sa.and_(
                                     NotamUpdate.disappearnotam == sa.null(),
                                     NotamUpdate.category.like(icao.upper() +
                                                               "/%"))).all()
                    print "notams:", repr(notams)
                    if notams:
                        nots = []
                        for notam, ack, downloaded in notams:
                            nots.append(
                                "<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;\">%s</div>"
                                % (cgi.escape(notam.text)))

                        weather += "<tr valign=\"top\"><td colspan=\"2\">NOTAM:</td></tr><tr><td colspan=\"2\">%s</td></tr>" % (
                            "".join(nots))

                    weather += "</table>"
                    meta.Session.flush()
                    meta.Session.commit()

                if len(links) > 0 and 'icao' in airp:
                    linksstr = helpers.foldable_links(airp['icao'] + "links",
                                                      links)

                rwys = []
                if 'runways' in airp:
                    for rwy in airp['runways']:
                        ends = []
                        for end in rwy['ends']:
                            ends.append(end['thr'])
                        surf = ""
                        if 'surface' in rwy:
                            surf = "(" + rwy['surface'] + ")"
                        rwys.append("/".join(ends) + surf)

                if len(rwys):
                    rwys = ["<b> Runways</b>: "] + [", ".join(rwys)]
                remark = ""
                if airp.get('remark'):
                    remark = "<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;background-color:#ffffe0\"><b>Remark:</b> " + cgi.escape(
                        airp['remark']) + "</div>"

                airports.append(u"<li><b>%s</b> - %s%s%s%s%s</li>" %
                                (airp.get('icao', 'ZZZZ'), airp['name'],
                                 linksstr, remark, " ".join(rwys), weather))
            airports.append("</ul>")

        sigpoints = []
        sigps = list(
            chain(get_sigpoints(lat, lon, zoomlevel),
                  userdata.get_sigpoints(lat, lon, zoomlevel, user)))
        if len(sigps):
            sigpoints.append("<b>Sig. points</b><ul>")
            for sigp in sigps:
                sigpoints.append(
                    u"<li><b>%s</b>(%s)</li>" %
                    (sigp['name'], sigp.get('kind', 'unknown point')))
            sigpoints.append("</ul>")

        firs = []
        for fir in list(get_firs(
            (lat, lon))) + list(userdata.get_firs(lat, lon, user)):
            if 'icao' in fir:
                firs.append("%s (%s)" % (fir['name'], fir['icao']))
        if not firs:
            firs.append("Unknown")

        variation = '?'
        terrelev = get_terrain_elev((lat, lon), zoomlevel)
        try:
            varf = geomag.calc_declination((lat, lon), utcnow,
                                           (terrelev + 1000))
            variation = u"%+.1f°" % (varf, )
        except Exception:
            pass

        weather = ""
        try:
            when, valid, fct = gfs_weather.get_prognosis(datetime.utcnow())
            qnh = fct.get_qnh(lat, lon)
            out = [
                "<b>Weather</b><br/>Forecast: %sZ, valid: %sZ<br />" %
                (when.strftime("%Y-%m-%d %H:%M"), valid.strftime("%H:%M"))
            ]
            try:
                out.append("Surface wind: %.0f deg, %.1f knots<br />" %
                           fct.get_surfacewind(lat, lon))
                out.append("Surface RH: %.0f%%<br />" %
                           (fct.get_surfacerh(lat, lon), ))
            except:
                print traceback.format_exc()
            out.append("<ul>")
            for fl, dir, st, temp in fct.get_winds(lat, lon):
                out.append("<li>FL%02d: %03d deg, %.1fkt, %.1f &#176;C" %
                           (int(fl), int(dir), float(st), temp))
            out.append("</ul>QNH: %d<br/><br/>" % (qnh, ))
            weather = "".join(out)
        except Exception:
            print traceback.format_exc()

        return "<b>Airspace:</b><ul><li><b>FIR:</b> %s</li>%s</ul>%s%s%s%s%s%s%s<br/>%s<b>Terrain: %s ft, Var: %s</b>" % (
            ", ".join(firs), spaces, sectors, aip_sup_strs, "".join(obstacles),
            "".join(airports), "".join(tracks), "".join(sigpoints), notamareas,
            weather, terrelev, variation)
Пример #6
0
    def get_airspace(self):
        utcnow=datetime.utcnow()
        try:
            zoomlevel=int(request.params['zoom'])
        except Exception:
            zoomlevel=session.get('zoom',5)
        lat=float(request.params.get('lat'))
        lon=float(request.params.get('lon'))
        clickmerc=mapper.latlon2merc((lat,lon),zoomlevel)
        user=session.get('user',None)
        out=[]
        spaces=chain(get_airspaces(lat,lon),userdata.get_airspaces(lat,lon,user))
        print "Spaces:",spaces
        def anydate(s):
            if not 'date' in s: return ""
            d=s['date']
            age=utcnow-d            
            if age>timedelta(367):
                return "<span style=\"font-size:10px\">[%d]</span>"%(d.year,)
            if age>timedelta(2):                
                return "<span style=\"font-size:10px\">[%d%02d%02d]</span>"%(
                        d.year,d.month,d.day)
            return ""
        spacelist=spaces
        spaces=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
                space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
                    spacelist,key=sort_airspace_key) if space['type']!='sector')


        #sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
        #        space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
        #            spacelist,key=sort_airspace_key) if space['type']=='sectoasdfr')

        try:
            sectors=u"".join(u"<li><b>%s</b>%s: %s - %s%s</li>"%(
                   space['name'],anydate(space),space['floor'],space['ceiling'],format_freqs(space['freqs'])) for space in sorted(
                  spacelist,key=sort_airspace_key) if space['type']=='sector')
            if sectors!="":
                sectors="<b>Sectors:</b><ul>"+sectors+"</ul>"
        except:
            print traceback.format_exc()
            sectors=""

        if spaces=="":
            spaces="No airspace found"

            
        mapviewurl=h.url_for(controller="mapview",action="index")

        
        notamlist=chain(get_notam_areas(lat,lon),get_notampoints(lat,lon,zoomlevel))
        notams=dict([(n['notam'].strip(),(n['notam_ordinal'],n['notam_line']) ) for n in notamlist])

        
        notamareas="".join("<li>%s <b><u><a href=\"javascript:navigate_to('%s#notam')\">Link</a></u></b></li>"%(
            text,h.url_for(controller="notam",action="show_ctx",backlink=mapviewurl,notam=notam,line=line)) for text,(notam,line) in notams.items())
        if notamareas!="":
            notamareas="<b>Area Notams:</b><ul>"+notamareas+"</ul>"

        aip_sup_strs="".join(["<li>%s <a href=\"%s\">link</a></li>"%(x['name'],x['url'].replace(" ","%20")) for x in get_aip_sup_areas(lat,lon)])
        if aip_sup_strs:
            aip_sup_strs="<b>AIP SUP:</b><ul>"+aip_sup_strs+"</ul>"
         
        obstbytype=dict()
        for obst in chain(get_obstacles(lat,lon,zoomlevel),userdata.get_obstacles(lat,lon,zoomlevel,user)):
            obstbytype.setdefault(obst['kind'],[]).append(obst)
            print "processing",obst
        obstacles=[]
        if len(obstbytype):
            for kind,obsts in sorted(obstbytype.items()):
                obstacles.append("<b>"+kind+":</b>")
                obstacles.append(u"<ul>")
                for obst in obsts:
                    obstacles.append(u"<li><b>%s</b>: %s ft</li>"%(obst['name'],obst['elev'])) 
                obstacles.append(u"</ul>")

        tracks=[]
        if session.get('showtrack',None)!=None:                
            track=session.get('showtrack')
            #print "%d points"%(len(track.points))
            mindiff=1e30
            found=dict()
            hdg=0
            speed=0
            clickvec=Vertex(int(clickmerc[0]),int(clickmerc[1]))
            if len(track.points)>0 and len(track.points[0])==2:                
                pass #Old style track, not supported anymore
            else:
                for a,b in izip(track.points,track.points[1:]): 
                    merc=mapper.latlon2merc(a[0],zoomlevel)
                    nextmerc=mapper.latlon2merc(b[0],zoomlevel)
                    l=Line(Vertex(int(merc[0]),int(merc[1])),Vertex(int(nextmerc[0]),int(nextmerc[1])))
                    diff=l.approx_dist(clickvec)                

                    if diff<mindiff:
                        mindiff=diff
                        found=(a,b)

                if mindiff<10:
                    tracks.append(u"<b>GPS track:</b><ul><li>%(when)s - %(altitude)d ft hdg:%(heading)03d spd: %(speed)d kt</li></ul>"%(get_stats(*found)))
                                                  

        airports=[]
        fields=list(chain(get_airfields(lat,lon,zoomlevel),userdata.get_airfields(lat,lon,zoomlevel,user)))
        if len(fields):
            airports.append("<b>Airfield:</b><ul>")
            for airp in fields:
                #print "clicked on ",airp
                linksstr=""
                links=[]
                if 'flygkartan_id' in airp:
                    links.append(('http://www.flygkartan.se/0%s'%(airp['flygkartan_id'].strip(),),
                      'www.flygkartan.se'))
                if 'aiptexturl' in airp:
                    links.append((airp['aiptexturl'],
                      'AIP Text'))
                if 'aipvacurl' in airp:
                    links.append((airp['aipvacurl'],
                      'AIP Visual Approach Chart'))
                    
                if False and 'aipsup' in airp:
                    #Using AIP SUP for opening hours has stopped.
                    links.append((
                        extracted_cache.get_se_aip_sup_hours_url(),
                        "AIP SUP Opening Hours"))
                weather=""
                if airp.get('icao','ZZZZ').upper()!='ZZZZ':
                    icao=airp['icao'].upper()
                    metar=metartaf.get_metar(icao)
                    taf=metartaf.get_taf(icao)
                    weather="<table>"
                    
                    def colorize(item,colfac=1):
                        if item==None:
                            col="ffffff"
                            agestr=""
                        else:
                            age=metartaf.get_data_age(item)
                            if age==None:
                                col="ffffff"
                                agestr=""                                
                            elif age<timedelta(0,60*35*colfac):
                                col="c5c5c5"
                                agestr="%d minutes"%(int(age.seconds/60))
                            elif age<timedelta(0,60*60*colfac):
                                col="ffff30"
                                agestr="%d minutes"%(int(age.seconds/60))
                            else:
                                col="ff3030"
                                if age<timedelta(2):
                                    if age<timedelta(0,3600*1.5):
                                        agestr="%d minutes"%int(age.seconds/60)
                                    else:
                                        agestr="%d hours"%int(0.5+(age.seconds)/3600.0)
                                else:
                                    agestr="%d days"%(int(age.days))
                            
                        return "style=\"background:#"+col+"\" title=\""+agestr+" old.\""
                
                    if taf and taf.text:
                        weather+="<tr valign=\"top\"><td>TAF:</td><td "+colorize(taf,5)+">"+taf.text+"</td></tr>"
                    if metar and metar.text:
                        weather+="<tr valign=\"top\"><td>METAR:</td><td "+colorize(metar)+">"+metar.text+"</td></tr>"
                        
                        
                    ack_cnt = meta.Session.query(NotamAck.appearnotam,NotamAck.appearline,sa.func.count('*').label('acks')).filter(NotamAck.user==session.get('user',None)).group_by(NotamAck.appearnotam,NotamAck.appearline).subquery()
                    notams=meta.Session.query(NotamUpdate,ack_cnt.c.acks,Notam.downloaded).outerjoin(
                        (ack_cnt,sa.and_(
                            NotamUpdate.appearnotam==ack_cnt.c.appearnotam,
                            NotamUpdate.appearline==ack_cnt.c.appearline))).outerjoin(
                        (Notam,Notam.ordinal==NotamUpdate.appearnotam)
                         ).order_by(sa.desc(Notam.downloaded)).filter(
                                sa.and_(NotamUpdate.disappearnotam==sa.null(),
                                        NotamUpdate.category.like(icao.upper()+"/%")
                                        )).all()
                    print "notams:",repr(notams)
                    if notams:
                        nots=[]
                        for notam,ack,downloaded in notams:
                            nots.append("<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;\">%s</div>"%(cgi.escape(notam.text)))
                        
                        weather+="<tr valign=\"top\"><td colspan=\"2\">NOTAM:</td></tr><tr><td colspan=\"2\">%s</td></tr>"%("".join(nots))
                    
                    weather+="</table>"
                    meta.Session.flush()
                    meta.Session.commit()
                    
                if len(links)>0 and 'icao' in airp:                    
                    linksstr=helpers.foldable_links(airp['icao']+"links",links)

                rwys=[]
                if 'runways' in airp:
                    for rwy in airp['runways']:
                        ends=[]                        
                        for end in rwy['ends']:
                            ends.append(end['thr'])
                        surf=""
                        if 'surface' in rwy:
                            surf="("+rwy['surface']+")"
                        rwys.append("/".join(ends)+surf)
                            
                if len(rwys):                    
                    rwys=["<b> Runways</b>: "]+[", ".join(rwys)]
                remark=""
                if airp.get('remark'):
                    remark="<div style=\"border:1px solid;margin:3px;border-color:#B8B8B8;padding:3px;background-color:#ffffe0\"><b>Remark:</b> "+cgi.escape(airp['remark'])+"</div>"
                
                
                
                airports.append(u"<li><b>%s</b> - %s%s%s%s%s</li>"%(airp.get('icao','ZZZZ'),airp['name'],linksstr,remark," ".join(rwys),weather))
            airports.append("</ul>")
        
        sigpoints=[]
        sigps=list(chain(get_sigpoints(lat,lon,zoomlevel),userdata.get_sigpoints(lat,lon,zoomlevel,user)))
        if len(sigps):
            sigpoints.append("<b>Sig. points</b><ul>")
            for sigp in sigps:
                sigpoints.append(u"<li><b>%s</b>(%s)</li>"%(sigp['name'],sigp.get('kind','unknown point')))
            sigpoints.append("</ul>")
       

        firs=[]        
        for fir in list(get_firs((lat,lon)))+list(userdata.get_firs(lat,lon,user)):
            if 'icao' in fir:
                firs.append("%s (%s)"%(fir['name'],fir['icao']))        
        if not firs:
            firs.append("Unknown")
            
        variation='?'
        terrelev=get_terrain_elev((lat,lon),zoomlevel)
        try:
            varf=geomag.calc_declination((lat,lon),utcnow,(terrelev+1000))
            variation=u"%+.1f°"%(varf,)
        except Exception:
            pass
        
        weather=""
        try:
            when,valid,fct=gfs_weather.get_prognosis(datetime.utcnow())
            qnh=fct.get_qnh(lat,lon)
            out=["<b>Weather</b><br/>Forecast: %sZ, valid: %sZ<br />"%(when.strftime("%Y-%m-%d %H:%M"),valid.strftime("%H:%M"))]
            try:                
                out.append("Surface wind: %.0f deg, %.1f knots<br />"%fct.get_surfacewind(lat,lon))
                out.append("Surface RH: %.0f%%<br />"%(fct.get_surfacerh(lat,lon),))
            except:
                print traceback.format_exc()
            out.append("<ul>")
            for fl,dir,st,temp in fct.get_winds(lat,lon):
                out.append("<li>FL%02d: %03d deg, %.1fkt, %.1f &#176;C"%(int(fl),int(dir),float(st),temp))            
            out.append("</ul>QNH: %d<br/><br/>"%(qnh,))
            weather="".join(out)
        except Exception:
            print traceback.format_exc()
        
        return "<b>Airspace:</b><ul><li><b>FIR:</b> %s</li>%s</ul>%s%s%s%s%s%s%s<br/>%s<b>Terrain: %s ft, Var: %s</b>"%(", ".join(firs),spaces,sectors,aip_sup_strs,"".join(obstacles),"".join(airports),"".join(tracks),"".join(sigpoints),notamareas,weather,terrelev,variation)