Ejemplo n.º 1
0
def buildStyles():
    ''' Build the various styles to be used for the placemarks'''
    kmlStyles = []
    for level in ADVISORY_SCALE:
        # build the dot style
        innerIconStyle = styles.IconStyle(NAME_SPACE,
                                          scale=.7,
                                          icon_href=buildDotIconUrl(level))
        iconStyle = styles.Style(NAME_SPACE,
                                 id=getDotIconId(level),
                                 styles=[innerIconStyle])
        kmlStyles.append(iconStyle)

        # build the polygon style
        innerPolyStyle = styles.PolyStyle(NAME_SPACE,
                                          color='33' + ADVISORY_SCALE[level],
                                          fill=1,
                                          outline=1)
        innerLineStyle = styles.LineStyle(NAME_SPACE,
                                          color='FF' + ADVISORY_SCALE[level],
                                          width=2)
        polyStyle = styles.Style(NAME_SPACE,
                                 id=getPolyStyleId(level),
                                 styles=[innerLineStyle, innerPolyStyle])
        kmlStyles.append(polyStyle)
    return kmlStyles
Ejemplo n.º 2
0
def tiles_to_kml(tiles, filename, name):
    # Create the root KML object
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    s = styles.Style(id="s", styles=[styles.LineStyle(color="ff0000ff", width=1)])

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns, name=name, styles=[s])
    k.append(d)

    # Create a KML Folder and add it to the Document
    f = kml.Folder(ns, name=name)
    d.append(f)

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    for tile_id in tiles:
        tile = Tile(tile_id)
        p = kml.Placemark(ns, tile_id, styleUrl="#s")
        p.geometry = tile.line_string_lon_lat
        f.append(p)

    print(k.to_string(prettyprint=True))
    with open(filename, 'w') as hf:
        hf.write(k.to_string(prettyprint=True))
    return True
Ejemplo n.º 3
0
	def write_to_kml(self,filename):
		k = kml.KML()
		ns = '{http://www.opengis.net/kml/2.2}'
		d = kml.Document(ns=ns, name='SNOPT Stitched Trajectory')

		#styles
		s = styles.Style(id='yellowLineGreenPoly')
		ls = styles.LineStyle(color='7f00ff00',width=4)
		ps = styles.PolyStyle(color='7f00ff00')
		s.append_style(ls)
		s.append_style(ps)
		d.append_style(s)

		#placemark
		pm = kml.Placemark(name='Stitched Trajectory',description='Trajectory for EADDDAS',styleUrl='#yellowLineGreenPoly')
		geom = Geometry()
		coords = []
		for i,x in enumerate(self.east):
			coord = [0]*3
			coord[1] = self.ka.lat + self.north[i]/111111.0 #lat
			coord[0] = self.ka.lon + self.east[i]/(111111.0*cos(coord[1]*pi/180)) #lon
			coord[2] = self.ka.alt + self.up[i] #alt
			coords.append(tuple(coord))
		geom.geometry = LineString(coords)
		geom.extrude = True
		geom.tessellate = True
		geom.altitude_mode = 'absolute'
		pm.geometry = geom
		d.append(pm)
		k.append(d)
		kmlfile = open(filename,"w")
		kmlfile.write(k.to_string(prettyprint=True))
		kmlfile.close()	
Ejemplo n.º 4
0
def gen_placemark_from_Line(coords, ns, names):
    """
    create a placemark object for kml
    :param coords: list of the base line and optionaly the offsets lines
    :type coords: list of coordinates
    :param ns: ns of kml version
    :type ns: str
    :param name: list of line names
    :type name: list of str
    :return: list of placemark object
    :rtype: list of placemark
    """
    outplacemarks = []
    name_l = [name for name in names if 'offset_l' in name]
    name_r = [name for name in names if 'offset_r' in name]
    name_b = [
        name for name in names
        if 'offset_r' not in name and 'offset_l' not in name
    ]
    coords_l = [
        coords[names.index(name)] for name in names if 'offset_l' in name
    ]
    coords_r = [
        coords[names.index(name)] for name in names if 'offset_r' in name
    ]
    dim = len(coords_r)
    coords_b = [
        coords[names.index(name)] for name in names
        if 'offset_r' not in name and 'offset_l' not in name
    ]
    colors = color_range_gen(dim + 1)
    for i in range(dim):
        ls = styles.LineStyle(ns=ns, id=None, color=colors[i + 1], width=1.5)
        s1 = styles.Style(styles=[ls])
        outplacemark_l = kml.Placemark(ns, None, name_l[i], None, styles=[s1])
        outplacemark_r = kml.Placemark(ns, None, name_r[i], None, styles=[s1])
        outplacemark_l.geometry = LineString(coords_l[i])
        outplacemark_r.geometry = LineString(coords_r[i])
        outplacemarks.append(outplacemark_l)
        outplacemarks.append(outplacemark_r)
    ls = styles.LineStyle(ns=ns, id=None, color=colors[0], width=3)
    s1 = styles.Style(styles=[ls])
    outplacemark = kml.Placemark(ns, None, name_b[0], None, styles=[s1])
    outplacemark.geometry = LineString(coords_b[0])
    outplacemarks.append(outplacemark)

    return outplacemarks
