Esempio n. 1
0
def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,
             figs, colorbar=None, **kw):
    """TODO: LatLon bbox, list of figs, optional colorbar figure,
    and several simplekml kw..."""

    kml = Kml()
    altitude = kw.pop('altitude', 1e0) #2e7)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude, roll=roll, tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0
    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        #ground.color = kw.pop('color', '9effffff') ##kw.pop('color', '9effffff')
        
        ground.atomauthor = kw.pop('author', 'PyHum')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode',
                                       'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.west = urcrnrlon

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0, y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015, y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5, y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
Esempio n. 2
0
    def make_kml(self, times, figs, fileout, colorbar=None, debug=False, **kw):
        """TODO: LatLon bbox, list of figs, optional colorbar figure,
		and several simplekml kw..."""

        kml = Kml()
        altitude = kw.pop('altitude', 2e7)
        roll = kw.pop('roll', 0)
        tilt = kw.pop('tilt', 0)
        altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
        camera = Camera(latitude=np.mean([self.urcrnrlat, self.llcrnrlat]),
                        longitude=np.mean([self.urcrnrlon, self.llcrnrlon]),
                        altitude=altitude,
                        roll=roll,
                        tilt=tilt,
                        altitudemode=altitudemode)

        # we need another date to close last interval
        dt = times[1] - times[0]
        next_time = times[-1] + dt
        times.append(next_time)

        kml.document.camera = camera
        draworder = 0
        for fig in figs:  # NOTE: Overlays are limited to the same bbox.
            draworder += 1
            ground = kml.newgroundoverlay(name='GroundOverlay')
            ground.draworder = draworder
            ground.visibility = kw.pop('visibility', 1)
            ground.name = kw.pop('name', 'overlay')
            ground.color = kw.pop('color', '9effffff')
            ground.atomauthor = kw.pop('author', 'esm')
            ground.latlonbox.rotation = kw.pop('rotation', 0)
            ground.description = kw.pop('description', 'Matplotlib figure')
            ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
            ground.icon.href = fig
            ground.latlonbox.east = self.llcrnrlon
            ground.latlonbox.south = self.llcrnrlat
            ground.latlonbox.north = self.urcrnrlat
            ground.latlonbox.west = self.urcrnrlon
            # date span
            ground.timespan.begin = times[draworder -
                                          1].strftime(format="%Y-%m-%d")
            ground.timespan.end = times[draworder].strftime(format="%Y-%m-%d")

        kmzfile = kw.pop('kmzfile', self.plotdir + fileout)
        kml.savekmz(kmzfile)
        return None
Esempio n. 3
0
def make_kml(llcrnrlon,
             llcrnrlat,
             urcrnrlon,
             urcrnrlat,
             figs,
             tim,
             colorbar=None,
             **kw):
    """TODO: LatLon bbox, list of figs, optional colorbar figure,
    and several simplekml kw..."""

    kml = Kml()

    altitude = kw.pop('altitude', 2e7)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)

    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    author = kw.pop('author', 'ocefpaf')
    rotation = kw.pop('rotation', 0)
    description = kw.pop('description', 'Matplotlib figure')
    name = kw.pop('name', 'overlay')
    gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
    visibility = kw.pop('visibility', 1)

    kml.document.camera = camera
    kml.document.description = description
    kml.document.author = author

    draworder = 0
    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        begin = str(datetime.utcfromtimestamp(tim[draworder]))
        end = str(datetime.utcfromtimestamp(tim[draworder + 1]))

        ground = kml.document.newgroundoverlay(name=name + " at " + begin)

        print(ground.name)

        #ground.draworder = draworder
        ground.visibility = visibility

        ground.gxaltitudemode = gxaltitudemode

        ground.timespan.begin = begin
        ground.timespan.end = end

        ground.icon.href = fig
        # this below is not working for some reason
        #ground.icon.RefreshMode =  RefreshMode.oninterval
        #ground.icon.refreshInterval = 300
        #ground.icon.viewRefreshMode = ViewRefreshMode.onstop
        #ground.icon.viewRefreshTime = 2
        #ground.icon.viewBoundScale = 0.85

        ground.latlonbox.rotation = rotation
        ground.latlonbox.east = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.west = urcrnrlon

        draworder += 1

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='Legend')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0,
                                     y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015,
                                   y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5,
                                       y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
    return kml
