Esempio 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
Esempio 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
Esempio 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()	
Esempio 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
Esempio 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()
Esempio n. 6
0
 def campground(self, data):
     self.description = ""
     icon = styles.IconStyle(icon_href="icons/campground.png")
     self.icons.append(icon.icon_href)
     self.styles = styles.Style(styles=[icon])
     self.description = ""
     if 'drinking_water' in data:
         if data['drinking_water'] == 'yes':
             self.description += "Water Available"
     if 'toilets' in data:
         if data['toilets'] == 'yes':
             self.description += "Toilet Available"
     return self.styles, self.description
Esempio 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)
Esempio n. 8
0
    def milestones(self, data):
        #print(data)
        self.description = ""
        id = data['osm_id']
        num = data['name']
        if 'alt_name' in data:
            street = data['alt_name']
        else:
            street = "unknown"
        self.description = "%s Highway %s" % (num, street)

        icon = styles.IconStyle(icon_href="icons/mm_highway_milestone.png")
        self.icons.append(icon.icon_href)
        self.styles = styles.Style(styles=[icon])

        return self.styles, self.description
Esempio n. 9
0
    def campsite(self, data=dict(), ground=None):
        self.description = ""
        icon = styles.IconStyle(icon_href="icons/mx_tourism_camp_site.png")
        self.icons.append(icon.icon_href)
        self.styles = styles.Style(styles=[icon])

        if ground is not None:
            self.description += ground

        if len(data) > 2:
            self.description += "<br><i>Has these features</i>:"

        if 'fee' in data:
            if data['fee'] == 'yes':
                self.description += "<brHas fee"
        if 'openfire' in data:
            if data['openfire'] == 'yes':
                self.description += "<br>Open fires allowed"
        if 'internet_access' in data:
            if data['internet_access'] == 'yes':
                self.description += "<br>Internet Available"
        if 'caravans' in data:
            if data['caravans'] == 'yes':
                self.description += "<br>RVs allowed"
        if 'parking' in data:
            if data['parking'] == 'yes':
                self.description += "<br>Parking Available"

        if 'drinking_water' in data:
            if data['drinking_water'] == 'yes':
                self.description += "<br>Drinking Water Available"
        if 'toilets' in data:
            if data['toilets'] == 'yes':
                self.description += "<br>Toilet Available"
        if 'bbq' in data:
            if data['bbq'] == 'yes':
                self.description += "<br>Grill Available"
        if 'power_supply' in data:
            if data['power_supply'] == 'yes':
                self.description += "<br>AC Power Available"
        if 'picnic_table' in data:
            if data['picnic_table'] == 'yes':
                self.description += "<br>Picbic table Available"
        if 'leisure' in data:
            self.description += "<br>Firepit"
        return self.styles, self.description
Esempio n. 10
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)
Esempio n. 11
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
Esempio n. 12
0
    def addresses(self, data):
        #print(data)
        self.description = ""
        color = "ffffff00"
        id = data['osm_id']
        name = ""
        if 'name' in data:
            if data['name'] is not None:
                name = data['name'] + '\n'

        if 'addr_street' in data:
            self.description = "%s %s %s" % (name, str(
                data['addr_housenumber']), data['addr_street'])
        # label = styles.LabelStyle(color='black', scale=1.0)
        icon = styles.IconStyle(icon_href="icons/mm_building.png")
        self.icons.append(icon.icon_href)
        self.styles = styles.Style(styles=[icon])

        return self.styles, self.description
Esempio n. 13
0
    def firewater(self, data):
        self.description = ""
        if 'water_tank' in data:
            icon = styles.IconStyle(
                icon_href="icons/mx_fire_hydrant_type_pillar.png")

        if 'emergency' in data:
            if data['emergency'] == "fire_hydrant":
                icon = styles.IconStyle(
                    icon_href="icons/mx_fire_hydrant_type_pillar.png")
            elif data['emergency'] == "water_tank":
                icon = styles.IconStyle(icon_href="icons/mx_storage_tank.png")
            elif data['emergency'] == "fire_water_pond":
                icon = styles.IconStyle(icon_href="icons/water.png")
            elif data['emergency'] == "suction_point":
                icon = styles.IconStyle(icon_href="icons/water.png")
            else:
                icon = styles.IconStyle(icon_href="icons/water.png")

        self.icons.append(icon.icon_href)
        self.styles = styles.Style(styles=[icon])
        return self.styles, self.description
