Exemplo n.º 1
1
"""
This shows the use of the 3 different types of extended data: Data, Simple Data and Simple Array Data, as well as prettying up the data.
"""

import os
from simplekml import Kml, Types, Snippet, Color

# The KML
kml = Kml(name="ExtendedData", open=1)

# Data Example---------------------------------------------------------------------------------------------------------
# Create and style a point
pnt = kml.newpoint(name='1. World of Birds (Data)', coords =[(18.361960,-34.016543)])
pnt.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/1.png'

# Add the Data to the point
pnt.extendeddata.newdata(name='birds', value=400, displayname="Bird Species")
pnt.extendeddata.newdata(name='aviaries', value=100, displayname="Aviaries")
pnt.extendeddata.newdata(name='visitors', value=10000, displayname="Annual Visitors")


# Simple Data Example -------------------------------------------------------------------------------------------------
# Create a schema
schema = kml.newschema(name='WOW')

schema.newsimplefield(name='birds', type='int', displayname='Bird Species')
schema.newsimplefield(name='aviaries', type='int', displayname='Aviaries')
schema.newsimplefield(name='visitors', type='int', displayname='Annual Visitors')

# Create and style a point
pnt = kml.newpoint(name='2. World of Birds (Simple Data)', coords =[(18.361960,-34.017224)])
Exemplo n.º 2
0
def main(args, options):

    global DEBUG
    DEBUG = options.debug

    global VERBOSE
    VERBOSE = options.verbose

    kml = Kml()

    kml.document.name = "GPX Extent Map created by pqmap.py on %s" % datetime.now()

    count = 0
    for arg in args:
        if DEBUG or VERBOSE:
            print("arg: %s" % arg)
        for globname in glob(arg):
            count += process_arg(kml, globname)

    document_name = os.path.join(BASEDIR, DOCUMENT_NAME)
    kml.save(document_name)

    if not options.verbose:
        print()

    print("%d .gpx files processed" % count)
    print("Output is in %s" % document_name)
Exemplo n.º 3
0
    def test_kml_simple(self):
        coordinates = [
            (-76.0, 38.0, 0.0),
            (-76.0, 38.0, 10.0),
            (-76.0, 38.0, 20.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 100.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 60.0),
        ]
        # Create Coordinates
        start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
        start.save()
        for coord in coordinates:
            self.create_log_element(*coord)
        end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
        end.save()

        kml = Kml()
        UasTelemetry.kml(user=self.user,
                         logs=UasTelemetry.by_user(self.user),
                         kml=kml,
                         kml_doc=kml)
        for coord in coordinates:
            tag = self.coord_format.format(coord[1], coord[0],
                                           units.feet_to_meters(coord[2]))
            self.assertTrue(tag in kml.kml())
Exemplo n.º 4
0
    def test_kml_simple(self):
        coordinates = [
            (0, -76.0, 38.0, 0.0, 0),
            (1, -76.0, 38.0, 10.0, 0),
            (2, -76.0, 38.0, 20.0, 0),
            (3, -76.0, 38.0, 30.0, 0),
            (4, -76.0, 38.0, 100.0, 0),
            (5, -76.0, 38.0, 30.0, 0),
            (6, -76.0, 38.0, 60.0, 0),
        ]
        # Create Coordinates
        start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
        start.save()
        start.timestamp = self.now
        start.save()
        for coord in coordinates:
            self.create_log_element(*coord)
        end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
        end.save()
        end.timestamp = self.now + datetime.timedelta(seconds=7)
        end.save()

        kml = Kml()
        UasTelemetry.kml(
            user=self.user,
            logs=UasTelemetry.by_user(self.user),
            kml=kml,
            kml_doc=kml.document)
        for coord in coordinates:
            tag = self.coord_format.format(coord[2], coord[1],
                                           units.feet_to_meters(coord[3]))
            self.assertTrue(tag in kml.kml())
Exemplo n.º 5
0
    def main():

        global options, args

        if options.list_colors:
            create_color_map(COLOR_TABLE)
            sys.exit()

        output_filename = options.output

        kml = Kml()
        kml.document.name = "Test of kmldraw.py"

        for line in RAWINPUT[1:-1].split('\n'):
            text, quad = line.split("\t")
            name = text.strip()

            import re
            result = re.match(
                '\((\d+.\d+), (\d+.\d+), (-\d+.\d+), (-\d+.\d+)\)', quad)
            minlat, maxlat, minlon, maxlon = list(map(float, result.groups()))
            quad = (minlat, maxlat, minlon, maxlon)

            kmldraw(kml, name, quad)

        kml.save(output_filename)
        print("Wrote to: %s" % output_filename)
Exemplo n.º 6
0
    def get_kml(self, app_session):

        kml = Kml()

        node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon(
            href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png')))
        node_folder = kml.newfolder(name="Nodes")
        for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in
                  app_session.data_set.query(Node).all()]:
            p.style = node_style

        node_index = {}
        node_counter = 0

        arc_folder = kml.newfolder(name="Arcs")
        for flow in app_session.data_set.query(NetworkFlow).all():

            if not node_index.get(flow.orig_name, None):
                node_index.update({flow.orig_name: node_counter})
                node_counter += 1

            arc_style = Style(
                linestyle=LineStyle(color=MapFlowOutput.get_cycled_hex_colour(node_index.get(flow.orig_name)), width=4))
            l = arc_folder.newlinestring(name="arc", coords=[(flow.orig_node.longitude, flow.orig_node.latitude),
                                                             (flow.dest_node.longitude, flow.dest_node.latitude)])
            l.style = arc_style

        return kml.kml()
Exemplo n.º 7
0
    def test_kml_simple(self):
        coordinates = [
            (-76.0, 38.0, 0.0),
            (-76.0, 38.0, 10.0),
            (-76.0, 38.0, 20.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 100.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 60.0),
        ]
        # Create Coordinates
        start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
        start.save()
        for coord in coordinates:
            self.create_log_element(*coord)
        end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
        end.save()

        kml = Kml()
        UasTelemetry.kml(user=self.user,
                         logs=UasTelemetry.by_user(self.user),
                         kml=kml,
                         kml_doc=kml)
        for coord in coordinates:
            tag = self.coord_format.format(coord[1], coord[0],
                                           units.feet_to_meters(coord[2]))
            self.assertTrue(tag in kml.kml())
Exemplo n.º 8
0
def density_kml(kml_path, city, dicts, borders,
                scaling=(lambda x: x)):

    def rgb_to_bgr(color):
        return "{rgb[4]}{rgb[5]}{rgb[2]}{rgb[3]}{rgb[0]}{rgb[1]}".format(
            rgb=color)

    def add_folder(kml, data):
        def cell_to_color(value, color, scaling):
            norm_value = scaling(value)
            return '{0:02x}{1}'.format(int(norm_value * 200), color)

        folder_dict = data['dict']

        # normalizing
        maximum = data['max']
        norm_scaling = lambda x: scaling(x / maximum)

        # make a kml of polygons
        folder = kml.newfolder(name=data['name'])
        color = rgb_to_bgr(data['color'])
        folder = dict_to_kml(folder, borders, folder_dict, cell_to_color,
                             color, norm_scaling)
        return kml

    kml = Kml()

    for data in dicts:
        kml = add_folder(kml, data)

    kml.save(kml_path)
    def test_kml_filter(self):
        coordinates = [
            (-76.0, 38.0, 0.0),
            (-76.0, 38.0, 10.0),
            (-76.0, 38.0, 20.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 100.0),
            (-76.0, 38.0, 30.0),
            (-76.0, 38.0, 60.0),
        ]
        filtered_out = [(0.1, 0.001, 100), (0.0, 0.0, 0)]
        # Create Coordinates
        start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
        start.save()
        for coord in coordinates:
            self.create_log_element(*coord)
        for coord in filtered_out:
            self.create_log_element(*coord)
        end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
        end.save()

        kml = Kml()
        UasTelemetry.kml(user=self.user,
                         logs=UasTelemetry.by_user(self.user),
                         kml=kml,
                         kml_doc=kml)

        for filtered in filtered_out:
            tag = self.coord_format.format(filtered[1], filtered[0],
                                           filtered[2])
            self.assertTrue(tag not in kml.kml())

        for coord in coordinates:
            tag = self.coord_format.format(coord[1], coord[0], coord[2])
            self.assertTrue(tag in kml.kml())
