Esempio n. 1
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))
    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()
Esempio 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())
Esempio n. 4
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")
Esempio n. 5
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")
Esempio n. 6
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
    )
Esempio n. 7
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()
Esempio n. 8
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)
Esempio n. 9
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)
Esempio n. 10
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)
Esempio n. 11
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)
Esempio n. 12
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()
Esempio n. 13
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)
Esempio n. 14
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())
Esempio n. 15
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()
Esempio n. 16
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)
Esempio n. 17
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)
Esempio n. 18
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")
Esempio n. 19
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)
Esempio n. 20
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)
Esempio n. 21
0
def generate_kml():
    """Generate KML file from geojson."""
    uuid = request.values.get('uuid', None)
    campaign_name = request.values.get('campaign_name', None)
    campaign = Campaign(uuid)

    # Get json for each type.
    types = campaign.get_s3_types()
    if types is None:
        return Response(json.dumps({'error': 'types not found'}), 400)

    data = []
    for t in types:
        data.append(campaign.get_type_geojsons(t))

    if len(data) == 0:
        return Response(json.dumps({'error': 'Data not found'}), 400)

    features = [i['features'] for sublist in data for i in sublist]

    # for each type, we need to get geojson.
    kml = Kml(name=campaign_name)

    file_name = hashlib.md5(
        uuid.encode('utf-8') + '{:%m-%d-%Y}'.format(datetime.today()).encode(
            'utf-8')).hexdigest() + '.kml'

    file_path = os.path.join(config.CACHE_DIR, file_name)

    # For now, let's work only with points.
    # TODO: include polygons in the kml file.
    features = [[f for f in sublist if f['geometry']['type'] == 'Point']
                for sublist in features]
    features = [item for sublist in features for item in sublist]

    for feature in features:
        tags = feature['properties']['tags']
        extended_data = ExtendedData()
        kml_name = ''

        if 'name' in tags.keys():
            kml_name = tags['name']
        elif 'amenity' in tags.keys():
            kml_name = tags['amenity']

        [
            extended_data.newdata(k, escape(v)) for k, v in tags.items()
            if k != 'name'
        ]
        kml.newpoint(name=kml_name,
                     extendeddata=extended_data,
                     coords=[(feature['geometry']['coordinates'][0],
                              feature['geometry']['coordinates'][1])])
    kml.save(path=file_path)
    if kml:
        # Save file into client storage device.
        return Response(json.dumps({'file_name': file_name}))
    def action(dependencies, targets):
        """

        :param dependencies: list of files to process
        :param targets: list of file to output
        :return:
        """
        kml = Kml()
        ship = kml.newdocument(name='ship')
        camera = kml.newdocument(name='camera')

        inputs = list(dependencies)
        inputs.sort()
        for dep in inputs:
            log = pd.read_csv(dep,
                              index_col='timestamp',
                              parse_dates=['timestamp'])
            log = log.resample('10S').first()
            log['Time'] = log.index
            log['Depth'] = 0
            item = log.iloc[0]
            track = ship.newgxtrack(
                name=f'operation {int(item.Operation):03d}',
                altitudemode=AltitudeMode.clamptoground,
                description=f'Site {item.Site}')
            track.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
            track.stylemap.normalstyle.linestyle.color = Color.green
            track.stylemap.normalstyle.linestyle.width = 6
            track.stylemap.highlightstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
            track.stylemap.highlightstyle.iconstyle.scale = 1.2
            track.stylemap.highlightstyle.linestyle.color = '99ffac59'
            track.stylemap.highlightstyle.linestyle.width = 8
            track.newgxcoord(
                list(
                    zip(log.ShipLongitude.interpolate().values,
                        log.ShipLatitude.interpolate().values,
                        log.Depth.interpolate())))
            track.newwhen(
                list(log.Time.dt.strftime('%Y-%m-%dT%H:%M:%S').values))
            track = camera.newgxtrack(
                name=f'operation {int(item.Operation):03d}',
                altitudemode=AltitudeMode.relativetoground,
                description=f'Site {item.Site}')
            track.newgxcoord(
                list(
                    zip(log.UsblLongitude.interpolate(),
                        log.UsblLatitude.interpolate(), -log.HSVPressure)))
            track.newwhen(
                list(log.Time.dt.strftime('%Y-%m-%dT%H:%M:%S').values))
            track.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
            track.stylemap.normalstyle.linestyle.color = Color.red
            track.stylemap.normalstyle.linestyle.width = 6
            track.stylemap.highlightstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
            track.stylemap.highlightstyle.iconstyle.scale = 1.2
            track.stylemap.highlightstyle.linestyle.color = '99ffac59'
            track.stylemap.highlightstyle.linestyle.width = 8
        kml.save(list(targets)[0])
Esempio n. 23
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
Esempio 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)
Esempio 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)
Esempio 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()
Esempio n. 27
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")
Esempio n. 28
0
    def get_kml(self, app_session):

        kml = Kml()

        def LongLat(l):
            return (l.longitude, l.latitude)

        mylocstyle = Style(iconstyle=IconStyle(
            scale=0.8,
            icon=Icon(
                href=
                'https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png'
            )))
        LocsFolder = kml.newfolder(name="Locations")
        locations = app_session.data_set.query(Location).all()
        if len(locations) < 100:
            for p in [
                    LocsFolder.newpoint(name=loc.name, coords=[LongLat(loc)])
                    for loc in locations
            ]:
                p.style = mylocstyle

        mylinestyle = Style(linestyle=LineStyle(color='FF0000FF', width=4))
        PathsFolder = kml.newfolder(name="Paths")

        paths = app_session.data_set.query(Path).all()
        if len(paths) < 100:
            for path in [
                    PathsFolder.newlinestring(name='path',
                                              coords=[
                                                  LongLat(l.start_location),
                                                  LongLat(l.end_location)
                                              ]) for l in paths
            ]:
                path.style = mylinestyle

        mylinestyle = Style(linestyle=LineStyle(color='FF00FF00', width=4))
        PathsFolder = kml.newfolder(name="Paths")

        paths = app_session.data_set.query(OutputPath).all()
        if len(paths) < 100:
            for path in [
                    PathsFolder.newlinestring(name='path',
                                              coords=[
                                                  LongLat(l.start_location),
                                                  LongLat(l.end_location)
                                              ]) for l in paths
            ]:
                path.style = mylinestyle

        return kml.kml()
Esempio n. 29
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"}
Esempio n. 30
0
    def test_line_sgmnt(self):
        """ 
		The segment specs are private variables. This tests whetehr line
		segments can be made.
		"""
        sample_row2 = self.convert_list_to_etree([
            '913686008', '0-2440482', 'Lima', '1517940807', 'UNLIMITED-TRACK',
            '-8.74288', '-74.43631', 'SPOT3', 'Y', '2018-02-06T18:13:27+0000',
            'GOOD', '0', '2027'
        ])
        kml = Kml()
        line = self.scraper.create_line_sgmnt(kml, self.sample_row1,
                                              sample_row2)
        self.assertIsInstance(line, LineString)