Esempio n. 14
0
 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,
          srvz[0] / (n_buf_points*1000), srvz[1] / (n_buf_points*1000),
Esempio n. 15
0
                '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)
     p.name = Doc.name.text
Esempio n. 16
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
Esempio n. 17
0
    def run(self):
        while True:
            #poison pill check
            if self.poison == True:
                break
            else:
                #read gps data (don't block)
                msg = self.master.recv_match(type='GLOBAL_POSITION_INT',
                                             blocking=False)
                if msg:
                    #print msg
                    self.aclat = msg.lat / 1e7
                    self.aclon = msg.lon / 1e7
                    self.acalt = msg.alt / 1e3
                    self.achdg = msg.hdg / 1e2

                    #Find position relative to Ka-1 (ENU)
                    #Convert degrees to radians:
                    lat1 = self.kalat * pi / 180
                    lon1 = self.kalon * pi / 180
                    lat2 = self.aclat * pi / 180
                    lon2 = self.aclon * pi / 180
                    dlat = lat2 - lat1
                    dlong = lon2 - lon1

                    #Haversine formula
                    R = 6371000
                    a = sin(dlat / 2) * sin(dlat / 2) + cos(lat1) * cos(
                        lat2) * sin(dlong / 2.0) * sin(dlong / 2.0)
                    c = 2.0 * atan2(sqrt(a), sqrt(1 - a))
                    d = R * c
                    #distance
                    b = atan2(
                        sin(dlong) * cos(lat2),
                        cos(lat1) * sin(lat2) -
                        sin(lat1) * cos(lat2) * cos(dlong))

                    self.east = d * cos(
                        pi / 2 - b)  #x meters offset from Datum (ENU)
                    self.north = d * sin(
                        pi / 2 - b)  #y meters offset from Datum (ENU)
                    self.up = self.acalt - self.kaalt  #z meters offset from Datum (ENU), should never be negative lol

                    #write KML for plane
                    ns = '{http://www.opengis.net/kml/2.2}'
                    d = kml.Document(ns=ns, name='TOL GCS')
                    k = kml.KML(ns=ns)

                    #AIRCRAFT
                    p = kml.Placemark(ns,
                                      name='sUAS(' +
                                      '{0:.2f}'.format(self.east) + ',' +
                                      '{0:.2f}'.format(self.north) + ',' +
                                      '{0:.2f}'.format(self.up) + ')',
                                      styleUrl='sn_airports')
                    #AC Style
                    s = styles.Style(id='sn_airports')
                    IS = styles.IconStyle(
                        scale=1.2,
                        icon_href=
                        'http://maps.google.com/mapfiles/kml/shapes/airports.png',
                        heading=self.achdg)
                    s.append_style(IS)
                    #AC Geometry
                    geom = Geometry()
                    geom.geometry = Point(self.aclon, self.aclat, self.acalt)
                    geom.altitude_mode = 'absolute'
                    p.geometry = geom
                    d.append_style(s)
                    d.append(p)

                    #MGS
                    p = kml.Placemark(ns,
                                      name='MGS (0,0,0)',
                                      styleUrl='sn_truck')
                    s = styles.Style(id='sn_truck')
                    IS = styles.IconStyle(
                        scale=1.2,
                        icon_href=
                        'http://maps.google.com/mapfiles/kml/shapes/truck.png')
                    s.append_style(IS)
                    #MGS Geometry
                    geom = Geometry()
                    geom.geometry = Point(self.kalon, self.kalat, self.kaalt)
                    geom.altitude_mode = 'absolute'
                    p.geometry = geom
                    d.append_style(s)
                    d.append(p)

                    #WRITE
                    k.append(d)
                    kmlfile = open('TOL_GCS.kml', "w")
                    kmlfile.write(k.to_string(prettyprint=True))
                    kmlfile.close()