Exemplo n.º 10
0
def prep_wind_kml_per_hour(data_to_show):
    ### create the kml file
    kml = Kml(open=1)
    ### name columns according to hour of day
    lon_col = "lon"
    lat_col = "lat"
    data_col = "data"
    ### create lines that represent thermals
    ### calculate centre of the small grid
    ### place the line segment in the centre
    ### take wind speed and direction and calculate coordinates
    ### of the end point of the line segment
    ### add the arrow pointer
    for i in range(1, len(data_to_show) - 1):
        x1 = -data_to_show[lon_col][i]
        y1 = data_to_show[lat_col][i]
        z1 = data_to_show[data_col][i]
        x2 = -data_to_show[lon_col][i + 1]
        y2 = data_to_show[lat_col][i + 1]
        z2 = data_to_show[data_col][i + 1]
        if z1 > 0 or z2 > 0:
            line_name = "line " + str(i)
            linestring = kml.newlinestring(name=line_name)
            linestring.coords = [(x1, y1), (x2, y2)]
            linestring.altitudemode = simplekml.AltitudeMode.relativetoground
            linestring.style.linestyle.width = 10
            linestring.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
            linestring.style.linestyle.color = '99ffac59'

    kml_file_name = "Roldanillo_wind.kml"
    kml.save(path2grid + "hours\\" + kml_file_name)
Exemplo n.º 11
0
 def get_kml(self, app_session):
     kml = Kml()
     stores = app_session.data_set.query(Store).all()
     for store in stores:
         kml.newpoint(name=store.name,
                      coords=[(store.longitude, store.latitude)])
     return kml.kml()
Exemplo n.º 12
0
def density_kml(kml_path, city, dicts, borders, scaling=(lambda x: x)):
    def rgb_to_bgr(color):
        return "{rgb[4]}{rgb[5]}{rgb[2]}{rgb[3]}{rgb[0]}{rgb[1]}".format(
            rgb=color)

    def add_folder(kml, data):
        def cell_to_color(value, color, scaling):
            norm_value = scaling(value)
            return '{0:02x}{1}'.format(int(norm_value * 200), color)

        folder_dict = data['dict']

        # normalizing
        maximum = data['max']
        norm_scaling = lambda x: scaling(x / maximum)

        # make a kml of polygons
        folder = kml.newfolder(name=data['name'])
        color = rgb_to_bgr(data['color'])
        folder = dict_to_kml(folder, borders, folder_dict, cell_to_color,
                             color, norm_scaling)
        return kml

    kml = Kml()

    for data in dicts:
        kml = add_folder(kml, data)

    kml.save(kml_path)
Exemplo n.º 13
0
def exportToKml():
    # KML
    kml = Kml()

    for aMergedWayTupleKey in tramRoutes:
        aMergedWayTuple = tramRoutes[aMergedWayTupleKey]
        aMergedWay = aMergedWayTuple[1]
        lineNames = ','.join(aMergedWayTuple[0])

        coords = list()

        for aCoordTuple in aMergedWay:
            lat = aCoordTuple[0]
            lon = aCoordTuple[1]

            coords.append((lon, lat))

        lin = kml.newlinestring(name="Pathway", description='-', coords=coords)

        r = lambda: random.randint(0, 255)
        randomColor = '#ff%02X%02X%02X' % (r(), r(), r())

        lin.style.linestyle.color = randomColor
        lin.style.linestyle.width = 10  # 10 pixels

    kml.save("singlestyle.kml")
Exemplo n.º 14
0
def exportToKml2():
    # KML
    kml = Kml()
    for aGroupedWayKey in subRoutes:
        aGroupedWay = subRoutes[aGroupedWayKey][0]
        lineNames = ','.join(aGroupedWay.lines)

        coords = list()
        for aNodeKey in aGroupedWay.nodesList:
            if type(aNodeKey) is str:
                aNode = nodesDict[aNodeKey]
                lat = aNode.lat
                lon = aNode.lon
            elif type(aNodeKey) is OsmNode:
                lat = aNodeKey.lat
                lon = aNodeKey.lon
            else:
                lat = aNodeKey[0]
                lon = aNodeKey[1]

            coords.append((lon, lat))

        lin = kml.newlinestring(name="Pathway", description='-', coords=coords)

        r = lambda: random.randint(0, 255)
        randomColor = '#ff%02X%02X%02X' % (r(), r(), r())  #random ARGB color
        lin.style.linestyle.color = randomColor
        lin.style.linestyle.width = 10  # 10 pixels

    kml.save("singlestyle.kml")
Exemplo n.º 15
0
def main():
    """Compute longitude to fit with computed latitude and checksum."""
    kml = Kml()

    kml.newpoint(name="Vitts Mill", coords=[(HOME[1], HOME[0])])
    kml.newpoint(name="Vitts Mill WP2", coords=[(WP2[1], WP2[0])])

    # known values for A, B, C
    lat = "N38 27.%d%d%d" % (A, B, C)
    clat = convert(lat)

    # all answers sum to 24
    leftovers = 24 - (A + B + C)

    # compute all values for D, E and F
    for D in range(10):
        if D > leftovers:
            continue
        for E in range(10):
            if (D + E) > leftovers:
                continue
            for F in range(10):
                if D + E + F == leftovers:
                    lon = "W91 00.%d%d%d" % (D, E, F)
                    clon = convert(lon)
                    here = (clat, clon)
                    # compute distance from posted coordinates
                    d = vincenty(HOME, here).miles
                    print(d, lat, lon)
                    name = "loc_%d%d%d%d%d%d" % (A, B, C, D, E, F)
                    kml.newpoint(name=name, coords=[(clon, clat)])
    kml.save(FILENAME)
    print("Output is in %s" % FILENAME)
Exemplo n.º 16
0
def makekml(t, lonLatAlt, lat0, lon0, ofn=None):

    assert isinstance(
        lonLatAlt,
        np.ndarray) and lonLatAlt.ndim == 2 and lonLatAlt.shape[1] == 3

    kml = Kml(name='My Kml')
    #    doc = kml.newdocument(name='My Doc',snippet=Snippet('snippet'))
    #    doc.lookat.gxtimespan.begin = t[0]
    #    doc.lookat.gxtimespan.end = t[-1]
    #    doc.lookat.latitude = lat0
    #    doc.lookat.longitude = lon0
    #    doc.lookat.range = 1e3

    #fol = kml.newfolder(name='My Tracks')

    trk = kml.newgxtrack(name='My Track')
    trk.newwhen(t)
    trk.newgxcoord(lonLatAlt.tolist())  #list of lon,lat,alt, NOT ndarray!

    # Styling (from simplekml docs)
    #    trk.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
    #    trk.stylemap.normalstyle.linestyle.color = '99ffac59'
    #    trk.stylemap.normalstyle.linestyle.width = 6
    #    trk.stylemap.highlightstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
    #    trk.stylemap.highlightstyle.iconstyle.scale = 1.2
    #    trk.stylemap.highlightstyle.linestyle.color = '99ffac59'
    #    trk.stylemap.highlightstyle.linestyle.width = 8
    if not ofn:
        ofn = mkstemp(suffix='.kml')[1]
    print('writing to', ofn)
    kml.save(str(ofn))