Esempio n. 4
0
def run_module(mod_name, query_name, database_names, activity, key_timestamp,
               sql_query):

    global records
    global total_loc_records

    for db in database_names:
        print("\tExecuting module on: " + db)

        if args.k == True and activity == "Location":
            kml = Kml()
            sharedstyle = Style()
            sharedstyle.iconstyle.color = 'ff0000ff'

        conn = sqlite3.connect(db)
        with conn:
            conn.row_factory = sqlite3.Row
            cur = conn.cursor()

        try:
            sql = sql_query
            cur.execute(sql)
            rows = cur.fetchall()
            num_records = str(len(rows))

            print("\t\tNumber of Records: " + num_records)
            records = records + len(rows)

            headers = []
            for x in cur.description:
                headers.append(x[0])

            loc_records = 0

            for row in rows:
                col_row = OrderedDict()
                col_row = (OrderedDict(list(zip(headers, row))))

                data_stuff = ""

                for k, v in six.iteritems(col_row):

                    data = "[" + str(k) + ": " + str(v) + "] "

                    try:
                        data_stuff = data_stuff + data
                    except:
                        data_stuff = [
                            x for x in data_stuff if x in string.printable
                        ]
                        data_stuff = data_stuff + data

                if args.o == 'csv':
                    key = col_row[key_timestamp]
                    try:
                        loccsv.writerow(
                            [key, activity, data_stuff, db, mod_name])
                    except:
                        loccsv.writerow([
                            key, activity,
                            data_stuff.encode('utf8'), db, mod_name
                        ])

                elif args.o == 'sql':
                    key = col_row[key_timestamp]
                    cw.execute(
                        "INSERT INTO APOLLO (Key, Activity, Output, Database, Module) VALUES (?, ?, ?, ?, ?)",
                        (key, activity, data_stuff, db, mod_name))

                if len(rows) > 0:
                    if args.k == True and activity == "Location":
                        coords_search = re.search(
                            r'COORDINATES: [\d\.\,\ \-]*', data_stuff)
                        coords = coords_search.group(0).split(" ")

                        point = kml.newpoint(name=key)
                        point.description = ("Data: " + data_stuff)
                        point.timestamp.when = key
                        point.style = sharedstyle
                        point.coords = [(coords[2], coords[1])]

                        loc_records = loc_records + 1
                        total_loc_records = total_loc_records + 1

            if len(rows) > 0:
                if args.k == True and activity == "Location":
                    kmzfilename = query_name + ".kmz"
                    print("\t\tNumber of Location Records: " +
                          str(loc_records))
                    print("\t\t===> Saving KMZ to " + kmzfilename + "...")
                    kml.savekmz(kmzfilename)

        except:
            print(
                "\t***WARNING***: Could not parse database [" + db +
                "]. Often this is due to file permissions, or changes in the database schema. This also happens with same-named databases that contain different data or database schemas (ie: cache_encryptedB.db or knowledgeC.db). If it should work, try using chown/chmod to change permissions/ownership."
            )
Esempio n. 5
0
def make_kml(extent, figs, colorbar=None, **kw):
    """
    Parameters
    ----------

    extent : tuple
        (lm,lM,Lm,LM)
        lower left corner longitude
        upper right corner longitude
        lower left corner Latitude
        upper right corner Latitude

    altitude : float
    altitudemode :
    roll : float
    tilt : float
    visibility : int

    """

    lm = extent[0]
    lM = extent[1]
    Lm = extent[2]
    LM = extent[3]

    kml = Kml()

    altitude = kw.pop('altitude', 2e6)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)

    camera = Camera(latitude=np.mean([Lm, LM]),
                    longitude=np.mean([lm, lM]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera

    draworder = 0

    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'author')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = lM
        ground.latlonbox.south = Lm
        ground.latlonbox.north = LM
        ground.latlonbox.west = lm

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0,
                                     y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015,
                                   y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5,
                                       y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
# Style of the Track
trk.iconstyle.icon.href = ""
trk.labelstyle.scale = 1
trk.linestyle.width = 10
trk.linestyle.color = '7f00ff00' # aabbggrr

gps.iconstyle.icon.href = ""
gps.labelstyle.scale = 0
gps.linestyle.width = 4
gps.linestyle.color = '7fff0000'


# Saving
#kml.save("Extended-Kalman-Filter-CTRV.kml")
kml.savekmz("Extended-Kalman-Filter-CTRV-Adaptive.kmz")

# <codecell>

print('Exported KMZ File for Google Earth')

# <headingcell level=2>

# Screenshot

# <markdowncell>

# ![Google Earth](https://raw.github.com/balzer82/Kalman/master/Extended-Kalman-Filter-CTRV-Adaptive-Kurve.jpg)

# <markdowncell>
# Style of the Track
trk.iconstyle.icon.href = ""
trk.labelstyle.scale = 1
trk.linestyle.width = 4
trk.linestyle.color = '7fff0000'

gps.iconstyle.icon.href = ""
gps.labelstyle.scale = 0
gps.linestyle.width = 3
gps.linestyle.color = '7fffffff'


# Saving
#kml.save("Extended-Kalman-Filter-CTRV.kml")
kml.savekmz("Extended-Kalman-Filter-CTRV.kmz")

# <codecell>

print('Exported KMZ File for Google Earth')

# <codecell>


# <codecell>


# <codecell>


Esempio n. 8
0
def make_kml(llcrnrlon,
             llcrnrlat,
             urcrnrlon,
             urcrnrlat,
             figs,
             colorbar=None,
             times=None,
             **kw):
    """
    TODO: LatLon bbox, list of figs, optional colorbar figure,
    and several simplekml kw ...
    TJL - Obtained from
    http://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/

    """
    if not SIMPLEKML_FLAG:
        print('***ERROR!***')
        print('simplekml not installed, download from',
              'https://pypi.python.org/pypi/simplekml/')
        return
    kml = Kml()
    altitude = kw.pop('altitude', 2e7)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0

    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'ocefpaf')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        if times:
            ground.timespan.begin = times[0]
            ground.timespan.end = times[1]
        ground.icon.href = fig
        # TJL - swapping west/east to match LL vs. UR properly
        ground.latlonbox.west = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.east = urcrnrlon

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0,
                                     y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015,
                                   y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5,
                                       y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