Ejemplo n.º 5
0
def colorizedGlyph(data, folderPath, docname, nbins, limits, cmap_type):
	# data: a numpy matrix with [latitude, longitude, height, f] in each row. Where f is the variable asociated with the color.
	# folderPath: a string with the folder path
	# nbins: number of beans of the color map
	# limits: a list [min, max] which are the limits of our color scale.
	# cmap_type: a string with the name of the colormap. Read matplotlib.cm reference for further information.
	
	 
	colormap = cm.get_cmap(cmap_type, nbins)
	
	
	# Create the root KML object
	k = kml.KML()
	ns = '{http://www.opengis.net/kml/2.2}'

	# Create a KML Document and add it to the KML root object
	docid=''
	docdescription='This file was generated automaticaly with fastKML to colorize the aeroglyph.'
	kdoc = kml.Document(ns, docid, docname, docdescription)
	k.append(kdoc)
	
	# Create a KML Folder and add it to the Document
	folder1 = kml.Folder(ns, '', 'aeroglyph', '')
	kdoc.append(folder1)
	
	
	puntoPrev=[]
	idPunto=0
	for punto in data:
		if(idPunto!=0):
			u=(punto[3]-limits[0])/(limits[1]-limits[0])
			uprev=(puntoPrev[3]-limits[0])/(limits[1]-limits[0])
			u=(u+uprev)/2
			
			rgbcolor=colormap(u)
			
			hexcolor=colors.to_hex(rgbcolor, keep_alpha=True)
			hexcolor=hexcolor[-2:]+hexcolor[1:7]
			

			# Create a Placemark with a LineString geometry and add it to the Document
			estilolinea = styles.LineStyle(ns, color=hexcolor, width=4)
			estilo = styles.Style(styles=[estilolinea])
			p = kml.Placemark(ns, str(idPunto), styles=[estilo])
			p.geometry =  LineString([puntoPrev[0:3], punto[0:3]])
			# _geometry attribute is supposed not to be accessed directly
			# we have to look for a better solution using fastkml functions.
			p._geometry.altitude_mode='absolute'
			folder1.append(p)
			
		puntoPrev=punto
		idPunto+=1
	
	# write kml buffer to our file.
	fileHandle= open(folderPath+docname+'.kml',"w+")
	fileHandle.write(k.to_string(prettyprint=True))
	fileHandle.close()
Ejemplo n.º 6
0
def write_kml(messages, output_filename):
    """ Sort messages on timestamp, convert to KML and write to disk """
    # Sort since when saving to a file on the watch, they may be out of order
    messages.sort(key=lambda x: x.epoch)

    # Create KML file
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'watch-loc-data', 'Watch location data')
    k.append(d)
    f = kml.Folder(ns, 'all-data', 'All location data')
    d.append(f)
    s = [
        kml.Style(ns, 'styles', [
            styles.LineStyle(ns, 'linestyle', 'FF0000FF', width=2),
            styles.PolyStyle(ns, 'polystyle', '00FFFFFF'),
        ])
    ]

    i = 0
    pt_prev = None
    ts_prev = None

    for msg in messages:
        if msg.message_type == SensorData.MESSAGE_TYPE_LOCATION:
            # Skip if invalid lat/lon/alt value
            if msg.longitude == 0.0 and msg.latitude == 0.0 and msg.horiz_acc == 0.0:
                continue
            if msg.altitude == 0.0 and msg.vert_acc == 0.0:
                continue

            ts = datetime.fromtimestamp(msg.epoch)
            pt = (msg.longitude, msg.latitude, msg.altitude)

            # We're drawing lines between points, so skip the first point
            if i != 0:
                p = kml.Placemark(ns,
                                  'point-' + str(i),
                                  'point-' + str(i),
                                  styles=s)
                p.geometry = geometry.Geometry(ns,
                                               'geometry-' + str(i),
                                               geometry.Polygon(
                                                   [pt_prev, pt, pt, pt_prev]),
                                               altitude_mode='absolute')
                p.begin = ts_prev
                p.end = ts
                f.append(p)

            i += 1
            pt_prev = pt
            ts_prev = ts

    with open(output_filename, "w") as f:
        f.write(k.to_string(prettyprint=True))
Ejemplo n.º 7
0
def kml_tiles(geometry, max_sq_geometry=None, individual: bool = False) -> str:
    ns = '{http://www.opengis.net/kml/2.2}'
    k = kml.KML(ns)

    style_normal = kml_styles.Style(id='normal',
                                    styles=[
                                        kml_styles.LineStyle(color="400000ff",
                                                             width=1),
                                        kml_styles.PolyStyle(
                                            color="300000ff",
                                            outline=(1 if individual else 0)),
                                    ])
    style_max_sq = kml_styles.Style(id='max_sq',
                                    styles=[
                                        kml_styles.LineStyle(color="40ff0000",
                                                             width=1),
                                        kml_styles.PolyStyle(
                                            color="30ff0000",
                                            outline=(1 if individual else 0)),
                                    ])

    d = kml.Document(ns,
                     name="explorer tiles",
                     styles=[style_normal, style_max_sq])
    k.append(d)

    p = kml.Placemark(ns, styleUrl="#normal")
    p.geometry = geometry
    d.append(p)

    if max_sq_geometry:
        p = kml.Placemark(ns, styleUrl="#max_sq")
        p.geometry = max_sq_geometry
        d.append(p)

    return k.to_string(prettyprint=True)