Exemplo n.º 17
0
def prep_sink_kml_per_hour(hours, data_to_show):
    for hour in hours:
        ### create the kml file
        kml = Kml(open=1)
        ### name columns according to hour of day
        lon_col = "lon" + str(hour)
        lat_col = "lat" + str(hour)
        data_col = "data" + str(hour)
        ### create lines that represent thermals
        for i in range(len(data_to_show) - 1):
            x1 = -data_to_show[lon_col][i]
            y1 = data_to_show[lat_col][i]
            z1 = data_to_show[data_col][i]
            x2 = -data_to_show[lon_col][i + 1]
            y2 = data_to_show[lat_col][i + 1]
            z2 = data_to_show[data_col][i + 1]
            if z1 < -100 or z2 < -100:
                line_name = "line " + str(i)
                linestring = kml.newlinestring(name=line_name)
                linestring.coords = [(x1, y1), (x2, y2)]
                linestring.altitudemode = simplekml.AltitudeMode.absolute
                linestring.style.linestyle.width = 3
                if z1 > -200 or z2 > -200:
                    linestring.style.linestyle.color = simplekml.Color.green
                elif z1 > -400 or z2 > -400:
                    linestring.style.linestyle.color = simplekml.Color.blue
                    linestring.style.linestyle.width = 6
                else:
                    linestring.style.linestyle.color = simplekml.Color.black
                    linestring.style.linestyle.width = 9
                ### linestring.extrude = 1

        kml_file_name = "Roldanillo_" + str(hour) + "_sinks.kml"
        kml.save(path2grid + "hours\\" + kml_file_name)
Exemplo n.º 18
0
    def get_kml(self, app_session):

        kml = Kml()

        person_style = Style(iconstyle=IconStyle(
            scale=0.8,
            icon=Icon(
                href=
                'https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png'
            )))
        people_folder = kml.newfolder(name="Potential Facilities")
        for p in [
                people_folder.newpoint(name=person.name,
                                       coords=[(person.longitude,
                                                person.latitude)])
                for person in app_session.data_set.query(Person).all()
        ]:
            p.style = person_style

        place_style = Style(iconstyle=IconStyle(
            scale=0.4,
            icon=Icon(
                href=
                'https://maps.google.com/mapfiles/kml/paddle/red-circle-lv.png'
            )))
        places_folder = kml.newfolder(name="Places")
        for p in [
                places_folder.newpoint(name=place.name,
                                       coords=[(place.longitude,
                                                place.latitude)])
                for place in app_session.data_set.query(Place).all()
        ]:
            p.style = place_style

        return kml.kml()
Exemplo n.º 19
0
def exportToKml2() :
    # KML 
    kml = Kml()
    for aGroupedWayKey in subRoutes :
        aGroupedWay = subRoutes[aGroupedWayKey][0]
        lineNames = ','.join(aGroupedWay.lines)

        coords = list() 
        for aNodeKey in aGroupedWay.nodesList : 
            if type(aNodeKey) is str : 
                aNode = nodesDict[aNodeKey]
                lat = aNode.lat
                lon = aNode.lon
            elif type(aNodeKey) is OsmNode:
                lat = aNodeKey.lat
                lon = aNodeKey.lon
            else :
                lat = aNodeKey[0]
                lon = aNodeKey[1]

            coords.append((lon,lat))

        lin = kml.newlinestring(name="Pathway", description='-', coords= coords)

        r = lambda: random.randint(0,255)
        randomColor = '#ff%02X%02X%02X' % (r(),r(),r()) #random ARGB color 
        lin.style.linestyle.color = randomColor
        lin.style.linestyle.width= 10  # 10 pixels

    kml.save("singlestyle.kml")
Exemplo n.º 20
0
def exportToKml() :
    # KML 
    kml = Kml()

    for aMergedWayTupleKey in tramRoutes :
        aMergedWayTuple = tramRoutes[aMergedWayTupleKey]
        aMergedWay = aMergedWayTuple[1]
        lineNames = ','.join(aMergedWayTuple[0])

        coords = list() 

        for aCoordTuple in aMergedWay :
            lat = aCoordTuple[0]
            lon = aCoordTuple[1]

            coords.append((lon,lat))

        lin = kml.newlinestring(name="Pathway", description='-', coords= coords)

        r = lambda: random.randint(0,255)
        randomColor = '#ff%02X%02X%02X' % (r(),r(),r())

        lin.style.linestyle.color = randomColor
        lin.style.linestyle.width= 10  # 10 pixels

    kml.save("singlestyle.kml")
    def get_kml(self, app_session):

        kml = Kml()

        # set up map points for Plants

        plants_folder = kml.newfolder(name="Potential Facilities")
        plants_points = [
            plants_folder.newpoint(name=plant.name,
                                   coords=[(plant.longitude, plant.latitude)])
            for plant in app_session.data_set.query(Plant).all()
        ]

        for p in plants_points:
            p.style = plant_style

        # set up map points for Shops

        shops_folder = kml.newfolder(name="Shops")
        shops_points = [
            shops_folder.newpoint(name=shop.name,
                                  coords=[(shop.longitude, shop.latitude)])
            for shop in app_session.data_set.query(Shop).all()
        ]
        for p in shops_points:
            p.style = shop_style

        return kml.kml()
Exemplo n.º 22
0
def graph_kml(
    env,
    fname="graph.kml",
    icon="http://maps.google.com/mapfiles/kml/shapes/donut.png",
    size=0.5,
    scale=0.5,
    width=5,
):
    """Create a kml visualisation of graph. Env variable needs to contain
    graph."""

    # create a kml file containing the visualisation
    kml = Kml()
    fol = kml.newfolder(name="Vessels")

    shared_style = Style()
    shared_style.labelstyle.color = "ffffffff"  # White
    shared_style.labelstyle.scale = size
    shared_style.iconstyle.color = "ffffffff"  # White
    shared_style.iconstyle.scale = scale
    shared_style.iconstyle.icon.href = icon
    shared_style.linestyle.color = "ff0055ff"  # Red
    shared_style.linestyle.width = width

    nodes = list(env.FG.nodes)

    # each timestep will be represented as a single point
    for log_index, value in enumerate(list(env.FG.nodes)[0 : -1 - 1]):

        pnt = fol.newpoint(
            name="",
            coords=[
                (
                    nx.get_node_attributes(env.FG, "Geometry")[nodes[log_index]].x,
                    nx.get_node_attributes(env.FG, "Geometry")[nodes[log_index]].y,
                )
            ],
        )
        pnt.style = shared_style

    edges = list(env.FG.edges)
    for log_index, value in enumerate(list(env.FG.edges)[0 : -1 - 1]):

        lne = fol.newlinestring(
            name="",
            coords=[
                (
                    nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][0]].x,
                    nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][0]].y,
                ),
                (
                    nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][1]].x,
                    nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][1]].y,
                ),
            ],
        )
        lne.style = shared_style

    kml.save(fname)