Esempio n. 9
0
def main(input, output, ElRes, axes, nokeepfiles=True):
    

    # Parse input file ##############################
    data=parse_csv(input)

    Ellipsoids={}
    AxL={}
    AxM={}
    AxS={}
    for i in range(len(data)):
    
        # instantiate #####################################
        Ellipsoids[i]=Icosahedron(ElRes,data['description'][i])
        if axes:
            AxL[i]=Axis(data['description'][i]+'_axisLong')
            AxM[i]=Axis(data['description'][i]+'_axisMed')
            AxM[i].rotate_about_zaxis(math.pi/2.) # get correct orientation
            AxS[i]=Axis(data['description'][i]+'_axisShort')
            AxS[i].rotate_about_yaxis(math.pi/2.) # get correct orientation
    
        # re-shape ########################################
        ax=([data['A'][i],data['B'][i],data['C'][i]])
        ax.sort(key=float,reverse=True)
        Ellipsoids[i].stretch(ax[0],ax[1],ax[2])
        if axes:
            AxL[i].stretch(ax[0],ax[0],ax[0])
            AxM[i].stretch(ax[0],ax[1],ax[0]) # axis is in y-direction
            AxS[i].stretch(ax[0],ax[0],ax[2]) # axis is in z-direction
    
        #Define Rotations ################################
        plunge=data['plunge'][i]*math.pi/180.
        # trend and strike are modified to make them measured relative to North at 0 with clockwise positive
        trend =math.pi/2.-data['trend'][i] *math.pi/180.
        strike=math.pi/2.-data['strike'][i]*math.pi/180.
        dip=data['dip'][i]*math.pi/180.
        # gamma, third rotation about the ellipsoid long axis, is derived as below
        gamma=-1*math.atan(-1*math.tan(dip)*math.cos(strike-trend))
        
        # Rotate ellipsoid to match user-defined orientation 
        Ellipsoids[i].rotate_AlphaBetaGamma(plunge,trend,gamma) 
        if axes:
            AxL[i].rotate_AlphaBetaGamma(plunge,trend,gamma)
            AxM[i].rotate_AlphaBetaGamma(plunge,trend,gamma)
            AxS[i].rotate_AlphaBetaGamma(plunge,trend,gamma)
        
        # Rotate ellipsoid to match google-earth coordinates
        Ellipsoids[i].rotate_eulerXY(math.pi,math.pi/2.)
        if axes:
            AxL[i].rotate_eulerXY(math.pi,math.pi/2.)
            AxM[i].rotate_eulerXY(math.pi,math.pi/2.)
            AxS[i].rotate_eulerXY(math.pi,math.pi/2.)
                
        # Write .dae files ###############################
        name='./'+Ellipsoids[i].name+'.dae'
        c=colours(data['colour'][i])
        t=(1.0)*data['transparency'][i].item()
        write_collada_file(Ellipsoids[i].TP,
                           Ellipsoids[i].NP,
                           Ellipsoids[i].indices,
                           name,
                           c[0],c[1],c[2],t)
        if axes:
            write_collada_file(AxL[i].TP,
                               AxL[i].NP,
                               AxL[i].indices,
                               './'+AxL[i].name+'.dae',
                               colours('black')[0],
                               colours('black')[1],
                               colours('black')[2],
                               0.0,
                               double_sided=True)
            write_collada_file(AxM[i].TP,
                               AxM[i].NP,
                               AxM[i].indices,
                               './'+AxM[i].name+'.dae',
                               colours('grey')[0],
                               colours('grey')[1],
                               colours('grey')[2],
                               0.0,
                               double_sided=True)
            write_collada_file(AxS[i].TP,
                               AxS[i].NP,
                               AxS[i].indices,
                               './'+AxS[i].name+'.dae',
                               colours('white')[0],
                               colours('white')[1],
                               colours('white')[2],
                               0.0,
                               double_sided=True)
                           


    # Create a KML document #########################
    kml = Kml()
    kml.document.name = "Ellipsoids"
                   
    for i in range(len(data)):
        mod = kml.newmodel(altitudemode=AltitudeMode.relativetoground,
                           location='<longitude>'+repr(data['lon'][i])+'</longitude>'+
                                    '<latitude>'+repr(data['lat'][i])+'</latitude>'+
                                    '<altitude>'+repr(data['alt'][i])+'</altitude>',
                           visibility=1,
                           name=data['description'][i]
                           )
        mod.link.href=('files/'+Ellipsoids[i].name+'.dae')
        kml.addfile('./'+Ellipsoids[i].name+'.dae')
        if axes:
            modaxL = kml.newmodel(altitudemode=AltitudeMode.relativetoground,
                                location='<longitude>'+repr(data['lon'][i])+'</longitude>'+
                                         '<latitude>'+repr(data['lat'][i])+'</latitude>'+
                                         '<altitude>'+repr(data['alt'][i])+'</altitude>',
                                visibility=1,
                                name=data['description'][i]+'_axesL'
                           )
            modaxL.link.href=('files/'+AxL[i].name+'.dae')
            kml.addfile('./'+AxL[i].name+'.dae')
            modaxM = kml.newmodel(altitudemode=AltitudeMode.relativetoground,
                                location='<longitude>'+repr(data['lon'][i])+'</longitude>'+
                                         '<latitude>'+repr(data['lat'][i])+'</latitude>'+
                                         '<altitude>'+repr(data['alt'][i])+'</altitude>',
                                visibility=1,
                                name=data['description'][i]+'_axesM'
                           )
            modaxM.link.href=('files/'+AxM[i].name+'.dae')
            kml.addfile('./'+AxM[i].name+'.dae')
            modaxS = kml.newmodel(altitudemode=AltitudeMode.relativetoground,
                                location='<longitude>'+repr(data['lon'][i])+'</longitude>'+
                                         '<latitude>'+repr(data['lat'][i])+'</latitude>'+
                                         '<altitude>'+repr(data['alt'][i])+'</altitude>',
                                visibility=1,
                                name=data['description'][i]+'_axesS'
                           )
            modaxS.link.href=('files/'+AxS[i].name+'.dae')
            kml.addfile('./'+AxS[i].name+'.dae')

    kml.savekmz(output)
    if (nokeepfiles):
        # Remove all intermediate Collada Files
        for i in range(len(data)):
            os.remove('./'+Ellipsoids[i].name+'.dae')
        if axes:
            for i in range(len(data)):
                #os.remove('./'+ElAx[i].name+'.dae')
                os.remove('./'+AxL[i].name+'.dae')
                os.remove('./'+AxM[i].name+'.dae')
                os.remove('./'+AxS[i].name+'.dae')