Esempio n. 18
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 = ""
Esempio n. 19
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
Esempio n. 20
0
def write_kml(ctx, no_styles, default_invisible, hierarchical):
    from fastkml import kml, styles
    from shapely.geometry import Point
    import pandas as pd

    df1 = get_airtable_as_dataframe(ctx.obj["config"],
                                    "categories",
                                    view="Grid view")
    df2 = df1.drop("places", axis=1).explode("parent")
    # TODO: need to repeatedly self-join until reach the root
    df3 = pd.merge(
        df2,
        df2,
        how="left",
        left_on="parent",
        right_on="airtable_record_id",
        suffixes=("", "_join"),
    )
    categories_df = df3
    df1 = get_airtable_as_dataframe(ctx.obj["config"], "places")
    df2 = df1.explode("primary_category")
    df3 = pd.merge(
        df2,
        categories_df,
        how="left",
        left_on="primary_category",
        right_on="airtable_record_id",
    )
    places_df = df3

    ns = "{http://www.opengis.net/kml/2.2}"
    k = kml.KML()

    # construct all nodes in hierarchy of categories
    folders = {
        "_root":
        kml.Document(
            ns=ns,
            id="myspots-document",
            name="myspots-document",
            description="myspots-document",
        ),
        "_uncat":
        kml.Folder(ns=ns, id="_uncat", name="uncategorized"),
    }
    for tup in categories_df.itertuples(index=False):
        folders[tup.category] = kml.Folder(ns=ns,
                                           id=tup.category,
                                           name=tup.category)

    # append folders into each other; works bc of mutability
    k.append(folders["_root"])
    folders["_root"].append(folders["_uncat"])
    for tup in categories_df.itertuples(index=False):
        parent = "_root" if pd.isna(tup.category_join) else tup.category_join
        container = parent if hierarchical else "_root"
        folders[container].append(folders[tup.category])

    # add places to approp folders
    for tup in places_df.itertuples(index=False):
        category = "_uncat" if pd.isna(tup.category) else tup.category
        style = None if no_styles else f"#style-{category}"
        p = kml.Placemark(ns=ns, id=str(tup.id), name=tup.name, styleUrl=style)
        p.geometry = Point(tup.longitude, tup.latitude)
        folders[category].append(p)

    # set default visibility
    visibility = 0 if default_invisible else 1
    for container in folders.values():
        container.visibility = visibility
    folders["_root"].visibility = 1

    # define icon styles for placemarks
    if not no_styles:
        doc = folders["_root"]
        doc.append_style(
            styles.Style(
                ns=ns,
                id="style-_uncat",
                styles=[
                    styles.IconStyle(
                        icon_href=
                        "https://raw.githubusercontent.com/google/material-design-icons/master/maps/1x_web/ic_place_black_48dp.png"
                    )
                ],
            ))
        for tup in categories_df.itertuples(index=False):
            if pd.isna(tup.icon_href):
                continue
            style = styles.Style(
                ns=ns,
                id=f"style-{tup.category}",
                styles=[styles.IconStyle(icon_href=tup.icon_href)],
            )
            doc.append_style(style)

    print(k.to_string(prettyprint=True))
Esempio n. 21
0
 def landingzones(self, data):
     self.description = ""
     icon = styles.IconStyle(icon_href="icons/heliport.png")
     self.icons.append(icon.icon_href)
     self.styles = styles.Style(styles=[icon])
     return self.styles, self.description
Esempio n. 22
0
 def hotsprings(self, data):
     self.description = ""
     icon = styles.IconStyle(icon_href="icons/mx_natural_hot_spring.png")
     self.icons.append(icon.icon_href)
     self.styles = styles.Style(styles=[icon])
     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)
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