Exemplo n.º 23
0
def create_kml(start_dt, traces):
    mintime = datetime(2100,1,1)
    maxtime = datetime(1901,1,1)
    bbox_nw = (sys.maxint, sys.maxint)
    bbox_se = (-sys.maxint, -sys.maxint)

    kml = Kml(name="Tracer")
    doc = kml.newdocument()

    fol = doc.newfolder(name="Traces")

    i = 0
    for id_, trace in traces:
        trace = list(trace)
        trk = fol.newgxtrack(name='Trace id: %s' % id_)

        times = [start_dt + timedelta(seconds=int(p['time'])) for p in trace]
        trk.newwhen([format_date(t) for t in times])

        places = [
            (float(p['lon']), float(p['lat']), 0)
            for p in trace
        ]
        trk.newgxcoord(places)

        m = min(places, key=operator.itemgetter(0))
        if m[0] < bbox_nw[0] and not (m[0] == 0.0 or m[1] == 0.0):
            bbox_nw = m[:2]

        m = max(places, key=operator.itemgetter(0))
        if m[0] > bbox_se[0] and not (m[0] == 0.0 or m[1] == 0.0):
            bbox_se = m[:2]

        mintime = min([mintime] + times)
        maxtime = max([maxtime] + times)

        trk.altitudemode = 'relativeToGround'

        trk.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
        trk.stylemap.normalstyle.linestyle.color = CATEGORICAL_COLORS[i % len(CATEGORICAL_COLORS)]
        trk.stylemap.normalstyle.linestyle.width = 5
        trk.stylemap.normalstyle.labelstyle.scale = 1
        trk.stylemap.highlightstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
        trk.stylemap.highlightstyle.iconstyle.scale = 1.2
        trk.stylemap.highlightstyle.linestyle.color = CATEGORICAL_COLORS[i % len(CATEGORICAL_COLORS)]
        trk.stylemap.highlightstyle.linestyle.width = 8

        i += 1

    doc.lookat.gxtimespan.begin = format_date(mintime)
    doc.lookat.gxtimespan.end   = format_date(maxtime)
    doc.lookat.longitude = bbox_nw[0] + (bbox_se[0] - bbox_nw[0]) / 2
    doc.lookat.latitude = bbox_nw[1] + (bbox_se[1] - bbox_nw[1]) / 2
    doc.lookat.range = 13000.00

    #doc.lookat.longitude, doc.lookat.latitude = list(list(traces)[0][1])[0]

    return kml.kml()
Exemplo n.º 24
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.º 25
0
    def export_to_kml(self, file_name):
        coords = list()
        for i in range(len(self._gps_latitude)):
            coords.append((self._gps_longitude[i], self._gps_latitude[i]))

        kml = Kml()
        lin = kml.newlinestring(name="Track", description="A track.", coords=coords)
        lin.style.linestyle.color = 'ff0000ff'  # Red
        lin.style.linestyle.width = 2           # 10 pixels
        kml.save(file_name)
Exemplo n.º 26
0
    def get_kml(self, app_session):
        kml = Kml()

        node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon(
            href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png')))
        node_folder = kml.newfolder(name="Nodes")
        for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in
                  app_session.data_set.query(Node).all()]:
            p.style = node_style

        return kml.kml()
Exemplo n.º 27
0
    def from_locations(self, doc_name, track_name, locations):
        when = {}
        for l in locations:
            try:
                if(l.bssid not in when):
                    when[l.bssid]=[]
                when[l.bssid].append({"time": l.time.strftime("%Y-%m-%dT%H:%M:%SZ-05:00"), "coords": (l.lon,l.lat)})
            except:
                continue

        kml = Kml(name=doc_name)
        doc = kml.newdocument(name=track_name)
Exemplo n.º 28
0
 def create_color_map(color_list):
     kml = Kml()
     lat = 38.000
     init_lon = lon = -90.000
     extent = 0.02
     for index, color in enumerate(color_list):
         add_patch(kml, lat, lon, extent, color)
         lon += extent
         if (index % 10) == 9:
             lon = init_lon
             lat -= extent
     kml.save("color_patches.kml")
     print("Output in color_patches.kml")
Exemplo n.º 29
0
def serialize_list_point_lon_lat_index_as_kml(list_points, name='point', color=Color.green, scale=1, abolutefilepath ='points.kml'):

    kml = Kml()
    point_folder = kml.newfolder(name='points')
    for point in list_points:
        lon_lat = [point[0],point[1]]
        index = point[2]
        pnt_0 = point_folder.newpoint()
        pnt_0.name = str(index)
        pnt_0.coords = [lon_lat]
        pnt_0.labelstyle.color=color
        pnt_0.style.labelstyle.scale = scale
        pnt_0.style.iconstyle.icon.href='http://maps.google.com/mapfiles/kml/paddle/grn-circle-lv.png'
    kml.save(abolutefilepath)