Esempio n. 10
0
                    altStr2Num(topAlt_1), altStr2Num(bottomAlt_1), clss_1)
    BCTR.generatePoly(ctr)
    print(BCTR.name + " polygon generated")

    tma = kml.newfolder(name="Budapest TMA")

    ENR2_1 = "C:/Users/bakad/OneDrive/Desktop/AIRAC/2020-06-18-AIRAC/html/eAIP/LH-ENR-2.1-en-HU.html"
    tmaPhrase = "BUDAPEST TMA"
    TMA = parseTMA(ENR2_1, tmaPhrase, 3)

    for arsp in TMA:
        box = Airspace(arsp[0], splitCoordinates(arsp[1]), altStr2Num(arsp[2]),
                       altStr2Num(arsp[3]), arsp[4])
        fld = tma.newfolder(name=box.name, open=False)
        box.generatePoly(fld)
        print(box.name + " polygon generated")

    glid = kml.newfolder(name="Glider areas")
    ENR5_5 = "C:/Users/bakad/OneDrive/Desktop/AIRAC/2020-06-18-AIRAC/html/eAIP/LH-ENR-5.5-en-HU.html"
    lhsgPhrase = "LHSG"
    LHSG = parseLHSG(ENR5_5, lhsgPhrase, 0)

    for arsp in LHSG:
        box = Airspace(arsp[0], splitCoordinates(arsp[6]),
                       altStr2Num(arsp[12]), altStr2Num(arsp[8]), "G")
        fld = glid.newfolder(name=box.name, open=False)
        box.generatePoly(fld)
        print(box.name + " polygon generated")

    kml.savekmz("test.kmz")
Esempio n. 11
0
def make_kml(extent,figs,colorbar=None, **kw):
    """
    Parameters
    ----------

    extent : tuple
        (lm,lM,Lm,LM)
        lower left corner longitude
        upper right corner longitude
        lower left corner Latitude
        upper right corner Latitude

    altitude : float
    altitudemode :
    roll : float
    tilt : float
    visibility : int

    """

    lm = extent[0]
    lM = extent[1]
    Lm = extent[2]
    LM = extent[3]

    kml = Kml()

    altitude = kw.pop('altitude', 2e6)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)

    camera = Camera(latitude  = np.mean([Lm, LM]),
                    longitude = np.mean([lm, lM]),
                    altitude = altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera

    draworder = 0

    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'author')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = lM
        ground.latlonbox.south = Lm
        ground.latlonbox.north = LM
        ground.latlonbox.west = lm

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0, y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015, y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5, y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
Esempio n. 12
0
def make_kml(location,
             period,
             llcrnrlon,
             llcrnrlat,
             urcrnrlon,
             urcrnrlat,
             figs,
             colorbar=None,
             **kw):
    """TODO: LatLon bbox, list of figs, optional colorbar figure, and several simplekml kw..."""

    kml = Kml()
    altitude = kw.pop('altitude', 2e5)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)

    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0

    loc_names = {
        'BOG': 'Bogota D.C. y Alrededores',
        'COL': 'Republica de Colombia'
    }

    str_period = kw['name']

    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'jchavarro')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop(
            'description', 'Densidad de Descargas Electricas en {} <br />'
            'Periodo: {} <br />'
            'Red Linet/Keraunos Suministrado IDEAM <br />'
            'Elaborado por: OSPA - IDEAM <br /><br />'
            '<img src="http://bart.ideam.gov.co/portal/prono_fin_semana/ospa/logo/logos.png" alt="picture" width="151" height="25" align="left" />'
            '<br /><br />'.format(loc_names[location], str_period))

        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.west = urcrnrlon

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).

        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0,
                                     y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015,
                                   y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5,
                                       y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')

    kml.savekmz(kmzfile)
