Exemplo 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)
Exemplo n.º 2
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)
Exemplo 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
Exemplo n.º 4
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)
Exemplo n.º 5
0
kml = Kml(name="Overlays", open=1)

# GroundOverlay
ground = kml.newgroundoverlay(name='GroundOverlay Test')
ground.icon.href = 'http://simplekml.googlecode.com/hg/samples/resources/smile.png'
ground.gxlatlonquad.coords = [(18.410524, -33.903972), (18.411429, -33.904171),
                              (18.411757, -33.902944), (18.410850, -33.902767)]
# or
#ground.latlonbox.north = -33.902828
#ground.latlonbox.south = -33.904104
#ground.latlonbox.east =  18.410684
#ground.latlonbox.west =  18.411633
#ground.latlonbox.rotation = -14

# ScreenOverlay
screen = kml.newscreenoverlay(name='ScreenOverlay Test')
screen.icon.href = 'http://simplekml.googlecode.com/hg/samples/resources/simplekml-logo.png'
screen.overlayxy = OverlayXY(x=0,
                             y=1,
                             xunits=Units.fraction,
                             yunits=Units.fraction)
screen.screenxy = ScreenXY(x=15,
                           y=15,
                           xunits=Units.pixels,
                           yunits=Units.insetpixels)
screen.size.x = -1
screen.size.y = -1
screen.size.xunits = Units.fraction
screen.size.yunits = Units.fraction

# PhotoOverlay
Exemplo n.º 6
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)
Exemplo n.º 7
0
kml = Kml(name="Overlays", open=1)

# GroundOverlay
ground = kml.newgroundoverlay(name='GroundOverlay Test')
ground.icon.href = 'http://simplekml.googlecode.com/hg/samples/resources/smile.png'
ground.gxlatlonquad.coords = [(18.410524,-33.903972),(18.411429,-33.904171),(18.411757,-33.902944),(18.410850,-33.902767)]
# or
#ground.latlonbox.north = -33.902828
#ground.latlonbox.south = -33.904104
#ground.latlonbox.east =  18.410684
#ground.latlonbox.west =  18.411633
#ground.latlonbox.rotation = -14

# ScreenOverlay
screen = kml.newscreenoverlay(name='ScreenOverlay Test')
screen.icon.href = 'http://simplekml.googlecode.com/hg/samples/resources/simplekml-logo.png'
screen.overlayxy = OverlayXY(x=0,y=1,xunits=Units.fraction,yunits=Units.fraction)
screen.screenxy = ScreenXY(x=15,y=15,xunits=Units.pixel,yunits=Units.insetpixels)
screen.size.x = -1
screen.size.y = -1
screen.size.xunits = Units.fraction
screen.size.yunits = Units.fraction

# PhotoOverlay
photo = kml.newphotooverlay(name='PhotoOverlay Test')
photo.camera = Camera(longitude=18.410858, latitude=-33.904446, altitude=50, altitudemode=AltitudeMode.clamptoground)
photo.point.coords = [(18.410858,-33.90444)]
photo.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/camera.png'
photo.icon.href = 'http://simplekml.googlecode.com/hg/samples/resources/stadium.jpg'
photo.viewvolume = ViewVolume(-25,25,-15,15,1)
Exemplo n.º 8
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)
Exemplo n.º 9
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)
Exemplo n.º 10
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)
Exemplo n.º 11
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)