Exemplo n.º 30
0
def flask_get_kml():
    """ Return KML with autorefresh """

    _config = autorx.config.global_config
    kml = Kml()
    netlink = kml.newnetworklink(name="Radiosonde Auto-RX Live Telemetry")
    netlink.open = 1
    netlink.link.href = flask.request.host_url + "rs_feed.kml"
    try:
        netlink.link.refreshinterval = _config["kml_refresh_rate"]
    except KeyError:
        netlink.link.refreshinterval = 10
    netlink.link.refreshmode = "onInterval"
    return kml.kml(), 200, {"content-type": "application/vnd.google-earth.kml+xml"}
    def create_kml(self,name):
        """
        create kml file from the HeatMap results
        :param name: filename
        """
        file = Kml()
        counts = [s.count**0.5 for s in self.heatmap]
        c_min, c_max = min(counts), max(counts)
        divisor= (c_max-c_min)/9
        for s in self.heatmap:
            single = file.newpolygon(name=str(s.count),
                                     outerboundaryis=s.get_coordinates())
            single.style.polystyle.color = COL[int(((s.count**0.5)-c_min)//divisor)]

        file.save(name+'.kml')
Exemplo n.º 32
0
def writekml(inarray, kmlfilename):
    kml = Kml()
    sharedstyle = Style()
    sharedstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/wht-blank.png'
    sharedstyle.iconstyle.color = "ffffffff"
    sharedstyle.iconstyle.ColorMode = "random"

    for indiv in numpy.nditer(inarray):
        desc = adddescription(indiv)
        lat =float(indiv[()]['Lat'])
        lon =float(indiv[()]['Long'])
        pnt = kml.newpoint(name=str(indiv[()]['GivenNames']) + " " +str(indiv[()]['FamilyName']), description=desc,
            coords = [(lon,lat)])
        pnt.style = sharedstyle
    kml.save(kmlfilename)
Exemplo n.º 33
0
 def test_kml_empty(self):
     kml = Kml()
     UasTelemetry.kml(
         user=self.user,
         logs=UasTelemetry.by_user(self.user),
         kml=kml,
         kml_doc=kml.document)
Exemplo n.º 34
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
Exemplo n.º 35
0
def make_kml(parsed_users, output_file, verbosity):
    """This function reads the user data supplied by ``parsed_users``, it then generates
    KML output and writes it to ``output_file``.

    Args:
        parsed_users (list): A list of lists, each sub_list should have 4 elements: ``[latitude, longitude, name, comment]``
        output_file (open): Location to save the KML output
        verbosity (int): If set to be >= ``1`` it will print out the string passed to ``message()``
    """
    kml = Kml()

    message("Making and writing KML to " + output_file, verbosity)
    for user in parsed_users:
        # Generate a KML point for the user.
        kml.newpoint(name=user[2], coords=[(user[1], user[0])], description=user[3])

    kml.save(output_file)
 def __init__(self, line_limit_point, pathDirectory):
     self.kml = Kml()
     self.init()
     self.kml_interest_line_already_meeted  = {}
     self.kml_interest_point_already_meeted = {}
     self.line_limit_point                  = line_limit_point
     self.pathDirectory = pathDirectory
     self.midday = (12,0,)
Exemplo n.º 37
0
    def test_sets_coords(self):
        """ 
		The coords are private variables, so they can't be 
		tested directly. Instead this test just checks they exist
		"""
        kml = Kml()
        point = self.scraper.create_point(kml, self.sample_row1)
        self.assertIsInstance(point.coords, Coordinates)
Exemplo n.º 38
0
    def create_lines_and_base_obj(self, msg_list):
        """
		Returns KML object with a chain of lines representing the order
		in which msg_list items are indexed.
		"""
        kml = Kml()
        for i in range(1, len(msg_list)):
            self.create_line_sgmnt(kml, msg_list[i - 1], msg_list[i])
        return kml
Exemplo n.º 39
0
    def from_networks(self, doc_name, networks):
        kml = Kml(name=doc_name)
        for n in networks:
            p = kml.newpoint(name=str(n))
            p.coords=[(n.lastlon,n.lastlat)]
            if(not n._lasttime):
                lasttime = "<i>None</i>"
            else:
                lasttime = n.formated_lasttime
                p.timestamp.when = n.lasttime.strftime("%Y-%m-%dT%H:%M:%SZ-05:00")
            
            if(not n.frequency):
                frequency = "<i>None</i>"
            else:
                frequency = "%s MHz" % n.frequency

            p.description = self._network_format % {"bssid": n.bssid, "ssid": (n.ssid or "<i>None</i>"), "capabilities": n.capabilities, "frequency": frequency, "lasttime": lasttime}

        return kml
Exemplo n.º 40
0
    def get_kml(self, app_session):
        kml = Kml()

        node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon(
            href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png')))
        node_folder = kml.newfolder(name="Nodes")
        for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in
                  app_session.data_set.query(Node).all()]:
            p.style = node_style

        arc_folder = kml.newfolder(name="Arcs")
        Arcs = app_session.data_set.query(Arc).all()
        for arc in Arcs:
            arc_style = Style(linestyle=LineStyle(color=MapArcInput.get_cycled_hex_colour(Arcs.index(arc)), width=4))
            l = arc_folder.newlinestring(name="arc", coords=[(arc.orig_node.longitude, arc.orig_node.latitude),
                                                             (arc.dest_node.longitude, arc.dest_node.latitude)])
            l.style = arc_style

        return kml.kml()
Exemplo n.º 41
0
def fCreateLineKML(zoznam, n, f):
    kml = Kml()
    fol = kml.newfolder(name="spojnica")
    At = zoznam[0][3]
    L = zoznam[0][0]
    B = zoznam[0][1]
    for i in range(1, len(zoznam)):
        At = zoznam[i][3]
        if At == 0:
            continue
        for data in f:
            if At == data[1]:
                farba = data[0]
        Ld = zoznam[i][0]
        Bd = zoznam[i][1]
        pnt = fol.newlinestring(name="{0}".format(At),
                                coords=[(L, B), (Ld, Bd)])

        pnt.style.linestyle.color = farba
    kml.save("data/vystup/kruh/" + n + "spojnica.kml")
Exemplo n.º 42
0
def process():

    distances = sorted(compute_distances())

    # thin out the result by taking every 50th distance
    THIN = 50
    distances = distances[::THIN]
    pprint(distances)

    bearings = compute_bearings()

    locations = compute_locations(distances, bearings)

    points = compute_points(locations)

    kml = Kml()

    for distance, bearing, lat, lon in points:
        name = "d_%s_b_%s" % (distance, bearing)
        kml.newpoint(
            name=name,
            coords=[(lon, lat)]
        )

    kml.save("ayhe11.kml")
Exemplo n.º 43
0
def google_earth_export():
    print('ttt'*100, request.form)
    form = GoogleEarthForm(request.form)
    if 'POST' in request.method:
        kml_file = Kml()
        for node in filter(lambda obj: obj.visible, Node.query.all()):
            point = kml_file.newpoint(name=node.name)
            point.coords = [(node.longitude, node.latitude)]
            point.style = styles[node.subtype]
            point.style.labelstyle.scale = request.form['label_size']

        for link in filter(lambda obj: obj.visible, Link.query.all()):
            line = kml_file.newlinestring(name=link.name)
            line.coords = [
                (link.source.longitude, link.source.latitude),
                (link.destination.longitude, link.destination.latitude)
            ]
            line.style = styles[link.type]
            line.style.linestyle.width = request.form['line_width']
        filepath = join(current_app.kmz_path, request.form['name'] + '.kmz')
        kml_file.save(filepath)
    return render_template(
        'google_earth_export.html',
        form=form
    )
Exemplo n.º 44
0
	def convert(self, output):
		output_filename = '{}.{}'.format(KMLParser.RESULT_FILENAME, output)
		if output in ['kml', 'kmz']: #check if value is in a list
			kmlinstance = Kml()
			folder = kmlinstance.newfolder()
			folder.name = "My Places"
			for name, lat, lon in self.content:#tuples can be decomposed in a for loop. This is the same as "for (x,y,z) in self.content" or "for t in self.content" and then using t[0] etc.
				folder.newpoint(name=name, coords=[(lat,lon)])
			kmlinstance.save( output_filename )
		elif output in ['terminal', 'txt']:
			newcontent = [ '%s\t->\t%.4f %.4f'%(name, float(lat),float(lon)) for name, lat, lon in self.content ] #list comprehensions rock!!
			if output == 'txt':
				f = open(output_filename, 'w')
				f.write( '\n'.join(newcontent) )
				f.close()
			elif output is 'terminal':
				print '\n'.join(newcontent)
		elif output == 'json':
			newcontent = [ {'name': name, 'coordinates': {'latitude':lat, 'longitude':lon} } for name, lat, lon in self.content ]
			f = open(output_filename, 'w')
			json.dump(newcontent, f, indent=2)
			f.close()
Exemplo n.º 45
0
"""
Styling points, linestrings, polygons and TOC items.
"""

import os
from simplekml import Kml, ListItemType, Color

kml = Kml(name="Styling", open=1)

# Make all the items into radio buttons
kml.document.liststyle.listitemtype = ListItemType.radiofolder

# Change the icon of the document in the TOC
kml.document.liststyle.itemicon.href = "http://maps.google.com/mapfiles/kml/shapes/parks.png"

# A normal Point with both a LabelStyle and IconStyle
pnt = kml.newpoint(name="Kirstenbosch Normal", description="A style map.", coords=[(18.431486,-33.988)])
pnt.labelstyle.color = 'ff0000ff'
pnt.labelstyle.scale = 2  # Text twice as big
pnt.labelstyle.color = "ffff0000"
pnt.iconstyle.color = 'ffff0000'  # Blue
pnt.iconstyle.scale = 3  # Icon thrice as big
pnt.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/info-i.png'  # Culry 'information i

# A Point with a styleMap. The Text changes from blue to red on mouse over.
pnt = kml.newpoint(name="Kirstenbosch StyleMap", coords=[(18.432314,-33.988862)])
pnt.stylemap.normalstyle.labelstyle.color = 'ffff0000'
pnt.stylemap.highlightstyle.labelstyle.color = 'ff0000ff'

# A red thick LineString
lin = kml.newlinestring(name="Pathway", description="A pathway in Kirstenbosch",
Exemplo n.º 46
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')
Exemplo n.º 47
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.º 48
0
"""
The very basics of simplekml.
"""

from __future__ import unicode_literals
import os
from simplekml import Kml, ColorMode, AltitudeMode, Style

# Create an instance of Kml
kml = Kml(name="Basics", open=1)

# Create a new document
doc = kml.newdocument(name="A Document")

# Create a nested document
nestdoc = doc.newdocument()
nestdoc.name = "A Nested Document"
nestdoc.description = "\u2013 This is the nested document's description with unicode."

# Create a new folder at the top level
fol = kml.newfolder()
fol.name = "A Folder"
fol.description = "Description of a folder"

# Some sub folders
fol = fol.newfolder(name='A Nested Folder', description="Description of a nested folder")
fol = kml.newfolder(name='Point Tests', description="Description of Point Folder")

# A folder containing points with style
stpnt = fol.newpoint(name="Cape Town Stadium", description='The Cape Town stadium built for the 2010 world cup soccer.', coords=[(18.411102, -33.903486)])
vapnt = fol.newpoint()
Exemplo n.º 49
0
UIDtoColor = {"E016246604C06B7A" : "http://maps.gstatic.com/mapfiles/ms2/micons/red-dot.png", 
              "E016246604C06BA0" : "http://maps.gstatic.com/mapfiles/ms2/micons/blue-dot.png", 
              "E016246604C070DE" : "http://maps.gstatic.com/mapfiles/ms2/micons/yellow-dot.png", 
              "E016246604C0862C" : "http://maps.gstatic.com/mapfiles/ms2/micons/green-dot.png", 
              "E016246604C0938B" : "http://maps.gstatic.com/mapfiles/ms2/micons/pink-dot.png", 
              "E016246604C05492" : "http://maps.gstatic.com/mapfiles/ms2/micons/ltblue-dot.png", 
              "E016246604C09352" : "http://maps.gstatic.com/mapfiles/ms2/micons/orange-dot.png", 
              "E0162466025BF373" : "http://maps.gstatic.com/mapfiles/ms2/micons/purple-dot.png"}

def sortNneaList(x,y):
    return int( (x.dateEvent.newTime - y.dateEvent.newTime).total_seconds() ) #warning, this method don care about milli and microseconds

nmeaLogs = sorted(nmeaLogs,cmp=sortNneaList)

from simplekml import Kml
kml = Kml()

currentNmeaLogDate = None
for nmeaLog in nmeaLogs:
    if currentNmeaLogDate == None:
        currentNmeaLogDate = nmeaLog.dateEvent.newTime
    elif nmeaLog.dateEvent.newTime.day != currentNmeaLogDate.day or nmeaLog.dateEvent.newTime.month != currentNmeaLogDate.month or nmeaLog.dateEvent.newTime.year != currentNmeaLogDate.year:
        kml.save(kmlDirectory+"skidump_"+str(currentNmeaLogDate.day)+"_"+str(currentNmeaLogDate.month)+"_"+str(currentNmeaLogDate.year)+".kml")
        currentNmeaLogDate = nmeaLog.dateEvent.newTime
        kml = Kml()

    tab = []
    firstPos = None
    for position in nmeaLog.NewPosition:
        if firstPos == None:
            firstPos = position
Exemplo n.º 50
0
def csv_to_kml(input_filename):

	# open input file
	csv_file = open(input_filename,'rU')
	reader = csv.DictReader(csv_file)
	# preamble 
	input_filename_base, input_filename_ext = os.path.splitext(input_filename)
		
	# open output file
	kml_file = open(input_filename_base + '.kml','w')

	kml_file.write(r"""<?xml version="1.0" encoding="utf-8" ?>
	<kml xmlns="http://www.opengis.net/kml/2.2">
	""")
	kml_file.write("<Document><name>%s</name>" % input_filename_base)
	kml_file.write(r""" <Style id="grid1k"><IconStyle> <Icon> <color>ff0000</color> </Icon> </IconStyle></Style>""")
	
	kml_file.write(r"""
	<Schema name="sample" id="sample">
		<SimpleField name="Name" type="string"></SimpleField>
		<SimpleField name="Description" type="string"></SimpleField>
		<SimpleField name="GID" type="string"></SimpleField>
	</Schema>
	""")
	gids_unique = set()
	gids = []
	locs_1k = []        
	# main loop 
	for line in reader:

		kml_file.write('  <Placemark>\n')
		kml_file.write('  <name>GID=%s</name>\n' % (line['GID_100m']))
		kml_file.write('\t<ExtendedData><SchemaData schemaUrl=\"#sample\">\n')
		kml_file.write('  <SimpleField name="GID">%s</SimpleField>\n' % (line['GID_100m']))
		kml_file.write('\t\t</SchemaData></ExtendedData>\n')
		kml_file.write("     <Point><coordinates>%s,%s</coordinates></Point>\n" % (line['x'], line['y']))
		kml_file.write('  </Placemark>\n')
	        
	        gids_unique.add(line['GID_1k'])
	        gids.append(line['GID_1k'])
                locs_1k.append([line['x_1k'], line['y_1k']])

	# epilogue
	kml_file.write('\t</Document>\n\t</kml>')
	csv_file.close()
	kml_file.close()
	gids_unique = list(gids_unique)
	locs_1k_unique = []
	for gid in gids_unique:
	    locs_1k_unique.append([locs_1k[k] for k, x in enumerate(map(lambda x: x==gid, gids)) if x][0])
	
	for i, loc in enumerate(locs_1k_unique):
	    kml=Kml()
	    proj_para =  "+proj=laea +ellps=WGS84 +lon_0=20 +lat_0=5 +units=m +no_defs"
	    project = pyproj.Proj(proj_para)
	    loc_laea = list(project(loc[0], loc[1]))
	    center_pt = kml.newpoint(name=gids_unique[i], description="1k by 1k grid", coords=[(loc[0], loc[1])])
            pol = kml.newpolygon(name="1k grid", description="A pathway in Kirstenbosch",  
                                 outerboundaryis=[project(loc_laea[0]-500, loc_laea[1]+500, inverse=True), 
                                                  project(loc_laea[0]+500, loc_laea[1]+500, inverse=True), 
                                                  project(loc_laea[0]+500, loc_laea[1]-500, inverse=True),
                                                  project(loc_laea[0]-500, loc_laea[1]-500, inverse=True), 
                                                  project(loc_laea[0]-500, loc_laea[1]+500, inverse=True)],
                                 innerboundaryis=[project(loc_laea[0]-500, loc_laea[1]+500, inverse=True), 
                                                  project(loc_laea[0]+500, loc_laea[1]+500, inverse=True), 
                                                  project(loc_laea[0]+500, loc_laea[1]-500, inverse=True),
                                                  project(loc_laea[0]-500, loc_laea[1]-500, inverse=True), 
                                                  project(loc_laea[0]-500, loc_laea[1]+500, inverse=True)])
            pol.polystyle.color = 'ff0000ff' 
	    kml.save("csv/"+gids_unique[i]+".kml")
Exemplo n.º 51
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)
class kmlManager(object):
    def init(self):
        self.kml_list_start_time               = None
        self.kml_list                          = []
        self.kml_interest_line_list            = []
        self.kml_interest_point_list           = []
        
    def __init__(self, line_limit_point, pathDirectory):
        self.kml = Kml()
        self.init()
        self.kml_interest_line_already_meeted  = {}
        self.kml_interest_point_already_meeted = {}
        self.line_limit_point                  = line_limit_point
        self.pathDirectory = pathDirectory
        self.midday = (12,0,)
    
    def addPointOfInterest(self,point):
        if point.descr not in self.kml_interest_point_already_meeted: #not yet printed ?
            self.kml_interest_point_already_meeted[point.descr] = True
            self.kml_interest_point_list.append(point)

    def addLineOfInterest(self, line):
        if line.descr not in self.kml_interest_line_already_meeted: #not yet printed ?
            self.kml_interest_line_already_meeted[line.descr] = True
            self.kml_interest_line_list.append(line)
            
    def addLinePoint(self,gpoint, utcdatetime, colorMarker):
        if self.line_limit_point > 0:#don't want to write the line of the road ?
            if len(self.kml_list) == 0: #set start time
                self.kml_list_start_time = utcdatetime
                
            self.kml_list.append( (gpoint.lat, gpoint.lon,) )
        
        if len(self.kml_list) >= self.line_limit_point:
            #kml process
            if len(self.kml_list) > 0:
                line = self.kml.newlinestring(name="From "+self.kml_list_start_time.isoformat()+" to "+utcdatetime.isoformat(), description="", coords=self.kml_list)
            
                #if past midday, colour the line in red
                if utcdatetime.hour < self.midday[0] or (utcdatetime.hour == self.midday[0] and utcdatetime.minute < self.midday[1]):
                    line.style.linestyle.color = 'afff0000'#morning, blue line
                else:
                    line.style.linestyle.color = 'af0000ff'#afternoon, red line
            
            #write the meeted line of interest
            for interest_line in self.kml_interest_line_list:
                #line
                line = self.kml.newlinestring(name=interest_line.descr, description="", coords=((interest_line.start.lat,interest_line.start.lon,), (interest_line.end.lat,interest_line.end.lon,),))
                line.style.linestyle.color = 'af00ff00' #green
                
                #start point
                point = self.kml.newpoint(name="Start point of "+interest_line[2], description="",coords=(interest_line.start.lat,interest_line.start.lon,))
                point.style.iconstyle.icon.href = "http://maps.google.com/mapfiles/dd-start.png"
                
                #end point
                point = self.kml.newpoint(name="End point of "+interest_line[2], description="",coords=(interest_line.end.lat,interest_line.end.lon,))
                point.style.iconstyle.icon.href = "http://maps.google.com/mapfiles/dd-end.png"
                
            #write the meeted point of interest
            for interest_point in self.kml_interest_point_list:
                point = self.kml.newpoint(name=interest_point.name, description=interest_point.descr,coords=( (interest_point.lat, interest_point.lon,), ))
                point.style.iconstyle.icon.href = colorMarker.getColorPath(interest_point.name)
           
            #save the file (for every line written, overwrite the file)
            date = datetime.datetime.now()
            self.kml.save(self.pathDirectory+"skidump_"+str(date.day)+"_"+str(date.month)+"_"+str(date.year)+".kml")
            
            #reset list
            self.init()

    def addEventPointList(self,l):
        #get point of interest from proxy
        self.kml_interest_point_list.extend(l)
Exemplo n.º 53
0
"""
Demonstrates the basics of overlays (ground screen and photo overlay).
"""

import os
from simplekml import Kml, OverlayXY, ScreenXY, Units, Camera, AltitudeMode, ViewVolume

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
Exemplo n.º 54
0
#!/usr/bin/python

from simplekml import Kml
import sys

in_file, out_file = sys.argv[1], sys.argv[2];
data = list()

kml = Kml(name = in_file, open = 1)

with open(in_file) as file:
	lines = file.readlines()
	for x in lines:
		# Ignore lines that start with "//".
		if x.startswith("//"):
			continue

		elements = x.split(",")[:3]
		group = tuple(elements)
		data.append(group)

path = kml.newlinestring(name = "Flight", description = in_file, coords = data)
path.altitudemode = "absolute"
path.extrude = 1
path.style.polystyle.color = "7fff575c"

kml.save(out_file)

Exemplo n.º 55
0
    car["gps"].append((longitude[i], latitude[i], 0))


# In[31]:

from simplekml import Kml, Model, AltitudeMode, Orientation, Scale, Style, Color


# In[32]:

# The model path and scale variables
car_dae = r'https://raw.githubusercontent.com/balzer82/Kalman/master/car-model.dae'
car_scale = 1.0

# Create the KML document
kml = Kml(name=d.strftime("%Y-%m-%d %H:%M"), open=1)

# Create the model
model_car = Model(altitudemode=AltitudeMode.clamptoground,
                            orientation=Orientation(heading=75.0),
                            scale=Scale(x=car_scale, y=car_scale, z=car_scale))

# Create the track
trk = kml.newgxtrack(name="EKF", altitudemode=AltitudeMode.clamptoground,
                     description="State Estimation from Extended Kalman Filter with CTRA Model")

# Attach the model to the track
trk.model = model_car
trk.model.link.href = car_dae

# Add all the information to the track
Exemplo n.º 56
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("pcap", help="path pcap file")
    parser.add_argument("-o", "--output", help="Output directory (must already exist)", default="./")
    parser.add_argument("-d", "--database", help="Database filename", default="sqlite.db")
    parser.add_argument("-k", "--kml", help="KML filename", default="results.kml")
    parser.add_argument("-r", "--report", help="Report filename", default="report.txt")
    args = parser.parse_args()

    # Check if pcap is a valid file
    if not os.path.exists(args.pcap):
        print "Invalid pcap file. Quitting."
        exit(1)
        
    # Check if output path is a valid file
    if not os.path.exists(args.output):
        print "Invalid output path. Quitting."
        exit(1)

    ### READ PCAP FILE ###
    pcap = rdpcap(args.pcap)
    files = extract_jpgs(pcap, args.output)
    
    ### INITIALIZE DATABASE ###
    conn = initdb(os.path.join(args.output,args.database))
    
    ### INITIALIZE KML ###
    kml = Kml(name=args.kml)
    
    for fname in files:
        
        ### EXTRACT EXIF DATA ###
        print "[+] Extracting exif data from " + fname
        image = Image.open(fname)
        exif = extract_exif(conn, image)
        
        ### GET MD5 ###
        md5hash = get_md5(os.path.basename(fname))
        print "[+] Getting md5 hash for " + os.path.basename(fname) + " => " + md5hash
        
        ### INSERT INTO DATABASE ###
        print "[+] Inserting record into database for " + fname
        insert_record(conn, os.path.basename(fname), md5hash, simplejson.dumps(exif))
        
        ### WRITE GPS INFO TO KML ###
        if exif["GPSInfo"]:
            latitude, longitude = get_lat_long(exif['GPSInfo'])
            print "[+] Writing GPS info (%s, %s) to KML for %s" % (longitude, latitude, os.path.basename(fname))
            descr = '%s, %s' % ( longitude, latitude )
            kml.newpoint(name=os.path.basename(fname),
                        description=descr,
                        coords=[(longitude, latitude)])
        
    ### SAVE KML TO FILE ###
    print "[+] Saving KML file to " + os.path.join(args.output, args.kml)
    kml.save(os.path.join(args.output, args.kml))
    
    ### GENERATE REPORT ###
    print "[+] Generating final report as " + os.path.join(args.output, args.report)
    with open(os.path.join(args.output, args.report), 'w') as r:
        now = strftime("%Y-%m-%d %H:%M:%S", gmtime())
        r.write("<==== Extraction Results ====>\n")
        r.write("Filename: %s\n" % args.pcap)
        r.write("Timestamp: %s GMT \n\n" % now)
        
        for row in conn.execute("SELECT * FROM results"):
            r.write("===================\n")
            r.write("Image: %s\n" % row[0])
            r.write("MD5 Hash: %s\n" % row[1])
            
            if row[2] and row[2] != "null":
                r.write("EXIF data:\n")
                json = simplejson.loads(row[2])
                for i in json:
                    r.write("\t%s: %s\n" % (i, json[i]))
                    if i == "GPSInfo":
                        latitude, longitude = get_lat_long(json['GPSInfo'])
                        r.write("\t%s (translated): %s, %s\n" % (i, latitude, longitude))
            else:
                r.write("No EXIF data found\n")
                        
            r.write("===================\n\n")
        
    conn.close()
def write_track_kml(csvreader):
    """
    Inputs: csv contains lon/lat
    Output:	glider track kml file
    """
    coord = []
    timerange = []

    lat_f = int(cfg.get(section1, "LAT_COLUMN"))
    lon_f = int(cfg.get(section1, "LON_COLUMN"))
    date_f = int(cfg.get(section1, "DATE_COLUMN"))
    date_fmt = cfg.get(section1, "DATE_FORMAT")
    kml_dir = cfg.get(section1, "KML_DIR")
    mission_date = cfg.get(section1, "MISSION_START_DATE")
    organization = cfg.get(section1, "ORGANIZATION")
    vehicle_name = cfg.get(section1, "VEHICLE_NAME")
    kml_title = cfg.get(section1, "KML_DOC_TITLE")
    kml_lookat_lon = float(cfg.get(section1, "KML_LOOKAT_LON"))
    kml_lookat_lat = float(cfg.get(section1, "KML_LOOKAT_LAT"))
    kml_lookat_range = float(cfg.get(section1, "KML_LOOKAT_RANGE"))
    kml_cdata_title = cfg.get(section1, "KML_CDATA_TITLE")
    plot_url = cfg.get(section1, "PLOT_URL")
    plot_width = int(cfg.get(section1, "PLOT_WIDTH"))
    plot_height = int(cfg.get(section1, "PLOT_HEIGHT"))
    plot_temp = cfg.get(section1, "PLOT_TEMP")
    plot_oxyg = cfg.get(section1, "PLOT_OXYG")
    plot_sali = cfg.get(section1, "PLOT_SALI")
    plot_chlo = cfg.get(section1, "PLOT_CHLO")
    plot_cdom = cfg.get(section1, "PLOT_CDOM")
    icon_url = cfg.get(section1, "ICON_URL")
    icon_normal_scale = cfg.get(section1, "ICON_NORMAL_SCALE")
    icon_normal_color = cfg.get(section1, "ICON_NORMAL_COLOR")
    icon_normal_width = cfg.get(section1, "ICON_NORMAL_WIDTH")
    icon_highlight_url = cfg.get(section1, "ICON_HIGHLIGHT_URL")
    icon_highlight_scale = cfg.get(section1, "ICON_HIGHLIGHT_SCALE")
    icon_highlight_color = cfg.get(section1, "ICON_HIGHLIGHT_COLOR")
    icon_highlight_width = cfg.get(section1, "ICON_HIGHLIGHT_WIDTH")
    path_line_color = cfg.get(section1, "PATH_LINE_COLOR")
    path_line_width = int(cfg.get(section1, "PATH_LINE_WIDTH"))

    csvheader = cfg.get(section1, "CSV_HEADER")
    if csvheader == "YES":
        csvreader.next()
    else:
        pass

    for row in csvreader:
        coord.append((row[lon_f - 1], row[lat_f - 1], 0.0))  # -1 for python order
        timestamp = time.strptime(row[date_f - 1], date_fmt)
        kmltime = time.strftime("%Y-%m-%dT%H:%M:%SZ", timestamp)  # KML requires specific time format
        timerange.append(kmltime)  # time stamp

    # This constructs the KML document from the CSV file.
    kml = Kml(name="%s %s" % (organization, vehicle_name))
    doc = kml.newdocument(name="%s" % kml_title, snippet=Snippet(timerange[0]))
    doc.lookat.gxtimespan.begin = timerange[0]
    doc.lookat.gxtimespan.end = timerange[-1]
    doc.lookat.longitude = kml_lookat_lon
    doc.lookat.latitude = kml_lookat_lat
    doc.lookat.range = kml_lookat_range
    # Create a folder
    ge_dir = doc.newfolder(name="Tracks")
    # Create a schema for extended data: heart rate, cadence and power
    schema = kml.newschema()

    # Create a new track in the folder
    trk = ge_dir.newgxtrack(name="%s %s" % (organization, vehicle_name))
    desc1 = "<![CDATA[\n%s<br />\n<br />\n" % kml_cdata_title
    desc2 = "<a href='%s/glider.html' target='_blank'>Link to Plot</a><br />\n" % plot_url
    desc_temp = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_temp, plot_height, plot_width)
    desc_oxyg = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_oxyg, plot_height, plot_width)
    desc_sali = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_sali, plot_height, plot_width)
    desc_chlo = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_chlo, plot_height, plot_width)
    desc_cdom = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_cdom, plot_height, plot_width)
    desc3 = "]]>\n"
    trk.description = desc1 + desc2 + desc_temp + desc_oxyg + desc_sali + desc_chlo + desc_cdom + desc3
    # Apply the above schema to this track
    trk.extendeddata.schemadata.schemaurl = schema.id
    # Add all information to the track
    trk.newwhen(timerange)  # Each item in the give nlist will become a new <when> tag
    trk.newgxcoord(coord)  # Ditto

    # Style
    trk.stylemap.normalstyle.iconstyle.icon.href = icon_url
    trk.stylemap.normalstyle.iconstyle.scale = icon_normal_scale
    trk.stylemap.normalstyle.linestyle.color = icon_normal_color
    trk.stylemap.normalstyle.linestyle.width = icon_normal_width
    trk.stylemap.highlightstyle.iconstyle.icon.href = icon_highlight_url
    trk.stylemap.highlightstyle.iconstyle.scale = icon_highlight_scale
    trk.stylemap.highlightstyle.linestyle.color = icon_highlight_color
    trk.stylemap.highlightstyle.linestyle.width = icon_highlight_width

    # Create a path line
    gpath = kml.newlinestring(name="%s %s" % (organization, vehicle_name))
    gpath.description = trk.description
    gpath.timespan.begin = timerange[0]
    gpath.timespan.end = ""
    gpath.coords = coord
    gpath.style.linestyle.color = path_line_color
    gpath.style.linestyle.width = path_line_width

    # Check if KML Directory exists
    if not os.path.exists(kml_dir):
        os.makedirs(kml_dir)

    # Save the KML
    kml.save("%s/Glider_%s_%s_%s.kml" % (kml_dir, organization, vehicle_name, mission_date))
    print("Glider_%s_%s_%s.kml created in '%s' folder" % (organization, vehicle_name, mission_date, kml_dir))