Esempio n. 13
0
def run_module(mod_name, query_name, database_names, activity, key_timestamp,
               sql_query):

    global records
    global total_loc_records

    for db in database_names:
        print("\tExecuting module on: " + db)

        if args.k == True and "Location" in activity:
            kml = Kml()
            sharedstyle = Style()
            sharedstyle.iconstyle.color = 'ff0000ff'

        conn = sqlite3.connect(db)
        with conn:
            conn.row_factory = sqlite3.Row
            cur = conn.cursor()

        try:
            try:
                sql = sql_query
                cur.execute(sql)
            except:
                print(
                    "\tSQL Query not supported for this version of the database."
                )

            try:
                rows = cur.fetchall()
            except:
                print("\t\tERROR: Cannot fetch query contents.")

            num_records = str(len(rows))
            print("\t\tNumber of Records: " + num_records)
            records = records + len(rows)

            headers = []
            for x in cur.description:
                headers.append(x[0])

            loc_records = 0

            for row in rows:
                col_row = OrderedDict()
                col_row = (OrderedDict(list(zip(headers, row))))

                data_stuff = ""
                for k, v in iter(col_row.items()):
                    data = "[" + str(k) + ": " + str(v) + "] "

                    try:
                        data_stuff = data_stuff + data
                    except:
                        data_stuff = [
                            x for x in data_stuff if x in string.printable
                        ]
                        data_stuff = data_stuff + data

                if output == 'csv':
                    key = col_row[key_timestamp]
                    if "\n" in data_stuff:
                        data_stuff = data_stuff.replace('\n', "<nl>")
                    if "\r" in data_stuff:
                        data_stuff = data_stuff.replace('\r', "<cr>")
                    try:
                        loccsv.writerow(
                            [key, activity, data_stuff, db, mod_name])
                    except:
                        loccsv.writerow([
                            key, activity,
                            data_stuff.encode('utf8'), db, mod_name
                        ])

                elif output == 'sql':
                    key = col_row[key_timestamp]
                    cw.execute(
                        "INSERT INTO APOLLO (Key, Activity, Output, Database, Module) VALUES (?, ?, ?, ?, ?)",
                        (key, activity, data_stuff, db, mod_name))

                elif output == 'sql_json':
                    key = col_row[key_timestamp]
                    cw.execute(
                        "INSERT INTO APOLLO (Key, Activity, Output, Database, Module) VALUES (?, ?, ?, ?, ?)",
                        (key, activity, json.dumps(col_row,
                                                   indent=4), db, mod_name))

                if len(rows) > 0:
                    if args.k == True and "COORDINATES" in data_stuff:
                        coords_search = re.search(
                            r'COORDINATES: [\d\.\,\ \-]*', data_stuff)
                        coords = coords_search.group(0).split(" ")

                        point = kml.newpoint(name=key)
                        point.description = ("Data: " + data_stuff)
                        point.timestamp.when = key
                        point.style = sharedstyle
                        point.coords = [(coords[2], coords[1])]

                        loc_records = loc_records + 1
                        total_loc_records = total_loc_records + 1

            if loc_records:
                kmzfilename = query_name + ".kmz"
                print("\t\tNumber of Location Records: " + str(loc_records))
                print("\t\t===> Saving KMZ to " + kmzfilename + "...")
                kml.savekmz(kmzfilename)

        except:
            print("\t\tERROR: Problem with database. Could be unsupported.")