Ejemplo n.º 8
0
def generate_kml(fname, poi_df):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    styid = 'style1'
    # colors in KML: aabbggrr, aa=00 is fully transparent
    sty = styles.Style(id=styid,
                       styles=[styles.LineStyle(color='9f0000ff',
                                                width=2)])  # transparent red
    doc = kml.Document(ns, '1', 'POIs', 'POIs visualization', styles=[sty])
    k.append(doc)

    # Placemark for POIs
    for ix in poi_df.index:
        name = poi_df.loc[ix, 'poiName']
        cat = poi_df.loc[ix, 'poiTheme']
        lat = poi_df.loc[ix, 'poiLat']
        lon = poi_df.loc[ix, 'poiLon']
        url = poi_df.loc[ix, 'poiURL']
        ext_data = kml.ExtendedData(
            ns,
            elements=[
                kml.Data(
                    name='video',
                    value=
                    "![CDATA[<iframe name='Framename' width='480' height='360' src='%s' frameborder='0'></iframe><br><br>]]"
                    % (url))
            ])

        desc = ''.join([
            'POI Name: ', name, '<br/>Category: ', cat,
            '<br/>Coordinates: (%f, %f)' % (lat, lon), '<br/>URL: ', url
        ])
        pm = kml.Placemark(ns,
                           str(ix),
                           name,
                           desc,
                           styleUrl='#' + styid,
                           extended_data=ext_data)
        pm.geometry = Point(lon, lat)
        doc.append(pm)

    # save to file
    kmlstr = k.to_string(prettyprint=True)
    with open(fname, 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write(kmlstr)
Ejemplo n.º 9
0
    def trails(self, data):
        #print(data)
        self.description = ""
        color = "ffffff00"
        if 'name' in data:
            name = data['name']
        id = data['osm_id']
        width = 3
        if 'sac_scale' in data:
            tmp = data['sac_scale']
            index = tmp.split(';')
            color = self.colors[self.default[index[0]]['color']]
            # id = self.default[index]['id']
            width = self.default[index[0]]['width']
            #self.description += "<br>Sac_scale: " + data['sac_scale']
        if 'mtb:scale:imba' in data:
            self.description += "<br>Mnt Scale: " + str(data['mtb:scale:imba'])
        if 'mtb:scale' in data:
            pass
            # self.description += "<br>Mnt Scale: " + str(data['mtb:scale'])

        # Create the description pop-up
        if 'surface' in data:
            self.description += "<br>Surface: " + data['surface']
        if 'bicycle' in data:
            self.description += "<br>Bicycle: " + data['bicycle']
        if 'horse' in data:
            self.description += "<br>Horse: " + data['horse']
        if 'atv' in data:
            self.description += "<br>Atv: " + data['atv']
        if 'access' in data:
            self.description += "<br>Access: " + data['access']
        if 'tracktype' in data:
            self.description += "<br>Tracetype: " + data['tracktype']
        if 'trail_visibility' in data:
            self.description += "<br>Visability: " + data['trail_visibility']
        if 'motor_vehicle' in data:
            self.description += "<br>Motor Vehicle: " + data['motor_vehicle']

        lstyle = styles.LineStyle(color=color, width=width)
        self.styles = styles.Style(styles=[lstyle])

        #print(self.description)
        return self.styles, self.description
Ejemplo n.º 10
0
def main(argv):
    # Get command line options
    try:
        opts, args = getopt.getopt(argv, "hf:o:a:",
                                   ["filepath=", "long-start=", "lat-start="])
    except getopt.GetoptError:
        print 'create-haworth-cemetery-f-kml.py -f <filepath> -o <long start> -a <lat start>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'create-haworth-cemetery-f-kml.py -f <filepath> -o <long start> -a <lat start>'
            sys.exit()
        elif opt in ("-f", "--filepath"):
            filepath = arg
        elif opt in ("-o", "--long-start"):
            long_start = float(arg)
        elif opt in ("-a", "--lat-start"):
            lat_start = float(arg)

    map_origin = Point(long_start, lat_start)

    # Read in all the graves as objects and stick them in a grid.
    graveyard = [[None for i in range(GRAVEYARD_MAX_SIZE)]
                 for j in range(GRAVEYARD_MAX_SIZE)]
    with open(filepath) as csvfile:
        reader = csv.DictReader(csvfile)
        for r in reader:
            if r['column']:
                row = int(r['row'])
                column = int(r['column'])
                graveyard[row][column] = Grave(r['section'], r['grave_id'],
                                               row, column, r['inscription'])
    # Create the root KML object.
    k = kml.KML()

    # Create the KML Document styles to use.
    doc_styles = []
    a = []
    a.append(styles.LineStyle(NS, None, 'ffbdbdbd'))
    a.append(styles.PolyStyle(NS, None, '4dbdbdbd'))
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-normal', a))
    a[0] = styles.LineStyle(NS, None, 'ffbdbdbd', None, 2)
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-highlight', a))
    doc_styles.append(
        kml.StyleMap(NS, "poly-BDBDBD-1-77",
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-normal'),
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-highlight')))

    # Create the KML Document, and add it to the KML root object.
    d = kml.Document(NS, None, NAME, DESCRIPTION.format(SECTION), doc_styles)
    k.append(d)

    # Create a KML Folder for the section and add it to the Document.
    f = kml.Folder(NS, None, "Section {}".format(SECTION))
    k.append(f)

    # Process the graveyard grid, creating a Placemark with a polygon for each grave.
    for i in range(GRAVEYARD_MAX_SIZE):
        for j in range(GRAVEYARD_MAX_SIZE):
            if graveyard[i][j]:
                g = graveyard[i][j]
                name = '{}-{}'.format(g.section, g.grave_id)
                p = kml.Placemark(NS, None, name.lower(), g.inscription, None,
                                  '#poly-BDBDBD-1-77')
                lon = long_start + (i * (LONG_2FEET * 3))
                lat = lat_start + (j * (LAT_2FEET * 2))
                p.geometry = Polygon([
                    (lon, lat, 0), (lon + LONG_3FEET + LONG_2FEET, lat, 0),
                    (lon + LONG_3FEET + LONG_2FEET, lat + LAT_3FEET, 0),
                    (lon, lat + LAT_3FEET, 0), (lon, lat, 0)
                ])
                p.geometry = shapely.affinity.rotate(p.geometry,
                                                     ADJUSTMENT_ANGLE,
                                                     map_origin)
                f.append(p)

    # Print out the KML Object as a string.
    print k.to_string(prettyprint=True)
Ejemplo n.º 11
0
   heading=float(nmea[54:59])
   speed_kt=float(nmea[47:53])
 speed_kmh=speed_kt*1.852
 if speed_kmh > kmh_max:
   kmh_max = speed_kmh
 if speed_kmh < kmh_min:
   kmh_min = speed_kmh
 if lonlat_prev:
   dist_m = distance(lonlat_prev[1], lonlat_prev[0], lonlat[1], lonlat[0])
   travel += dist_m
   if dist_m < discontinuety_m: # don't draw too long lines
     # if no IRI20 available, take IRI100 for color and name
     iri_avg_main = iri_avg
     if iri20_avg > 0:
       iri_avg_main = iri20_avg
     ls0 = styles.LineStyle(ns,
       color=("%08X" % color32(iri_avg_main/red_iri)), width=6)
     lsty0 = styles.Style(styles = [ls0])
     p1 = kml.Placemark(ns, 'id',
       name=("%.2f" % iri_avg_main),
       description=(
         ("L100=%.2f mm/m\n"
          "R100=%.2f mm/m\n"
          "L20=%.2f, R20=%.2f\n"
          "Lc=%.2f, Rc=%.2f\n"
          "azl0=%.3e, azr0=%.3e\n"
          "slope_l=%.3e, slope_r=%.3e\n"
          "phi=%.1f, theta=%.1f, psi=%.1f\n"
          "v=%.1f km/h\n%s"
         ) %
         (iri_left, iri_right,
          iri20_left, iri20_right,
Ejemplo n.º 12
0
def write_kml_tiles(out_filepath,
                    tiles,
                    land_mask_filepath,
                    doc_name="doc name",
                    doc_desc="doc description"):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', doc_name, doc_desc)
    k.append(d)
    p_style = styles.PolyStyle(ns, 'id', fill=0)
    l_style = styles.LineStyle(ns, 'id', color="FF0000FF")
    sty = kml.Style(ns, 'id', styles=[p_style, l_style])

    # read SHP land mask
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds_mask = driver.Open(land_mask_filepath, update=False)
    layer_mask = ds_mask.GetLayer()

    for tile_counter in range(0, tiles.shape[2]):
        points = tiles[:, :, tile_counter]
        points = np.concatenate((points, np.array([points[0, :]])), axis=0)
        polygon_points = []
        for point in points:
            polygon_points.append((float(point[0]), float(point[1])))
        f = kml.Folder(ns, 'fid', 'f name', 'f description')
        d.append(f)
        # define geometry
        geom = geometry.Geometry()
        geom.geometry = Polygon(polygon_points)

        # create and add metadata
        polygon = ogr.CreateGeometryFromWkt(geom.geometry.wkt)
        coversland = False
        for feat_mask in layer_mask:
            if polygon.Intersects(feat_mask.geometry()):
                coversland = True
                break
        layer_mask.ResetReading()
        ll_lon = int(np.min(points[:, 0]))
        ll_lat = int(np.min(points[:, 1]))
        extent = int(np.max(points[:, 0]) - np.min(points[:, 0]))
        tilename = "{:03d}_{:03d}".format(
            int(np.min(points[:, 0])) + 180,
            int(np.min(points[:, 1])) + 90)
        schema_data = kml.SchemaData(
            ns,
            schema_url="#" +
            os.path.splitext(os.path.basename(out_filepath))[0])
        schema_data.append_data(name="GRID", value="LatLon Grid")
        schema_data.append_data(name="VERSION", value="V1")
        schema_data.append_data(name="ZONE", value="Globe")
        schema_data.append_data(name="SHORTNAME", value="LLG GL")
        schema_data.append_data(name="TILE", value=tilename)
        schema_data.append_data(name="EXTENT", value=str(extent))
        schema_data.append_data(name="LLLON", value=str(ll_lon))
        schema_data.append_data(name="LLLAT", value=str(ll_lat))
        schema_data.append_data(name="COVERSLAND", value=str(int(coversland)))
        # create placemark
        p = kml.Placemark(ns,
                          'id',
                          extended_data=kml.ExtendedData(
                              ns, elements=[schema_data]))
        p.geometry = geom
        p.append_style(sty)
        f.append(p)

    with open(out_filepath, 'w') as filehandle:
        filehandle.write(k.to_string(prettyprint=True))
Ejemplo n.º 13
0
    def roads(self, data):
        """
        trunk - Wide Red/Orange, "salmon1"
        motorway - Wide pink,  "lightpink3"
        primary - Wide light orange, "burlywood1"
        tertiary - Wide white, "white"
        secondary - Wide Yellow, "yellow"
        unclassified - white, "white"
        residential - white, "white"
        track - dotted brown, "brick"
        path - dotted red, "red"
        service - white, "white"
        footway - dotted red, "red"
        road - gray, "gray"
        """

        index = data['highway']
        #logging.debug("Looking for road type: %r" % index)
        width = 3.0
        try:
            id = self.default[index]['id']
            width = self.default[index]['width']
            color = self.colors[self.default[diff]['color']]
        except:
            color = 'pink'

        self.description = ""

        # Tags that go in the description popyup
        if 'service' in data:
            if data['service'] == 'driveway':
                color = self.colors[self.default['driveway']['color']]
                self.description += "Private Driveway"
        else:
            if 'name' in data:
                self.description += "<br>Name: " + data['name']
        if 'alt_name' in data:
            self.description += "<br>Alt Name: " + data['alt_name']
        if 'tracktype' in data:
            if data['tracktype'] == 'yes':
                color = self.colors[self.default['tracktype']['color']]
                self.description += "<br>Tracktype: " + data['tracktype']
        if 'motor_vehicle' in data:
            if data['motor_vehicle'] == 'yes':
                color = self.colors[self.default['motor_vehicle']['color']]
                self.description += "<br>Vehicles OK: yes"
        if 'access' in data:
            if data['access'] == 'private':
                color = self.colors[self.default['private']['color']]
        if 'atv' in data:
            if data['atv'] == 'yes':
                color = self.colors[self.default['atv']['color']]
                self.description += "<br>ATVs OK: yes"
        if 'horse' in data:
            if data['horse'] == 'yes':
                color = self.colors[self.default['horse']['color']]
                self.description += "<br>Horse OK: yes"
        if 'bicycle' in data:
            if data['bicycle'] == 'yes':
                color = self.colors[self.default['bicycle']['color']]
                self.description += "<br>Bicycle OK: yes"
        if '4wd_only' in data:
            if data['4wd_only'] == 'yes':
                color = self.colors[self.default['4wd_only']['color']]
            self.description += "<br>4wd Only: " + data['4wd_only']
        if 'smoothness' in data:
            pass
        if 'surface' in data:
            pass
        self.description += "<p>Data: %r" % data

        lstyle = styles.LineStyle(color=color, width=width)
        self.styles = styles.Style(styles=[lstyle])

        #print(self.description)
        return self.styles, self.description
def main(argv):
    # Get command line options
    try:
        opts, args = getopt.getopt(argv, "ho:a:",
                                   ["long-start=", "lat-start="])
    except getopt.GetoptError:
        print 'test-rotation-kml.py -o <long start> -a <lat start>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test-rotation-kml.py -o <long start> -a <lat start>'
            sys.exit()
        elif opt in ("-o", "--long-start"):
            long_start = float(arg)
        elif opt in ("-a", "--lat-start"):
            lat_start = float(arg)

    map_origin = Point(long_start, lat_start)

    k = kml.KML()

    # Create the KML Document styles to use.
    doc_styles = []
    a = []
    a.append(styles.LineStyle(NS, None, 'ffbdbdbd'))
    a.append(styles.PolyStyle(NS, None, '4dbdbdbd'))
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-normal', a))
    a[0] = styles.LineStyle(NS, None, 'ffbdbdbd', None, 2)
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-highlight', a))
    doc_styles.append(
        kml.StyleMap(NS, "poly-BDBDBD-1-77",
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-normal'),
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-highlight')))

    # Create the KML Document, and add it to the KML root object.
    d = kml.Document(NS, None, NAME, DESCRIPTION.format(SECTION), doc_styles)
    k.append(d)

    # Create a KML Folder for the section and add it to the Document.
    f = kml.Folder(NS, None, "Section {}".format(SECTION))
    k.append(f)

    # Process a spiral of markers in a counter-clockwise direction
    lon = long_start + (OBJECT_START_ROW * (LONG_2FEET * 3))
    lat = lat_start + (OBJECT_START_COL * (LAT_2FEET * 2))
    adjustment_angle = 0.00
    while adjustment_angle < 360:
        name = 'Degrees: {}'.format(adjustment_angle)
        p = kml.Placemark(NS, None, name, "Test Rotation", None,
                          '#poly-BDBDBD-1-77')
        p.geometry = Polygon([(lon, lat, 0),
                              (lon + LONG_3FEET + LONG_2FEET, lat, 0),
                              (lon + LONG_3FEET + LONG_2FEET, lat + LAT_3FEET,
                               0), (lon, lat + LAT_3FEET, 0), (lon, lat, 0)])
        p.geometry = shapely.affinity.rotate(p.geometry, adjustment_angle,
                                             map_origin)
        f.append(p)
        adjustment_angle += ADJUSTMENT_ANGLE_INCR

    # Print out the KML Object as a string.
    print k.to_string(prettyprint=True)
Ejemplo n.º 15
0
 f = kml.Folder(ns, 'Antennas_' + dpa_id, 'Antennas',
                'Antenna Angles')
 placementDoc.append(f)
 feature1[feature_index].append(f)
 for c in newcover:
     center = c[0]
     index = c[1]
     angle = c[2]
     print "==== center index angle ====", center, index, angle
     lon, lat = basemap(center[0], center[1], inverse=True)
     lobe = antennacover.translate_and_rotate(
         antenna_cover_patterns, center, index, angle)
     # Note that our frame of reference is Due EAST but the conventional
     # way of specifying angles is due north.
     angle_degrees = (angle / math.pi * 180 - 90) % 360
     lstyle = styles.LineStyle(color='ff0055ff', width=2.0)
     style = styles.Style(styles=[lstyle])
     p = kml.Placemark(
         ns,
         "antenna" + str(lobe_counter),
         'antenna',
         'Sensitivity (dBm): ' +
         str(antenna_cover_patterns[index].sensitivity_dbm) +
         ", Aperture angle: " + str(aperture_angle) + " degrees" +
         ", lon : " + str(lon) + " lat : " + str(lat) +
         ", Azimuth angle: " +
         str(float(np.round(angle_degrees, 2))),
         styles=[style])
     p.geometry = projection.polygon_to_latlon(lobe)
     # p.styles.StyleUrl(url='http://maps.google.com/mapfiles/kml/shapes/placemark_square.png')
     # p.styles.IconStyle(color='#ff5500', scale=2)
Ejemplo n.º 16
0
    def __init__(self, ns):
        self.ns = ns
        self.description = ""
        self.default = dict()
        self.icons = list()

        self.colors = dict()
        self.colors['pink'] = 'ffff00ff'
        self.colors['red'] = 'ff0000ff'
        self.colors['gray'] = 'ff808080'
        self.colors['black'] = 'ff000000'
        self.colors['orange'] = 'ff00a5ff'
        self.colors['yellow'] = 'ffffff00'
        self.colors['magenta'] = 'ffff00ff'
        self.colors['maroon'] = 'ff800000'
        self.colors['purple'] = 'ff800080'
        self.colors['cyan'] = 'ff00ffff'
        self.colors['lightblue'] = 'ff00ffff'
        self.colors['blue'] = 'ffff0000'
        self.colors['darkblue'] = 'ff000080'
        self.colors['teal'] = 'ff008080'
        self.colors['olive'] = 'ff808000'
        self.colors['lightgreen'] = 'ff00ff00'
        self.colors['green'] = 'ff008000'
        self.colors['darkgreen'] = 'ff008000'
        self.colors['brown'] = 'ff008000'  # FIXME: wrong value!

        # Access
        width = 3.0
        self.default['private'] = {"color": "gray", "width": width}

        # highway=path
        self.default['hiking'] = {"color": "brown", "width": width}
        self.default['mountain_hiking'] = {"color": "orange", "width": width}
        self.default['demanding_mountain_hiking'] = {
            "color": "purple",
            "width": width
        }
        self.default['alpine_hiking'] = {"color": "lightblue", "width": width}
        self.default['demanding_alpine_hiking'] = {
            "color": "lightblue",
            "width": width
        }
        self.default['difficult_alpine_hiking'] = {
            "color": "lightblue",
            "width": width
        }

        self.default['0'] = {"color": "brown", "width": width}
        self.default['1'] = {"color": "green", "width": width}
        self.default['2'] = {"color": "blue", "width": width}
        self.default['3'] = {"color": "red", "width": width}
        self.default['4'] = {"color": "black", "width": width}

        # Tracktype
        self.default['grade1'] = {
            "color": "brown",
            "id": "BrownLine",
            "width": 2.0
        }
        self.default['grade2'] = {
            "color": "green",
            "id": "BrownLine",
            "width": 2.0
        }
        self.default['grade3'] = {
            "color": "blue",
            "id": "BrownLine",
            "width": 2.0
        }
        self.default['grade4'] = {
            "color": "red",
            "id": "BrownLine",
            "width": 2.0
        }

        # highway=*
        self.default['trunk'] = {
            "color": "orange",
            "id": "Wide Red/Orange",
            "width": 3.0
        }
        self.default['motorway'] = {
            "color": "lightpink3",
            "id": "WideLightPink",
            "width": 3.0
        }
        self.default['primary'] = {
            "color": "burlywood1",
            "id": "WideLightOrange",
            "width": 3.0
        }
        self.default['tertiary'] = {
            "color": "white",
            "id": "WideWhite",
            "width": 3.0
        }
        self.default['secondary'] = {
            "color": "yellow",
            "id": "WideYellow",
            "width": 3.0
        }
        # Space cadets... fix later when possible
        self.default['road'] = {"color": "black", "id": "gray", "width": 3.0}
        self.default['service'] = {
            "color": "red",
            "id": "RedLine",
            "width": 3.0
        }
        self.default['motorway_link'] = {
            "color": "red",
            "id": "RedLine",
            "width": 3.0
        }
        self.default['secondary_link'] = {
            "color": "yellow",
            "id": "YellowLine",
            "width": 3.0
        }
        self.default['trunk_link'] = {
            "color": "salmon1",
            "id": "OrangeLine",
            "width": 3.0
        }
        self.default['living_street'] = {
            "color": "white",
            "id": "whiteLine",
            "width": 3.0
        }

        # Probably added by me
        self.default['unclassified'] = {
            "color": "white",
            "id": "whiteLine",
            "width": 3.0
        }
        self.default['residential'] = {
            "color": "white",
            "id": "whiteLine",
            "width": 3.0
        }
        self.default['track'] = {
            "color": "brown",
            "id": "DottedBrown",
            "width": 3.0
        }
        self.default['4wd_only'] = {
            "color": "black",
            "id": "dotted brown",
            "width": 3.0
        }

        # handled by self.trails
        #self.default['path']= { "color": "black", "id": "dotted red", "width": 3.0}
        self.default['driveway'] = {
            "color": "white",
            "id": "whiteLine",
            "width": 3.0
        }
        # a footway is a sidewalk, so we don't care
        #self.default['footway'] = { "color": "black", "id": "dotted red", "width": 3.0}
        self.default['cycleway'] = {
            "color": "black",
            "id": "dotted red",
            "width": 3.0
        }
        self.default['bridleway'] = {
            "color": "black",
            "id": "dotted red",
            "width": 3.0
        }

        # Ignore surface tag for now
        #self.default['dirt'] = { "color": "black", "id": "dotted red", "width": 3.0}

        # Ignore tracktype tag for now
        #self.default['grade1'] = { "color": "black", "id": "dotted red", "width": 3.0}

        # For smoothness tag
        self.default['impassable'] = {
            "color": "blue",
            "id": "blue",
            "width": 3.0
        }
        self.default['poor'] = {"color": "blue", "id": "blue", "width": 3.0}
        self.default['bad'] = {"color": "blue", "id": "blue", "width": 3.0}
        self.default['horrible'] = {
            "color": "blue",
            "id": "blue",
            "width": 3.0
        }
        self.default['very_horrible'] = {
            "color": "blue",
            "id": "blue",
            "width": 3.0
        }

        #
        self.default['motor_vehicle'] = {
            "color": "blue",
            "id": "blue",
            "width": 1.0
        }
        self.default['horse'] = {"color": "blue", "id": "blue", "width": 1.0}
        self.default['atv'] = {"color": "blue", "id": "blue", "width": 1.0}
        self.default['bicycle'] = {"color": "blue", "id": "blue", "width": 1.0}

        # Piste trail grooming
        # self.default['backcountry'] = { "color": "yellow", "id": "yellow", "width": 1.0}
        # self.default['nordic'] = { "color": "blue", "id": "blue", "width": 1.0}
        # self.default['downhill'] = { "color": "blue", "id": "blue", "width": 1.0}
        self.default['skitour'] = {"color": "blue", "id": "blue", "width": 1.0}
        self.default['snow_park'] = {
            "color": "blue",
            "id": "blue",
            "width": 1.0
        }
        self.default['snowshoe'] = {
            "color": "blue",
            "id": "blue",
            "width": 1.0
        }
        self.default['skating'] = {"color": "blue", "id": "blue", "width": 1.0}
        self.default['classic'] = {"color": "blue", "id": "blue", "width": 1.0}

        self.linestyles = list()
        for key, val in self.default.items():
            # lstyle = styles.LineStyle(id=val['id'], color=val['color'], width=val['width'])
            lstyle = styles.LineStyle(color=val['color'], width=val['width'])
            self.linestyles.append(styles.Style(styles=[lstyle]))
            self.styles = list()

        self.description = ""
Ejemplo n.º 17
0
    def piste(self, data):
        self.description = ""
        color = "ffffff00"
        if 'piste:name' in data:
            name = data['piste:name']
        if 'name' in data:
            name = data['name']
            if 'piste:name' in data:
                self.description += data['piste:name']
        id = data['osm_id']
        width = 3

        # Colors based on https://wiki.openstreetmap.org/wiki/Piste_Maps
        # Downhill Piste difficulty
        downhill = dict()
        width = 2.0
        downhill['easy'] = {"color": "lightgreen", "width": width}
        downhill['novice'] = {"color": "lightgreen", "width": width}
        downhill['intermediate'] = {"color": "blue", "width": width}
        downhill['extreme'] = {"color": "orange", "width": width}
        downhill['freeride'] = {"color": "yellow", "width": width}
        downhill['expert'] = {"color": "gray", "width": width}
        downhill['advanced'] = {"color": "gray", "width": width}
        downhill['unknown'] = {"color": "gray", "width": width}
        downhill['Traverse'] = {"color": "gray", "width": width}

        nordic = dict()
        width = 1.0
        nordic['easy'] = {"color": "cyan", "width": width}
        nordic['novice'] = {"color": "cyan", "width": width}
        nordic['intermediate'] = {"color": "blue", "width": width}
        nordic['expert'] = {"color": "gray", "width": width}
        nordic['advanced'] = {"color": "gray", "width": width}
        nordic['skating'] = {"color": "yellow", "width": width}
        nordic['classic'] = {"color": "green", "width": width}
        nordic['classic+skating'] = {"color": "green", "width": width}
        nordic['unknown'] = {"color": "black", "width": width}

        if 'piste:type' not in data:
            data['piste:type'] = 'downhill'

        if 'piste:difficulty' not in data:
            # When in doubt, make it bad
            diff = 'unknown'
            data['piste:difficulty'] = 'unknown'
        else:
            diff = data['piste:difficulty']

        if 'piste:type' in data:
            self.description += "<br>Type: " + data['piste:type']
            if data['piste:type'] == 'downhill':
                color = self.colors[downhill[diff]['color']]
                # id = downhill[diff]['osm_id']
                width = downhill[diff]['width']
            elif data['piste:type'] == 'nordic':
                diff = data['piste:difficulty']
                color = self.colors[nordic[diff]['color']]
                # id = nordic[diff]['osm_id']
                width = nordic[diff]['width']
                # FIXME: improve these colors
            else:
                logging.warning("Unsupported piste type, %r" %
                                data['piste:type'])
                color = self.colors['maroon']
                width = 1.0
        else:
            color = self.colors['purple']

        # Create the description pop-up
        if 'piste:difficulty' in data:
            self.description += "<br>Difficulty: " + data['piste:difficulty']
        else:
            data['piste:difficulty'] = 'extreme'

        if 'piste:grooming' in data:
            self.description += "<br>Grooming: " + data['piste:grooming']

        lstyle = styles.LineStyle(color=color, width=width)
        self.styles = styles.Style(styles=[lstyle])

        #print(self.description)
        return self.styles, self.description
def gen_kml(fname, traj_data, traj_stats, traj_id_list, traj_name_list=None):
    """Generate KML file"""
    assert (len(traj_id_list) > 0)
    if traj_name_list:
        assert (len(traj_id_list) == len(traj_name_list))

    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    stid = 'style1'
    # colors in KML: aabbggrr, aa=00 is fully transparent
    # developers.google.com/kml/documentation/kmlreference?hl=en#colorstyle
    st = styles.Style(id=stid,
                      styles=[styles.LineStyle(color='2f0000ff',
                                               width=3)])  # transparent red
    doc = kml.Document(ns,
                       '001',
                       'Trajectories',
                       'Trajectory visualization',
                       styles=[st])
    k.append(doc)

    stats = traj_stats[traj_stats['Trajectory_ID'].isin(traj_id_list)]
    assert (stats.shape[0] == len(traj_id_list))

    pm_traj = []
    pm_photo = []

    for i in range(len(stats.index)):
        ri = stats.index[i]
        traj_id = stats.ix[ri]['Trajectory_ID']
        photos = traj_data[traj_data['Trajectory_ID'] == traj_id]
        lngs = [lng for lng in photos['Longitude'].tolist()]
        lats = [lat for lat in photos['Latitude'].tolist()]
        name = 'Trajectory_' + str(traj_id)
        if traj_name_list: name += '_' + traj_name_list[i]
        desc = 'User_ID: '              + str(stats.ix[ri]['User_ID']) + \
               '<br/>Start_Time: '      + str(stats.ix[ri]['Start_Time']) + \
               '<br/>Travel_Distance: ' + str(round(stats.ix[ri]['Travel_Distance(km)'], 2)) + ' km' + \
               '<br/>Total_Time: '      + str(round(stats.ix[ri]['Total_Time(min)'], 2)) + ' min' + \
               '<br/>Average_Speed: '   + str(round(stats.ix[ri]['Average_Speed(km/h)'], 2)) + ' km/h' + \
               '<br/>#Photos: '         + str(stats.ix[ri]['#Photo']) + \
               '<br/>Photos: '          + str(photos['Photo_ID'].tolist())
        pm = kml.Placemark(ns, str(traj_id), name, desc, styleUrl='#' + stid)
        pm.geometry = LineString([(lngs[j], lats[j])
                                  for j in range(len(lngs))])
        pm_traj.append(pm)

        for rj in photos.index:
            name = 'Photo_' + str(photos.ix[rj]['Photo_ID'])
            desc = 'Trajectory_ID: '  + str(traj_id) + \
                   '<br/>Photo_ID: '  + str(photos.ix[rj]['Photo_ID']) + \
                   '<br/>User_ID: '   + str(photos.ix[rj]['User_ID']) + \
                   '<br/>Timestamp: ' + str(photos.ix[rj]['Timestamp']) + \
                   '<br/>Coordinates: (' + str(photos.ix[rj]['Longitude']) + ', ' + str(photos.ix[rj]['Latitude']) + ')' + \
                   '<br/>Accuracy: '  + str(photos.ix[rj]['Accuracy']) + \
                   '<br/>URL: '       + str(photos.ix[rj]['URL'])
            pm = kml.Placemark(ns, str(photos.ix[rj]['Photo_ID']), name, desc)
            pm.geometry = Point(photos.ix[rj]['Longitude'],
                                photos.ix[rj]['Latitude'])
            pm_photo.append(pm)

    for pm in pm_traj:
        doc.append(pm)
    for pm in pm_photo:
        doc.append(pm)

    kmlstr = k.to_string(prettyprint=True)
    with open(fname, 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write(kmlstr)
Ejemplo n.º 19
0
def ConvertAthenaCsvToKml(outputBucket, outputKey, inputBucket, inputKey):

    print(outputBucket)
    print(outputKey)
    print(inputBucket)
    print(inputKey)

    # Get the object from the event and show its content type
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    lstyle = styles.LineStyle(color='7dff0000', width=2.0, id='redLine')
    style = styles.Style(styles=[lstyle])

    d = kml.Document(ns, 'docid', 'doc name', 'doc description', [style])

    k.append(d)
    shapeFolder = kml.Folder(ns, 'fid', 'f name', 'f description')
    d.append(shapeFolder)

    bucket = inputBucket
    key = inputKey
    try:
        response = s3.get_object(Bucket=bucket, Key=key)
        csvRows = response['Body'].read().decode('utf-8').splitlines()

        rowIterator = iter(csvRows)
        next(rowIterator)

        for row in rowIterator:
            csvColumns = row.split(',', 1)
            icao24 = csvColumns[0].strip('"')
            pathString = csvColumns[1]
            pathString = pathString.strip('""[]')
            pathArray = pathString.split('"", ""')
            tupleArray = [tuple(map(float, x.split(','))) for x in pathArray]
            tupleArray = [(pos[1], pos[0], pos[2] * .3048)
                          for pos in tupleArray]

            if len(tupleArray) > 1:
                placemark = kml.Placemark(ns, icao24, icao24,
                                          'Flight path for ' + icao24)

                lineGeo = LineString(coordinates=tupleArray)
                placemark.geometry = geometry.Geometry(
                    geometry=lineGeo, altitude_mode='absolute')

                placemark.styleUrl = "#redLine"
                shapeFolder.append(placemark)

        s3.put_object(Body=k.to_string(),
                      ContentType='application/vnd.google-earth.kml+xml',
                      Bucket=outputBucket,
                      Key="AUSAirTraffic-" +
                      time.strftime('%l:%M%p %Z on %b %d, %Y') + ".kml")

        #print(k.to_string(prettyprint=True))

        return
    except Exception as e:
        print(e)
        raise e