def generate_kml(dates, sessions, GamitConfig): tqdm.write(' >> Generating KML for this run (see production directory)...') kml = simplekml.Kml() # define styles ICON = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' styles_stn = simplekml.StyleMap() styles_stn.normalstyle.iconstyle.icon.href = ICON styles_stn.normalstyle.iconstyle.color = 'ff00ff00' styles_stn.normalstyle.labelstyle.scale = 0 styles_stn.highlightstyle.iconstyle.icon.href = ICON styles_stn.highlightstyle.iconstyle.color = 'ff00ff00' styles_stn.highlightstyle.labelstyle.scale = 2 styles_tie = simplekml.StyleMap() styles_tie.normalstyle.iconstyle.icon.href = ICON styles_tie.normalstyle.iconstyle.color = 'ff0000ff' styles_tie.normalstyle.labelstyle.scale = 0 styles_tie.highlightstyle.iconstyle.icon.href = ICON styles_tie.highlightstyle.iconstyle.color = 'ff0000ff' styles_tie.highlightstyle.labelstyle.scale = 2 for date in tqdm(dates, ncols=80, disable=None): folder = kml.newfolder(name=date.yyyyddd()) sess = [] for session in sessions: if session.date == date: sess.append(session) if len(sess) > 1: for session in sess: folder_net = folder.newfolder(name=session.NetName) for stn in session.stations_dict: pt = folder_net.newpoint(**stn) if stn in session.tie_dict: pt.stylemap = styles_tie else: pt.stylemap = styles_stn elif len(sess) == 1: for stn in sess[0].stations_dict: pt = folder.newpoint(**stn) pt.stylemap = styles_stn if not os.path.exists('production'): os.makedirs('production') kml.savekmz('production/' + GamitConfig.NetworkConfig.network_id.lower() + '.kmz')
def generate_kml(self): # save this session as a kml kml = simplekml.Kml() ICON_SQUARE = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' # define styles styles_stn = simplekml.StyleMap() styles_stn.normalstyle.iconstyle.icon.href = ICON_SQUARE styles_stn.normalstyle.iconstyle.color = 'ff00ff00' styles_stn.normalstyle.iconstyle.scale = 4 styles_stn.normalstyle.labelstyle.scale = 0 styles_stn.highlightstyle.iconstyle.icon.href = ICON_SQUARE styles_stn.highlightstyle.iconstyle.color = 'ff00ff00' styles_stn.highlightstyle.iconstyle.scale = 5 styles_stn.highlightstyle.labelstyle.scale = 2 styles_tie = simplekml.StyleMap() styles_tie.normalstyle.iconstyle.icon.href = ICON_SQUARE styles_tie.normalstyle.iconstyle.color = 'ff0000ff' styles_tie.normalstyle.iconstyle.scale = 4 styles_tie.normalstyle.labelstyle.scale = 0 styles_tie.highlightstyle.iconstyle.icon.href = ICON_SQUARE styles_tie.highlightstyle.iconstyle.color = 'ff0000ff' styles_tie.highlightstyle.iconstyle.scale = 5 styles_tie.highlightstyle.labelstyle.scale = 3 folder_net = kml.newfolder(name=self.DirName) for stn in self.stations_dict + self.tie_dict: pt = folder_net.newpoint(**stn) if stn in self.tie_dict: pt.stylemap = styles_tie else: pt.stylemap = styles_stn kml.savekmz(os.path.join(self.solution_pwd, self.DirName) + '.kmz')
def create_styles(document, icon_text, scale_normal, scale_highlight, color): """Create styles/style maps for station KML. Args: document (Element): LXML KML Document element. """ style_normal = add_icon_style(document, icon_text, scale_normal, 0.0, color) style_highlight = add_icon_style(document, icon_text, scale_highlight, 1.0, color) style_map = skml.StyleMap(normalstyle=style_normal, highlightstyle=style_highlight) return style_map
def generate_kml(cnn, project, stations): stnlist = [s['NetworkCode'] + '.' + s['StationCode'] for s in stations] tqdm.write( ' >> Generating KML for this run (see production directory)...') kml = simplekml.Kml() rs = cnn.query_float( 'SELECT * FROM stations WHERE "NetworkCode" NOT LIKE \'?%\' ' 'ORDER BY "NetworkCode", "StationCode" ', as_dict=True) tqdm.write(' >> Adding stations in database') folder1 = kml.newfolder(name=project) folder2 = kml.newfolder(name='all stations') stylec = simplekml.StyleMap() stylec.normalstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' stylec.normalstyle.labelstyle.scale = 0 stylec.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' stylec.highlightstyle.labelstyle.scale = 2 styles_ok = simplekml.StyleMap() styles_ok.normalstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' styles_ok.normalstyle.iconstyle.color = 'ff00ff00' styles_ok.normalstyle.labelstyle.scale = 0 styles_ok.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' styles_ok.highlightstyle.iconstyle.color = 'ff00ff00' styles_ok.highlightstyle.labelstyle.scale = 2 styles_nok = simplekml.StyleMap() styles_nok.normalstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' styles_nok.normalstyle.iconstyle.color = 'ff0000ff' styles_nok.normalstyle.labelstyle.scale = 0 styles_nok.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' styles_nok.highlightstyle.iconstyle.color = 'ff0000ff' styles_nok.highlightstyle.labelstyle.scale = 2 for stn in tqdm(rs, ncols=80): count = cnn.query_float( 'SELECT count(*) as cc FROM rinex_proc WHERE "NetworkCode" = \'%s\' ' 'AND "StationCode" = \'%s\'' % (stn['NetworkCode'], stn['StationCode'])) ppp_s = cnn.query_float( 'SELECT count(*) as cc FROM ppp_soln WHERE "NetworkCode" = \'%s\' ' 'AND "StationCode" = \'%s\'' % (stn['NetworkCode'], stn['StationCode'])) stninfo = pyStationInfo.StationInfo(cnn, stn['NetworkCode'], stn['StationCode'], allow_empty=True) if count[0][0]: completion = '%.1f' % (float(ppp_s[0][0]) / float(count[0][0]) * 100) else: completion = 'NA' if stn['DateStart']: DS = '%.3f' % stn['DateStart'] DE = '%.3f' % stn['DateEnd'] else: DS = 'NA' DE = 'NA' if stn['NetworkCode'] + '.' + stn['StationCode'] in stnlist: folder = folder1 # mark the stations with less than 100 observations or with less than 60% completion (PPP) if count[0][0] >= 100 and (float(ppp_s[0][0]) / float(count[0][0]) * 100) >= 60.0: style = styles_ok else: style = styles_nok else: folder = folder2 style = stylec plt = plot_station_info_rinex(cnn, stn['NetworkCode'], stn['StationCode'], stninfo) pt = folder.newpoint(name=stn['NetworkCode'] + '.' + stn['StationCode'], coords=[(stn['lon'], stn['lat'])]) pt.stylemap = style pt.description = """<strong>%s -> %s</strong> RINEX count: %i PPP soln: %s%%<br><br> <strong>Station Information:</strong><br> <table width="880" cellpadding="0" cellspacing="0"> <tr> <td align="left" valign="top"> <p style="font-family: monospace; font-size: 8pt;">%s<br><br> <strong>Observation distribution:</strong><br> </p> <img src="data:image/png;base64, %s" alt="Observation information" /> </tr> </td> </table>""" % (DS, DE, count[0][0], completion, stninfo.return_stninfo_short().replace('\n', '<br>'), plt) if not os.path.exists('production'): os.makedirs('production') kml.savekmz('production/' + project + '.kmz')
''' Created on Feb 4, 2016 @author: Harald ''' import numpy as np import simplekml # To extract Google map files import matplotlib.pyplot as plt from geopy.distance import vincenty # To compute great circle distance from coordinates from mpl_toolkits.basemap import Basemap # my_proj = Proj(proj='utm',zone="31T", ellps='WGS84',units='m') # Prepare the Longitude/Latidude to Easting/Northing transformation style = simplekml.StyleMap( ) # Create a style map for highlight style and normal style FOR UNCORRECTED style.normalstyle.labelstyle.scale = 0 style.normalstyle.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/pushpin/red-pushpin.png" # grn style.highlightstyle.labelstyle.scale = 1 style.highlightstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/pushpin/blue-pushpin.png' ###################################################### class LoadData(object): ''' Loads and pre-processes the data. Contains methods for data Cleaning. ''' populations = [] # Contains table of IDs and populations blocks = [] # Contains table of all shared blocks coordinates = [] # Matrix saving the coordinates of a country countries_oi = []
def generate_kmz(kmz, stations, discarded, deformation_type='interseismic', units='mm/yr'): tqdm.write(' >> Generating KML (see production directory)...') kml = simplekml.Kml() folder1 = kml.newfolder(name=deformation_type) folder2 = kml.newfolder(name='discarded') # define styles styles_ok = simplekml.StyleMap() styles_nok = simplekml.StyleMap() for (s, icon_color, label_scale) in ((styles_ok.normalstyle, 'ff00ff00', 0), (styles_ok.highlightstyle, 'ff00ff00', 3), (styles_nok.normalstyle, 'ff0000ff', 0), (styles_nok.highlightstyle, 'ff0000ff', 3)): s.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_square.png' s.iconstyle.color = icon_color s.labelstyle.scale = label_scale for stn in tqdm(stations, ncols=160, disable=None, desc=' -- Included station list'): stn_id = stationID(stn) plot = plot_station_param(stn['NetworkCode'], stn['StationCode'], deformation_type, units, stn['n'], stn['e']) pt = folder1.newpoint(name=stn_id, coords=[(stn['lon'], stn['lat'])]) pt.stylemap = styles_ok pt.description = """<strong>NE (%s): %5.2f %5.2f [%s]</strong><br><br> <table width="880" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"> <strong>Parameters:</strong><br> <img src="data:image/png;base64, %s" alt="Observation information" height="300" width="300"/><br> <strong>Trajectory model:</strong><br> <img src="data:image/png;base64, %s" alt="Observation information" height="750" width="1100"/> </p> </tr> </td> </table> """ % (deformation_type, stn['n'] * 1000, stn['e'] * 1000, units, plot, stn['etm']) ls = folder1.newlinestring(name=stn_id) ls.coords = [ (stn['lon'], stn['lat']), (stn['lon'] + stn['e'] * 10, stn['lat'] + stn['n'] * 10 * np.cos(stn['lat'] * np.pi / 180)) ] ls.style.linestyle.width = 3 ls.style.linestyle.color = 'ff0000ff' for stn in tqdm(discarded, ncols=160, disable=None, desc=' -- Excluded station list'): stn_id = stationID(stn) plot = plot_station_param(stn['NetworkCode'], stn['StationCode'], deformation_type, units, stn['n'], stn['e']) pt = folder2.newpoint(name=stn_id, coords=[(stn['lon'], stn['lat'])]) pt.stylemap = styles_nok pt.description = """<strong>NE (%s): %5.2f %5.2f [%s]</strong><br><br> <table width="880" cellpadding="0" cellspacing="0"> <tr> <td align="center" valign="top"> <strong>Parameters:</strong><br> <img src="data:image/png;base64, %s" alt="Observation information" height="300" width="300"/><br> <strong>Trajectory model:</strong><br> <img src="data:image/png;base64, %s" alt="Observation information" height="750" width="1100"/> </p> </tr> </td> </table> """ % (deformation_type, stn['n'] * 1000, stn['e'] * 1000, units, plot, stn['etm']) ls = folder2.newlinestring(name=stn_id) ls.coords = [ (stn['lon'], stn['lat']), (stn['lon'] + stn['e'] * 10, stn['lat'] + stn['n'] * 10 * np.cos(stn['lat'] * np.pi / 180)) ] ls.style.linestyle.width = 3 ls.style.linestyle.color = 'ff0000ff' if not os.path.exists('production'): os.makedirs('production') tqdm.write(' >> Saving kmz...') kml.savekmz(kmz)
def to_kml_obj(self, type='LineString', time_ratio=1.0, color='ff0000ff', kml=None): """Format the object to a kml object Args: type (str or RepType): Multiple type can be used with | or '|' for string (default is 'LineString') time_ratio (float): The time ratio used only when type is 'Camera' (default is 1.0) color (str): The hexadecimal color with or without the alpha channel at the end (default is 'ff0000ff') kml (object): The kml object, if node a kml object is created (default is None) Returns: object : The kml object """ if isinstance(type, str): type = RepType(type).rep if len(color) == 6: color += 'ff' if kml is None: kml = simplekml.Kml() style = simplekml.Style() style.iconstyle.color = simplekml.Color.hex(color[:-2]) style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/open-diamond.png' style.linestyle.color = simplekml.Color.hexa(color) style.linestyle.width = 2 style.labelstyle.scale = 0 style_h = simplekml.Style() style_h.iconstyle.color = simplekml.Color.hex(color[:-2]) style_h.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/open-diamond.png' style_h.linestyle.color = simplekml.Color.hexa(color) style_h.linestyle.width = 2 style_h.labelstyle.scale = 1 stylemap = simplekml.StyleMap(style, style_h) if type & RepType.Camera: tour = kml.newgxtour(name='camera') play = tour.newgxplaylist() heading = 0 for i in range(0, len(self.data)): l = self.data[i] if i != len(self.data) - 1: l1 = self.data[i + 1] y = l1.geographic[0] - l.geographic[0] x = l1.geographic[1] - l.geographic[1] heading = math.degrees(math.atan2(y, x)) gxduration = (l1.time - l.time).total_seconds() * time_ratio camera = simplekml.Camera( latitude=l1.geographic[1], longitude=l1.geographic[0], altitude=l1.geographic[2], gxtimestamp=l.time.strftime("%Y-%m-%dT%H:%M:%S"), tilt=90, altitudemode='absolute', heading=heading) fly = play.newgxflyto(gxduration=gxduration, camera=camera) fly._kml['gx:flyToMode'] = 'smooth' if type & RepType.Track: times = [] coords = [] for l in self.data: coords.append(tuple(l.geographic)) times.append(l.time.strftime("%Y-%m-%dT%H:%M:%S")) trk = kml.newgxtrack() trk.newwhen(times) trk.newgxcoord(coords) trk.altitudemode = 'absolute' trk.style = style trk.extendeddata = simplekml.ExtendedData() for k, v in self.data[0].to_dict().items(): trk.extendeddata.newdata(k, v) if type & RepType.LineString: coords = [] for l in self.data: coords.append(tuple(l.geographic)) lin = kml.newlinestring(coords=coords, altitudemode='absolute') lin.timespan.begin = self.data[0].time.strftime( "%Y-%m-%dT%H:%M:%S") lin.timespan.end = self.data[-1].time.strftime("%Y-%m-%dT%H:%M:%S") lin.style = style if type & RepType.Points: for i in range(0, len(self.data)): l = self.data[i] if i % 100 == 0: l2 = self.list[i + 100] if i + 100 < len( self.data) else self.data[-1] name = l.time.strftime( "%H:%M:%S") + " - " + l2.time.strftime("%H:%M:%S") f = kml.newfolder(name=name) f.visibility = 1 if int(i / 50) == 0 else 0 pt = f.newpoint(name=l.time.strftime("%H:%M:%S"), coords=[tuple(l.geographic)], timestamp=simplekml.TimeStamp( l.time.strftime("%Y-%m-%dT%H:%M:%S")), altitudemode='absolute') pt.stylemap = stylemap pt.extendeddata = simplekml.ExtendedData() pt.visibility = 1 if int(i / 100) == 0 else 0 for k, v in l.to_dict().items(): pt.extendeddata.newdata(k, v) i += 1 return kml