Esempio n. 14
0
def nparray_to_kml(input_array,
                   out_name,
                   ncol=ncol,
                   nrow=nrow,
                   xll=xll,
                   yll=yll,
                   cellsize=np.mean([delc, delr]),
                   colorbar=None,
                   **kw):

    from osgeo import gdal, osr
    from mpl_toolkits.basemap import Basemap
    from simplekml import (Kml, OverlayXY, ScreenXY, Units, RotationXY,
                           AltitudeMode, Camera)

    # turn the numpy array into an asc raster in UTM zone 2S
    the_asc = os.path.join(workspace, "{}.asc".format(out_name))
    np.savetxt(the_asc, input_array)

    new_first = (
        'NCOLS {}\n'  # these are the parameters for the .asc file
        'NROWS {}\n'
        'XLLCENTER {}\n'
        'YLLCENTER {}\n'
        'CELLSIZE {}\n'
        'NODATA_value -999.0\n'.format(ncol, nrow, xll, yll,
                                       np.mean([delc, delr])))

    with open(the_asc, 'r+') as file:  # add in new first line and save file
        file_data = file.read()
        file.seek(0, 0)
        file.write(new_first + '\n' + file_data)

# turn the new .asc file into a geo-tiff
    the_tif = os.path.join(workspace, "{}.tif".format(out_name))
    in_raster = gdal.Open(the_asc)
    gdal.Warp(the_tif,
              in_raster,
              srcSRS='EPSG:{}'.format(model_epsg),
              dstSRS='EPSG:4326')

    # plotting function to plot and format the tif into a Gearth image that doesnt look like crap
    # Note This plotting function is clunky and not very good, but it is the best example I could find so far, probably should do better
    # One of its main issues is that it reads the data upside down and it needs to be flipped with a command, obviously something is wrong
    # from https://gis.stackexchange.com/questions/184727/plotting-raster-maps-in-python

    the_png = os.path.join(workspace, "{}.png".format(out_name))

    ds = gdal.Open(the_tif)  # tif file in
    data = ds.ReadAsArray()

    data = np.flipud(data)  # this is where that sketchy data flip happens

    gt = ds.GetGeoTransform()
    proj = ds.GetProjection()

    xres = gt[1]
    yres = gt[5]
    xmin = gt[0] + xres * 0.5
    xmax = gt[0] + (xres * ds.RasterXSize) - xres * 0.5
    ymin = gt[3] + (yres * ds.RasterYSize) + yres * 0.5
    ymax = gt[3] - yres * 0.5
    x_center = (xmin + xmax) / 2
    y_center = (ymin + ymax) / 2

    m = Basemap(llcrnrlon=xmin,
                llcrnrlat=ymin,
                urcrnrlon=xmax,
                urcrnrlat=ymax,
                projection='merc',
                lat_0=y_center,
                lon_0=x_center)
    x = np.linspace(0, m.urcrnrx, data.shape[1])
    y = np.linspace(0, m.urcrnry, data.shape[0])
    xx, yy = np.meshgrid(x, y)

    # create the igure object scaled for google earth   from https://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/
    aspect = np.cos(np.mean([ymin, ymax]) * np.pi / 180.0)
    xsize = np.ptp([xmax, xmin]) * aspect
    ysize = np.ptp([ymax, ymin])
    aspect = ysize / xsize

    if aspect > 1.0:
        figsize = (10.0 / aspect, 10.0)
    else:
        figsize = (10.0, 10.0 * aspect)

    if False:

        plt.ioff()  # Make `True` to prevent the KML components from poping-up.
    fig = plt.figure(figsize=figsize, frameon=False, dpi=1024 // 10)
    # KML friendly image.  If using basemap try: `fix_aspect=False`.
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

    cs = m.pcolormesh(
        xx, yy, data, cmap=plt.cm.jet
    )  # alpha = .9)                              ########################   make a cmap option
    fig.savefig(the_png, transparent=False, format='png', dpi=600)

    # this is the save KML overlay part, there are some options in here that can be changed for visualization stuff
    # from https://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/

    the_kml = os.path.join(workspace, "{}.kmz".format(out_name))

    kml = Kml()
    altitude = kw.pop('altitude', 2e4)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([ymax, ymin]),
                    longitude=np.mean([xmax, xmin]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0
    for fig in [the_png]:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'ocefpaf')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = xmin
        ground.latlonbox.south = ymin
        ground.latlonbox.north = ymax
        ground.latlonbox.west = xmax

    # now make a legend for the kml file
    the_ledg = os.path.join(workspace, "legend_{}.png".format(out_name))

    fig = plt.figure(figsize=(1.5, 4.0), facecolor=None, frameon=False)
    ax = fig.add_axes([0.0, 0.05, 0.2, 0.9])
    cb = fig.colorbar(cs, cax=ax)
    cb.set_label(out_name, rotation=-90, color='k', labelpad=20)
    fig.savefig(
        the_ledg, transparent=True, format='png'
    )  # Change transparent to True if your colorbar is not on space :)

    screen = kml.newscreenoverlay(name='ScreenOverlay')
    screen.icon.href = the_ledg
    screen.overlayxy = OverlayXY(x=0,
                                 y=0,
                                 xunits=Units.fraction,
                                 yunits=Units.fraction)
    screen.screenxy = ScreenXY(x=0.015,
                               y=0.075,
                               xunits=Units.fraction,
                               yunits=Units.fraction)
    screen.rotationXY = RotationXY(x=0.5,
                                   y=0.5,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
    screen.size.x = 0
    screen.size.y = 0
    screen.size.xunits = Units.fraction
    screen.size.yunits = Units.fraction
    screen.visibility = 1

    kmzfile = kw.pop('kmzfile', the_kml)
    kml.savekmz(kmzfile)
Esempio n. 15
0
def plot_map(a, stadata, fechas, anch=80, ms=3, sel='all', op=''):
    print(
        "NUEVA VERSIÓN, AHORA EN LA CARPETA DE TRABAJO SE GUARDA ARCHIVO KMZ CON LOCALIZACION(ES)"
    )
    print(
        "QUIZAS (LO MAS PROBABLE) SEA NECESARIO INSTALAR LIBRERIA KML, EN EL PROMPT EJECUTAR"
    )
    print("conda install -c conda-forge simplekml")
    print("SI SALE EL ERROR 'NO MODULE NAME SIMPLEKML'\n\n\n\n\n")
    kml = Kml()
    #a = pd.DataFrame.from_dict(a, orient='index')
    #stadata = pd.DataFrame.from_dict(stadata, orient='index')
    if op == 'REAV':
        zona = a.iloc[0]['zona_id']
        cod = a.iloc[0]['vol_cod']
        latv = float(a.iloc[0]['vol_lat'])
        lonv = float(a.iloc[0]['vol_lon'])
        nref = float(a.iloc[0]['vol_alt'])
        t_deg = anch / (111.320 * cos(radians(latv)))
        ancho = haversine(float(lonv), float(latv),
                          float(lonv) + float(t_deg), float(latv))
        ancho = int(round(ancho))
        factorlatlon = param_volcan(zona, cod)[0]
        londelta = float(t_deg / 2)
        latdelta = float(londelta * factorlatlon)
        tiev, late, lone, profe, ML = [], [], [], [], []
        for i in range(0, len(a)):
            tiev.append(a.iloc[0]['ev_tipoev'])
            late.append(a.iloc[0]['ev_lat'])
            lone.append(a.iloc[0]['ev_lon'])
            profe.append(a.iloc[0]['ev_prof'])
            ML.append(a.iloc[0]['ev_ml'])
    else:
        zona = a.zona_id
        cod = a.vol_cod
        latv = float(a.vol_lat)
        lonv = float(a.vol_lon)
        nref = a.vol_alt
        tiev = a.ev_tipoev
        late = a.ev_lat
        lone = a.ev_lon
        profe = a.ev_prof
        ML = a.ev_ml
        t_deg = anch / (111.320 * cos(radians(latv[0])))
        ancho = haversine(float(lonv[0]), float(latv[0]),
                          float(lonv[0]) + float(t_deg), float(latv[0]))
        ancho = int(round(ancho))
        factorlatlon = param_volcan(zona[0], cod[0])[0]
        londelta = float(t_deg / 2)
        latdelta = float(londelta * factorlatlon)
    gs = gen_fig_topo()
    x, y = 'prof', 'lat'  #Latitud vs prof (x,y,datos_x,datos_y,nref)
    subfig_prof(x, y, profe, late, nref, gs, latv, lonv, latdelta, londelta,
                tiev, 'hypo', ms, ML)
    gs, m = gen_fig_map(nref, latv, lonv, latdelta, londelta, zona, cod, gs,
                        factorlatlon, ancho / 4, t_deg, op, fechas)
    if op != 'reav':
        #plot_esta(m,stadata,kml,ms)
        print(sel)
        from matplotlib.lines import Line2D
        legend_elements = [
            Line2D([], [],
                   marker='o',
                   color='k',
                   label='ML=1',
                   lw=0,
                   markersize=ms * 1,
                   markerfacecolor='none'),
            Line2D([], [],
                   marker='o',
                   color='k',
                   label='ML=2',
                   lw=0,
                   markersize=ms * 2,
                   markerfacecolor='none'),
            Line2D([], [],
                   marker='o',
                   color='k',
                   label='ML=3',
                   lw=0,
                   markersize=ms * 3,
                   markerfacecolor='none'),
            Line2D([], [],
                   marker='^',
                   color='k',
                   label='Est. Sísmica',
                   lw=0,
                   markerfacecolor='k',
                   markersize=ms * 2)
        ]
        if sel == 'all':
            legend_elements.extend([
                Line2D([], [],
                       marker='o',
                       color='k',
                       label='VT',
                       lw=0,
                       markerfacecolor='r',
                       markersize=ms * 3),
                Line2D([], [],
                       marker='o',
                       color='k',
                       label='LP',
                       lw=0,
                       markerfacecolor='y',
                       markersize=ms * 3)
            ])
        else:
            if sel == 'VT': color = 'r'
            elif sel == 'LP': color = 'y'
            legend_elements.extend([
                Line2D([], [],
                       marker='o',
                       color='k',
                       label=sel,
                       lw=0,
                       markerfacecolor=color,
                       markersize=ms * 3),
                Line2D([], [],
                       marker='o',
                       color='none',
                       label='',
                       lw=0,
                       markerfacecolor='none',
                       markersize=ms * 3)
            ])
        #legend = plt.gca().legend(ncol=2,title='Leyenda',handles=legend_elements, loc='lower right', fontsize=ms*3)
        #plt.setp(legend.get_title(),fontsize=ms*3)
    plot_sis(late, lone, latv, lonv, latdelta, londelta, m, tiev, 'hypo', ms,
             ML)  #MAPA
    x, y = 'lon', 'prof'
    subfig_prof(x, y, lone, profe, nref, gs, latv, lonv, latdelta, londelta,
                tiev, 'hypo', ms, ML)
    path = save_fig_vol(zona, cod)

    #evs = pd.DataFrame.from_dict(a).T
    fol01 = kml.newfolder(name='ML 0-1')
    fol12 = kml.newfolder(name='ML 1-2')
    fol23 = kml.newfolder(name='ML 2-3')
    fol39 = kml.newfolder(name='ML >3')
    for index, row in a.iterrows():
        if row['ev_ml'] > 0 and row['ev_ml'] < 1.1:
            pnt = fol01.newpoint()
        elif row['ev_ml'] > 1 and row['ev_ml'] < 2.1:
            pnt = fol12.newpoint()
        elif row['ev_ml'] > 2 and row['ev_ml'] < 3.1:
            pnt = fol23.newpoint()
        elif row['ev_ml'] > 3:
            pnt = fol39.newpoint()
        if row['ev_tipoev'] == 'VT':
            pnt.style.iconstyle.color = 'ff0000ff'
        elif row['ev_tipoev'] == 'LP':
            pnt.style.iconstyle.color = 'ff00ffff'
        elif row['ev_tipoev'] == 'VD':
            pnt.style.iconstyle.color = 'ffff00ff'
        lat = row['ev_lat']
        lon = row['ev_lon']
        pnt.coords = [(lon, lat)]
        pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png'
    kml.savekmz(str(zona) + str(cod) + ".kmz")

    return path
Esempio n. 16
0
def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,
             figs, colorbar=None, times=None, **kw):
    """
    TODO: LatLon bbox, list of figs, optional colorbar figure,
    and several simplekml kw...
    TJL - Obtained from 
    http://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/
    
    """
    if not SIMPLEKML_FLAG:
        print '***ERROR!***'
        print 'simplekml not installed, download from',\
              'https://pypi.python.org/pypi/simplekml/'
        return
    kml = Kml()
    altitude = kw.pop('altitude', 2e7)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude, roll=roll, tilt=tilt,
                    altitudemode=altitudemode)
                    
    kml.document.camera = camera
    draworder = 0

    for fig in figs: #NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'ocefpaf')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode',
                                       'clampToSeaFloor')
        if times:
            ground.timespan.begin = times[0]
            ground.timespan.end   = times[1]
        ground.icon.href = fig
        #TJL - swapping west/east to match LL vs. UR properly
        ground.latlonbox.west =  llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.east =  urcrnrlon
                    
    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0, y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015, y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5, y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1
                    
    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)