Exemplo n.º 58
0
    "2010-05-28T02:02:56Z"]

coord = [(-122.207881,37.371915,156.000000),
    (-122.205712,37.373288,152.000000),
    (-122.204678,37.373939,147.000000),
    (-122.203572,37.374630,142.199997),
    (-122.203451,37.374706,141.800003),
    (-122.203329,37.374780,141.199997),
    (-122.203207,37.374857,140.199997)]

cadence = [86, 103, 108, 113, 113, 113, 113]
heartrate = [181, 177, 175, 173, 173, 173, 173]
power = [327.0, 177.0, 179.0, 162.0, 166.0, 177.0, 183.0]

# Create the KML document
kml = Kml(name="Tracks", open=1)
doc = kml.newdocument(name='GPS device', snippet=Snippet('Created Wed Jun 2 15:33:39 2010'))
doc.lookat.gxtimespan.begin = '2010-05-28T02:02:09Z'
doc.lookat.gxtimespan.end = '2010-05-28T02:02:56Z'
doc.lookat.longitude = -122.205544
doc.lookat.latitude = 37.373386
doc.lookat.range = 1300.000000

# Create a folder
fol = doc.newfolder(name='Tracks')

# Create a schema for extended data: heart rate, cadence and power
schema = kml.newschema()
schema.newgxsimplearrayfield(name='heartrate', type=Types.int, displayname='Heart Rate')
schema.newgxsimplearrayfield(name='cadence', type=Types.int, displayname='Cadence')
schema.newgxsimplearrayfield(name='power', type=Types.float, displayname='Power')
    car["when"].append(d.strftime("%Y-%m-%dT%H:%M:%SZ"))
    car["coord"].append((lonekf[i], latekf[i], 0))
    car["gps"].append((longitude[i], latitude[i], 0))