Esempio n. 17
0
# Attach the model to the track
trk.model = model_car
trk.model.link.href = car_dae

# Add all the information to the track
trk.newwhen(car["when"])
trk.newgxcoord(car["coord"])

# Style of the Track
trk.iconstyle.icon.href = ""
trk.labelstyle.scale = 1
trk.linestyle.width = 4
trk.linestyle.color = '7fff0000'

# Add GPS measurement marker
fol = kml.newfolder(name="GPS Measurements")
sharedstyle = Style()
sharedstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png'

for m in range(len(latitude)):
    if GPS[m]:
        pnt = fol.newpoint(coords = [(longitude[m],latitude[m])])
        pnt.style = sharedstyle

# Saving
#kml.save("Extended-Kalman-Filter-CTRV.kml")
kml.savekmz("Extended-Kalman-Filter-CTRV.kmz")

# <codecell>

print('Exported KMZ File for Google Earth')
Esempio n. 18
0
def makeKML(llcrnrlon,
            llcrnrlat,
            urcrnrlon,
            urcrnrlat,
            figs,
            colorbar=None,
            **kw):
    """
    Borrowed from https://ocefpaf.github.io/python4oceanographers/blog/2014/03/10/gearth/
    
    This function creates a Google KMZ file for use in Google Earth. It accepts as input
    the filename(s) of the figure(s) to be converted, along with the bounding lat/lon.
    The option to include multiple figures would be useful if one were to split a single
    figure (perhaps containing contours and vectors) into separate layers in the KMZ 
    (i.e., plot the contours and vectors as different figures).

    Parameters
    ----------
    llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat : floats
        Floats specifying the extent of the figure in lat/lon degrees.
    figs : tuple
        Tuple of figure file names to be included in output.
    colorbar : string, optional
        If supplied, provides filename of colorbar figure
    """

    kml = Kml()
    altitude = kw.pop('altitude', 640000)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude,
                    roll=roll,
                    tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0
    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'ocefpaf')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.west = urcrnrlon

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0,
                                     y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015,
                                   y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5,
                                       y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)