# <codecell>

from simplekml import Kml, Model, AltitudeMode, Orientation, Scale

# <codecell>

# The model path and scale variables
car_dae = r'http://simplekml.googlecode.com/hg/samples/resources/car-model.dae'
car_scale = 1.0

# Create the KML document
kml = Kml(name=d.strftime("%Y-%m-%d %H:%M"), open=1)

# Create the model
model_car = Model(altitudemode=AltitudeMode.clamptoground,
                            orientation=Orientation(heading=75.0),
                            scale=Scale(x=car_scale, y=car_scale, z=car_scale))

# Create the track
trk = kml.newgxtrack(name="EKF", altitudemode=AltitudeMode.clamptoground,
                     description="State Estimation from Extended Kalman Filter with CTRV Model")
gps = kml.newgxtrack(name="GPS", altitudemode=AltitudeMode.clamptoground,
                     description="Original GPS Measurements")

# Attach the model to the track
trk.model = model_car
gps.model = model_car
Exemplo n.º 60
0
import numpy as np
import zipfile
import crust1
from os import remove
from simplekml import Kml, Style

# Create an instance of Kml
kml = Kml(open=1)
fol = kml.newfolder(name="Crust 1.0")


def convert_to_html(model):
    """
    Takes a model instance and produces an HTML table that represents the
    results in a nice way for us to look at.

    Parameters
    ----------
    model : dict
    Dictionary of layers and their properties as a list in the form of
    [Vp, Vs, rho, thickness, top]

    Returns
    -------
    html_str : str
    Nicely formatted HTML table of the model results.
    """

    layer_labels = ["Water", "Ice", "Upper_Seds.", "Middle_Seds.",
                    "Lower_Seds.", "Upper_Crust", "Middle_Crust",
                    "Lower_Crust", "Mantle"]