def get_kml(self, app_session): kml = Kml() node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon( href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png'))) node_folder = kml.newfolder(name="Nodes") for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in app_session.data_set.query(Node).all()]: p.style = node_style node_index = {} node_counter = 0 arc_folder = kml.newfolder(name="Arcs") for flow in app_session.data_set.query(NetworkFlow).all(): if not node_index.get(flow.orig_name, None): node_index.update({flow.orig_name: node_counter}) node_counter += 1 arc_style = Style( linestyle=LineStyle(color=MapFlowOutput.get_cycled_hex_colour(node_index.get(flow.orig_name)), width=4)) l = arc_folder.newlinestring(name="arc", coords=[(flow.orig_node.longitude, flow.orig_node.latitude), (flow.dest_node.longitude, flow.dest_node.latitude)]) l.style = arc_style return kml.kml()
def get_kml(self, app_session): kml = Kml() person_style = Style(iconstyle=IconStyle( scale=0.8, icon=Icon( href= 'https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png' ))) people_folder = kml.newfolder(name="Potential Facilities") for p in [ people_folder.newpoint(name=person.name, coords=[(person.longitude, person.latitude)]) for person in app_session.data_set.query(Person).all() ]: p.style = person_style place_style = Style(iconstyle=IconStyle( scale=0.4, icon=Icon( href= 'https://maps.google.com/mapfiles/kml/paddle/red-circle-lv.png' ))) places_folder = kml.newfolder(name="Places") for p in [ places_folder.newpoint(name=place.name, coords=[(place.longitude, place.latitude)]) for place in app_session.data_set.query(Place).all() ]: p.style = place_style return kml.kml()
def get_kml(self, app_session): kml = Kml() # set up map points for Plants plants_folder = kml.newfolder(name="Potential Facilities") plants_points = [ plants_folder.newpoint(name=plant.name, coords=[(plant.longitude, plant.latitude)]) for plant in app_session.data_set.query(Plant).all() ] for p in plants_points: p.style = plant_style # set up map points for Shops shops_folder = kml.newfolder(name="Shops") shops_points = [ shops_folder.newpoint(name=shop.name, coords=[(shop.longitude, shop.latitude)]) for shop in app_session.data_set.query(Shop).all() ] for p in shops_points: p.style = shop_style return kml.kml()
def get_kml(self, app_session): kml = Kml() def LongLat(l): return (l.longitude, l.latitude) mylocstyle = Style(iconstyle=IconStyle( scale=0.8, icon=Icon( href= 'https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png' ))) LocsFolder = kml.newfolder(name="Locations") locations = app_session.data_set.query(Location).all() if len(locations) < 100: for p in [ LocsFolder.newpoint(name=loc.name, coords=[LongLat(loc)]) for loc in locations ]: p.style = mylocstyle mylinestyle = Style(linestyle=LineStyle(color='FF0000FF', width=4)) PathsFolder = kml.newfolder(name="Paths") paths = app_session.data_set.query(Path).all() if len(paths) < 100: for path in [ PathsFolder.newlinestring(name='path', coords=[ LongLat(l.start_location), LongLat(l.end_location) ]) for l in paths ]: path.style = mylinestyle mylinestyle = Style(linestyle=LineStyle(color='FF00FF00', width=4)) PathsFolder = kml.newfolder(name="Paths") paths = app_session.data_set.query(OutputPath).all() if len(paths) < 100: for path in [ PathsFolder.newlinestring(name='path', coords=[ LongLat(l.start_location), LongLat(l.end_location) ]) for l in paths ]: path.style = mylinestyle return kml.kml()
def graph_kml( env, fname="graph.kml", icon="http://maps.google.com/mapfiles/kml/shapes/donut.png", size=0.5, scale=0.5, width=5, ): """Create a kml visualisation of graph. Env variable needs to contain graph.""" # create a kml file containing the visualisation kml = Kml() fol = kml.newfolder(name="Vessels") shared_style = Style() shared_style.labelstyle.color = "ffffffff" # White shared_style.labelstyle.scale = size shared_style.iconstyle.color = "ffffffff" # White shared_style.iconstyle.scale = scale shared_style.iconstyle.icon.href = icon shared_style.linestyle.color = "ff0055ff" # Red shared_style.linestyle.width = width nodes = list(env.FG.nodes) # each timestep will be represented as a single point for log_index, value in enumerate(list(env.FG.nodes)[0 : -1 - 1]): pnt = fol.newpoint( name="", coords=[ ( nx.get_node_attributes(env.FG, "Geometry")[nodes[log_index]].x, nx.get_node_attributes(env.FG, "Geometry")[nodes[log_index]].y, ) ], ) pnt.style = shared_style edges = list(env.FG.edges) for log_index, value in enumerate(list(env.FG.edges)[0 : -1 - 1]): lne = fol.newlinestring( name="", coords=[ ( nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][0]].x, nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][0]].y, ), ( nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][1]].x, nx.get_node_attributes(env.FG, "Geometry")[edges[log_index][1]].y, ), ], ) lne.style = shared_style kml.save(fname)
def get_kml(self, app_session): kml = Kml() node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon( href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png'))) node_folder = kml.newfolder(name="Nodes") for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in app_session.data_set.query(Node).all()]: p.style = node_style arc_folder = kml.newfolder(name="Arcs") Arcs = app_session.data_set.query(Arc).all() for arc in Arcs: arc_style = Style(linestyle=LineStyle(color=MapArcInput.get_cycled_hex_colour(Arcs.index(arc)), width=4)) l = arc_folder.newlinestring(name="arc", coords=[(arc.orig_node.longitude, arc.orig_node.latitude), (arc.dest_node.longitude, arc.dest_node.latitude)]) l.style = arc_style return kml.kml()
def get_kml(self, app_session): kml = Kml() node_style = Style(iconstyle=IconStyle(scale=0.8, icon=Icon( href='https://maps.google.com/mapfiles/kml/paddle/blu-circle-lv.png'))) node_folder = kml.newfolder(name="Nodes") for p in [node_folder.newpoint(name=n.name, coords=[(n.longitude, n.latitude)]) for n in app_session.data_set.query(Node).all()]: p.style = node_style return kml.kml()
def serialize_list_point_lon_lat_index_as_kml(list_points, name='point', color=Color.green, scale=1, abolutefilepath ='points.kml'): kml = Kml() point_folder = kml.newfolder(name='points') for point in list_points: lon_lat = [point[0],point[1]] index = point[2] pnt_0 = point_folder.newpoint() pnt_0.name = str(index) pnt_0.coords = [lon_lat] pnt_0.labelstyle.color=color pnt_0.style.labelstyle.scale = scale pnt_0.style.iconstyle.icon.href='http://maps.google.com/mapfiles/kml/paddle/grn-circle-lv.png' kml.save(abolutefilepath)
def fCreateLineKML(zoznam, n, f): kml = Kml() fol = kml.newfolder(name="spojnica") At = zoznam[0][3] L = zoznam[0][0] B = zoznam[0][1] for i in range(1, len(zoznam)): At = zoznam[i][3] if At == 0: continue for data in f: if At == data[1]: farba = data[0] Ld = zoznam[i][0] Bd = zoznam[i][1] pnt = fol.newlinestring(name="{0}".format(At), coords=[(L, B), (Ld, Bd)]) pnt.style.linestyle.color = farba kml.save("data/vystup/kruh/" + n + "spojnica.kml")
def convert(self, output): output_filename = '{}.{}'.format(KMLParser.RESULT_FILENAME, output) if output in ['kml', 'kmz']: #check if value is in a list kmlinstance = Kml() folder = kmlinstance.newfolder() folder.name = "My Places" for name, lat, lon in self.content:#tuples can be decomposed in a for loop. This is the same as "for (x,y,z) in self.content" or "for t in self.content" and then using t[0] etc. folder.newpoint(name=name, coords=[(lat,lon)]) kmlinstance.save( output_filename ) elif output in ['terminal', 'txt']: newcontent = [ '%s\t->\t%.4f %.4f'%(name, float(lat),float(lon)) for name, lat, lon in self.content ] #list comprehensions rock!! if output == 'txt': f = open(output_filename, 'w') f.write( '\n'.join(newcontent) ) f.close() elif output is 'terminal': print '\n'.join(newcontent) elif output == 'json': newcontent = [ {'name': name, 'coordinates': {'latitude':lat, 'longitude':lon} } for name, lat, lon in self.content ] f = open(output_filename, 'w') json.dump(newcontent, f, indent=2) f.close()
def fCreatePointKML(zoznam, n): kml = Kml() fol = kml.newfolder(name="kruh") At = zoznam[0][3] L = zoznam[0][0] B = zoznam[0][1] pnt = fol.newpoint(name="{0}".format(At), coords=[(L, B)]) pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/ylw-blank-lv.png' pnt.style.iconstyle.scale = 0.5 pnt.style.labelstyle.color = 'ffffffff' pnt.style.labelstyle.scale = 1 for i in range(1, len(zoznam)): At = zoznam[i][3] if At == 0: continue L = zoznam[i][0] B = zoznam[i][1] pnt = fol.newpoint(name="{0}".format(At), coords=[(L, B)]) pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/grn-blank-lv.png' pnt.style.iconstyle.scale = 0.4 pnt.style.labelstyle.color = 'ffffffff' pnt.style.labelstyle.scale = 1 kml.save("data/vystup/kruh/" + n + "kruh.kml")
def process(options): # create a .kml file kml = Kml() lat_pattern = "N39 45.%s66" lon_pattern = "W89 45.8%s%s" # create a new KML folder f0 = kml.newfolder(name="Solution Locations") # try all values of C for C in range(10): # try all values of I for I in range(10): # use a middle-guess for J J = 5 # compute a location dmlat = lat_pattern % C dmlon = lon_pattern % (I, J) lat = convert(dmlat) lon = convert(dmlon) # make up a name name = "P_C%s_I%s_J%s" % (C, I, J) # insert a new waypoint f0.newpoint(name=name, coords=[(lon, lat)]) if True or options.circles: draw_circles(kml, options.circles) kml.save("omega.kml")
def plot_map(a, stadata, fechas, anch=80, ms=3, sel='all', op=''): print( "NUEVA VERSIÓN, AHORA EN LA CARPETA DE TRABAJO SE GUARDA ARCHIVO KMZ CON LOCALIZACION(ES)" ) print( "QUIZAS (LO MAS PROBABLE) SEA NECESARIO INSTALAR LIBRERIA KML, EN EL PROMPT EJECUTAR" ) print("conda install -c conda-forge simplekml") print("SI SALE EL ERROR 'NO MODULE NAME SIMPLEKML'\n\n\n\n\n") kml = Kml() #a = pd.DataFrame.from_dict(a, orient='index') #stadata = pd.DataFrame.from_dict(stadata, orient='index') if op == 'REAV': zona = a.iloc[0]['zona_id'] cod = a.iloc[0]['vol_cod'] latv = float(a.iloc[0]['vol_lat']) lonv = float(a.iloc[0]['vol_lon']) nref = float(a.iloc[0]['vol_alt']) t_deg = anch / (111.320 * cos(radians(latv))) ancho = haversine(float(lonv), float(latv), float(lonv) + float(t_deg), float(latv)) ancho = int(round(ancho)) factorlatlon = param_volcan(zona, cod)[0] londelta = float(t_deg / 2) latdelta = float(londelta * factorlatlon) tiev, late, lone, profe, ML = [], [], [], [], [] for i in range(0, len(a)): tiev.append(a.iloc[0]['ev_tipoev']) late.append(a.iloc[0]['ev_lat']) lone.append(a.iloc[0]['ev_lon']) profe.append(a.iloc[0]['ev_prof']) ML.append(a.iloc[0]['ev_ml']) else: zona = a.zona_id cod = a.vol_cod latv = float(a.vol_lat) lonv = float(a.vol_lon) nref = a.vol_alt tiev = a.ev_tipoev late = a.ev_lat lone = a.ev_lon profe = a.ev_prof ML = a.ev_ml t_deg = anch / (111.320 * cos(radians(latv[0]))) ancho = haversine(float(lonv[0]), float(latv[0]), float(lonv[0]) + float(t_deg), float(latv[0])) ancho = int(round(ancho)) factorlatlon = param_volcan(zona[0], cod[0])[0] londelta = float(t_deg / 2) latdelta = float(londelta * factorlatlon) gs = gen_fig_topo() x, y = 'prof', 'lat' #Latitud vs prof (x,y,datos_x,datos_y,nref) subfig_prof(x, y, profe, late, nref, gs, latv, lonv, latdelta, londelta, tiev, 'hypo', ms, ML) gs, m = gen_fig_map(nref, latv, lonv, latdelta, londelta, zona, cod, gs, factorlatlon, ancho / 4, t_deg, op, fechas) if op != 'reav': #plot_esta(m,stadata,kml,ms) print(sel) from matplotlib.lines import Line2D legend_elements = [ Line2D([], [], marker='o', color='k', label='ML=1', lw=0, markersize=ms * 1, markerfacecolor='none'), Line2D([], [], marker='o', color='k', label='ML=2', lw=0, markersize=ms * 2, markerfacecolor='none'), Line2D([], [], marker='o', color='k', label='ML=3', lw=0, markersize=ms * 3, markerfacecolor='none'), Line2D([], [], marker='^', color='k', label='Est. Sísmica', lw=0, markerfacecolor='k', markersize=ms * 2) ] if sel == 'all': legend_elements.extend([ Line2D([], [], marker='o', color='k', label='VT', lw=0, markerfacecolor='r', markersize=ms * 3), Line2D([], [], marker='o', color='k', label='LP', lw=0, markerfacecolor='y', markersize=ms * 3) ]) else: if sel == 'VT': color = 'r' elif sel == 'LP': color = 'y' legend_elements.extend([ Line2D([], [], marker='o', color='k', label=sel, lw=0, markerfacecolor=color, markersize=ms * 3), Line2D([], [], marker='o', color='none', label='', lw=0, markerfacecolor='none', markersize=ms * 3) ]) #legend = plt.gca().legend(ncol=2,title='Leyenda',handles=legend_elements, loc='lower right', fontsize=ms*3) #plt.setp(legend.get_title(),fontsize=ms*3) plot_sis(late, lone, latv, lonv, latdelta, londelta, m, tiev, 'hypo', ms, ML) #MAPA x, y = 'lon', 'prof' subfig_prof(x, y, lone, profe, nref, gs, latv, lonv, latdelta, londelta, tiev, 'hypo', ms, ML) path = save_fig_vol(zona, cod) #evs = pd.DataFrame.from_dict(a).T fol01 = kml.newfolder(name='ML 0-1') fol12 = kml.newfolder(name='ML 1-2') fol23 = kml.newfolder(name='ML 2-3') fol39 = kml.newfolder(name='ML >3') for index, row in a.iterrows(): if row['ev_ml'] > 0 and row['ev_ml'] < 1.1: pnt = fol01.newpoint() elif row['ev_ml'] > 1 and row['ev_ml'] < 2.1: pnt = fol12.newpoint() elif row['ev_ml'] > 2 and row['ev_ml'] < 3.1: pnt = fol23.newpoint() elif row['ev_ml'] > 3: pnt = fol39.newpoint() if row['ev_tipoev'] == 'VT': pnt.style.iconstyle.color = 'ff0000ff' elif row['ev_tipoev'] == 'LP': pnt.style.iconstyle.color = 'ff00ffff' elif row['ev_tipoev'] == 'VD': pnt.style.iconstyle.color = 'ffff00ff' lat = row['ev_lat'] lon = row['ev_lon'] pnt.coords = [(lon, lat)] pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png' kml.savekmz(str(zona) + str(cod) + ".kmz") return path
def get_kml(self, app_session): kml = Kml() flows = app_session.data_set.query(Flow).all() # set up points for Plants used plants_used = list(set([flow.plant for flow in flows])) plants_used_folder = kml.newfolder(name="Facilities Chosen") plants_used_points = [ plants_used_folder.newpoint(name=plant.name, coords=[(plant.longitude, plant.latitude)]) for plant in plants_used ] for p in plants_used_points: p.style = plant_style # set up points for Plants not used plants_not_used_folder = kml.newfolder(name="Facilities Not Chosen") plants_not_used_points = [ plants_not_used_folder.newpoint(name=plant.name, coords=[(plant.longitude, plant.latitude)]) for plant in app_session.data_set.query(Plant).all() if plant not in plants_used ] for p in plants_not_used_points: p.style = plant_style for plant in plants_used: catchment_folder = kml.newfolder(name="Catchment for " + plant.name) catchment_points = [ catchment_folder.newpoint(name=shop.name, coords=[(shop.longitude, shop.latitude)]) for shop in [flow.shop for flow in plant.flows] ] for point in catchment_points: point.style = shop_style plant_location = catchment_folder.newpoint(name=plant.name, coords=[ (plant.longitude, plant.latitude) ]) plant_location.style = plant_style catchment_line_style = Style( linestyle=LineStyle(color=KMLMapOutput.get_cycled_hex_colour( plants_used.index(plant)), width=4)) catchment_lines = [ catchment_folder.newlinestring( name='From: %s<br>To: %s<br>Flow: %s' % (flow.plant_name, flow.shop_name, flow.volume), coords=[(flow.plant.longitude, flow.plant.latitude), (flow.shop.longitude, flow.shop.latitude)]) for flow in plant.flows ] for l in catchment_lines: l.style = catchment_line_style return kml.kml()
# Attach the model to the track trk.model = model_car trk.model.link.href = car_dae # Add all the information to the track trk.newwhen(car["when"]) trk.newgxcoord(car["coord"]) # Style of the Track trk.iconstyle.icon.href = "" trk.labelstyle.scale = 1 trk.linestyle.width = 4 trk.linestyle.color = '7fff0000' # Add GPS measurement marker fol = kml.newfolder(name="GPS Measurements") sharedstyle = Style() sharedstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' for m in range(len(latitude)): if GPS[m]: pnt = fol.newpoint(coords = [(longitude[m],latitude[m])]) pnt.style = sharedstyle # Saving kml.savekmz("Extended-Kalman-Filter-CTRA.kmz") # In[33]: print('Exported KMZ File for Google Earth')
""" Demonstrates three types of MultiGeometry (point, linestring and polygon) using the South Africa coordinate system as a basis. """ import os from simplekml import Kml, Color kml = Kml(name="MultiGeometry", open=1) # Creating MultiGeometry multipnt = kml.newmultigeometry(name="MultiPoint") # SA (Hartebeeshoek94) Grid Intersections multilin = kml.newmultigeometry(name="MultiLine") # SA (Hartebeeshoek94) Lo. Lines multipolodd = kml.newmultigeometry(name="MultiPolyOdd") # SA (Hartebeeshoek94) Lo. Regions multipoleven = kml.newmultigeometry(name="MultiPolyEven") # SA (Hartebeeshoek94) Second Lo. Regions for styling lolabels = kml.newfolder(name="Lo. Regions") # The labels of the Lo. Regions (17-33) # Create all the coordinates to populate the South African Coordinate System polycoordsodd = [] polycoordseven = [] firstrun = True for x in range(16, 36, 2): linecoords = [] if x < 34: # Label region lo = lolabels.newpoint(name=str(x+1), coords=[(x+1, -29)]) lo.iconstyle.icon.href = "" # Remove the icons for y in range(-35, -19, 2): multipnt.newpoint(coords=[(x, y)]) linecoords.append((x,y)) multilin.newlinestring(coords=linecoords) polycoordsodd.append(linecoords) if len(polycoordsodd) == 2:
import numpy as np import zipfile import crust1 from os import remove from simplekml import Kml, Style # Create an instance of Kml kml = Kml(open=1) fol = kml.newfolder(name="Crust 1.0") def convert_to_html(model): """ Takes a model instance and produces an HTML table that represents the results in a nice way for us to look at. Parameters ---------- model : dict Dictionary of layers and their properties as a list in the form of [Vp, Vs, rho, thickness, top] Returns ------- html_str : str Nicely formatted HTML table of the model results. """ layer_labels = ["Water", "Ice", "Upper_Seds.", "Middle_Seds.", "Lower_Seds.", "Upper_Crust", "Middle_Crust", "Lower_Crust", "Mantle"]
def site_kml( env, sites, fname="site_development.kml", icon="http://maps.google.com/mapfiles/kml/shapes/square.png", size=1, scale=3, stepsize=120, ): """Create a kml visualisation of vessels. Env variable needs to contain epoch to enable conversion of simulation time to real time. Vessels need logs that contain geometries in lat, lon as a function of time.""" # create a kml file containing the visualisation kml = Kml() fol = kml.newfolder(name="Sites") # each timestep will be represented as a single point for site in sites: for log_index, value in enumerate(site.log["Timestamp"][:-1]): style = Style() style.labelstyle.color = "ffffffff" # White style.labelstyle.scale = 1 style.iconstyle.color = "ff00ffff" # Yellow style.iconstyle.scale = scale * (site.log["Value"][log_index] / site.container.capacity) style.iconstyle.icon.href = icon begin = site.log["Timestamp"][log_index] end = site.log["Timestamp"][log_index + 1] pnt = fol.newpoint( name=site.name, coords=[( site.log["Geometry"][log_index].x, site.log["Geometry"][log_index].y, )], ) pnt.timespan.begin = begin.isoformat() pnt.timespan.end = end.isoformat() pnt.style = style # include last point as well style = Style() style.labelstyle.color = "ffffffff" # White style.labelstyle.scale = 1 style.iconstyle.color = "ff00ffff" # Yellow style.iconstyle.scale = scale * (site.log["Value"][log_index + 1] / site.container.capacity) style.iconstyle.icon.href = icon begin = site.log["Timestamp"][log_index + 1] # end = site.log["Timestamp"][log_index + 1] pnt = fol.newpoint( name=site.name, coords=[( site.log["Geometry"][log_index + 1].x, site.log["Geometry"][log_index + 1].y, )], ) pnt.timespan.begin = begin.isoformat() # pnt.timespan.end = end.isoformat() pnt.style = style kml.save(fname)
def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, figs, tim, colorbar=None, **kw): """TODO: LatLon bbox, list of figs, optional colorbar figure, and several simplekml kw...""" # Get data from parameter or use defaults altitude = kw.pop('altitude', 2e7) roll = kw.pop('roll', 0) tilt = kw.pop('tilt', 0) altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground) author = kw.pop('author', 'ocefpaf') rotation = kw.pop('rotation', 0) description = kw.pop('description', 'Matplotlib figure') name = kw.pop('name', 'overlay') gxaltitudemode = kw.pop('gxaltitudemode', 'clampToSeaFloor') visibility = kw.pop('visibility', 1) kmzfile = kw.pop('kmzfile', 'overlay.kmz') # Create kml kml = Kml() kml.document.name = name kml.document.description = description kml.document.atomauthor = author # Create camera camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]), longitude=np.mean([urcrnrlon, llcrnrlon]), altitude=altitude, roll=roll, tilt=tilt, altitudemode=altitudemode) kml.document.camera = camera # Create folder in the kml to hold the overlays folder = kml.newfolder(name = name) folder.name = name # Create overlays draworder = 0 for fig in figs: # NOTE: Overlays are limited to the same bbox. begin = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(tim[draworder])) end = time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(tim[draworder+1])) # Place all in the folder ground = folder.newgroundoverlay(name=name + " at " + begin) print (ground.name) ground.draworder = draworder ground.visibility = visibility ground.gxaltitudemode = gxaltitudemode ground.timespan.begin = begin ground.timespan.end = end ground.icon.href = 'files\\' + fig # this below is not working for some reason #ground.icon.RefreshMode = RefreshMode.oninterval #ground.icon.refreshInterval = 300 #ground.icon.viewRefreshMode = ViewRefreshMode.onstop #ground.icon.viewRefreshTime = 2 #ground.icon.viewBoundScale = 0.85 ground.latlonbox.rotation = rotation ground.latlonbox.east = llcrnrlon ground.latlonbox.south = llcrnrlat ground.latlonbox.north = urcrnrlat ground.latlonbox.west = urcrnrlon draworder += 1 # Create Colorbar if colorbar: # Options for colorbar are hard-coded (to avoid a big mess). screen = kml.newscreenoverlay(name='Legend') screen.icon.href = colorbar screen.overlayxy = OverlayXY(x=0, y=0, xunits=Units.fraction, yunits=Units.fraction) screen.screenxy = ScreenXY(x=0.015, y=0.075, xunits=Units.fraction, yunits=Units.fraction) screen.rotationXY = RotationXY(x=0.5, y=0.5, xunits=Units.fraction, yunits=Units.fraction) screen.size.x = 0 screen.size.y = 0 screen.size.xunits = Units.fraction screen.size.yunits = Units.fraction screen.visibility = 1 kml.save(ourfile + '.kml') kml.savekmz(kmzfile) return kml
sides.polystyle.color = self.color sides.altitudemode = AltitudeMode.absolute return desc = "készítette: Baka Dávid\n\ LHHH - Műegyetemi Sportrepülő Egyesület\n\ https://github.com/bakadave/KMLcreator\n\ [email protected]" if __name__ == "__main__": kml = Kml(name="test") kml.document = Folder(name="Hungary airspaces", open=1, description=desc) ctr = kml.newfolder(name="Budapest CTR") BCTR = Airspace(airspaceName_1, splitCoordinates(line_1), altStr2Num(topAlt_1), altStr2Num(bottomAlt_1), clss_1) BCTR.generatePoly(ctr) print(BCTR.name + " polygon generated") tma = kml.newfolder(name="Budapest TMA") ENR2_1 = "C:/Users/bakad/OneDrive/Desktop/AIRAC/2020-06-18-AIRAC/html/eAIP/LH-ENR-2.1-en-HU.html" tmaPhrase = "BUDAPEST TMA" TMA = parseTMA(ENR2_1, tmaPhrase, 3) for arsp in TMA: box = Airspace(arsp[0], splitCoordinates(arsp[1]), altStr2Num(arsp[2]), altStr2Num(arsp[3]), arsp[4]) fld = tma.newfolder(name=box.name, open=False)
def export(request, ref): mosaic_obj = Mosaic.objects.get(ref=ref) if not mosaic_obj.big_preview_url: imgByteArr = mosaic_obj.generatePreview(100) response = cloudinary.uploader.upload(imgByteArr, public_id=mosaic_obj.ref + '_100') mosaic_obj.big_preview_url = response['url'] mosaic_obj.save() kml = Kml() normalstyle = Style() normalstyle.iconstyle.color = 'ffd18802' normalstyle.iconstyle.scale = 1 normalstyle.iconstyle.icon.href = 'http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png' normalstyle.iconstyle.hotspot.x = 32 normalstyle.iconstyle.hotspot.xunits = 'pixels' normalstyle.iconstyle.hotspot.y = 64 normalstyle.iconstyle.hotspot.xunits = 'insetPixels' normalstyle.labelstyle.scale = 0 normalstyle.linestyle.color = 'ffd18802' normalstyle.linestyle.width = 5 highlightstyle = Style() highlightstyle.iconstyle.color = 'ffd18802' highlightstyle.iconstyle.scale = 1 highlightstyle.iconstyle.icon.href = 'http://www.gstatic.com/mapspro/images/stock/503-wht-blank_maps.png' highlightstyle.iconstyle.hotspot.x = 32 highlightstyle.iconstyle.hotspot.xunits = 'pixels' highlightstyle.iconstyle.hotspot.y = 64 highlightstyle.iconstyle.hotspot.xunits = 'insetPixels' highlightstyle.labelstyle.scale = 1 stylemap = StyleMap(normalstyle, highlightstyle) folder = kml.newfolder(name=mosaic_obj.title) for mission_obj in mosaic_obj.missions.all().order_by('order'): multipnt = folder.newmultigeometry(name=mission_obj.title) multipnt.stylemap = stylemap multipnt.description = '<![CDATA[<img src="' + mosaic_obj.big_preview_url + '" height="200" width="auto" />' + mission_obj.desc + ']]>' multipnt.extendeddata.newdata('MIM link', 'https://www.myingressmosaics.com/mosaic/' + mosaic_obj.ref) pnt = multipnt.newpoint() linestring = multipnt.newlinestring(name=mission_obj.title) actions = '' coordinates = [] jsondata = json.loads(mission_obj.data) if len(jsondata) > 9: index = 0 for portal in jsondata[9]: index += 1 lat = 0.0 lng = 0.0 if portal[5]: if portal[5][0] == 'f': lat = portal[5][1] / 1000000.0 lng = portal[5][2] / 1000000.0 if portal[5][0] == 'p': lat = portal[5][2] / 1000000.0 lng = portal[5][3] / 1000000.0 actions += str(index) + '.' if portal[2] == 'Unavailable': actions += 'Unavailable ' else: if portal[4] == 1: actions += 'hack ' if portal[4] == 2: actions += 'capture ' if portal[4] == 7: actions += 'view ' if portal[4] == 8: actions += 'passphrase ' if lat and lng: coordinates.append((lng, lat)) if lat and lng and index==1: pnt.coords = [(lng, lat)] linestring.coords = coordinates multipnt.extendeddata.newdata('actions', actions) response = HttpResponse(kml.kml()) response['Content-Disposition'] = 'attachment; filename="' + mosaic_obj.title + '.kml"' response['Content-Type'] = 'application/kml' return response
import os from simplekml import Kml, ColorMode, AltitudeMode, Style # Create an instance of Kml kml = Kml(name="Basics", open=1) # Create a new document doc = kml.newdocument(name="A Document") # Create a nested document nestdoc = doc.newdocument() nestdoc.name = "A Nested Document" nestdoc.description = "\u2013 This is the nested document's description with unicode." # Create a new folder at the top level fol = kml.newfolder() fol.name = "A Folder" fol.description = "Description of a folder" # Some sub folders fol = fol.newfolder(name='A Nested Folder', description="Description of a nested folder") fol = kml.newfolder(name='Point Tests', description="Description of Point Folder") # A folder containing points with style stpnt = fol.newpoint(name="Cape Town Stadium", description='The Cape Town stadium built for the 2010 world cup soccer.', coords=[(18.411102, -33.903486)]) vapnt = fol.newpoint() vapnt.name = "V&A Waterfront" vapnt.description = "The V&A Waterfront in Cape Town" vapnt.coords = [(18.418699, -33.907080)] vapnt.style.labelstyle.color = 'ff0000ff' vapnt.labelstyle.scale = 2
def flask_get_kml_feed(): """ Return KML with RS telemetry """ kml = Kml() kml.resetidcounter() kml.document.name = "Track" kml.document.open = 1 # Station Placemark pnt = kml.newpoint( name="Ground Station", altitudemode=AltitudeMode.absolute, description="AutoRX Ground Station", ) pnt.open = 1 pnt.iconstyle.icon.href = flask.request.host_url + "static/img/antenna-green.png" pnt.coords = [ ( autorx.config.global_config["station_lon"], autorx.config.global_config["station_lat"], autorx.config.global_config["station_alt"], ) ] for rs_id in flask_telemetry_store: try: coordinates = [] for tp in flask_telemetry_store[rs_id]["track"].track_history: coordinates.append((tp[2], tp[1], tp[3])) rs_data = """\ {type}/{subtype} Frequency: {freq} Altitude: {alt:.1f} m Heading: {heading:.1f} degrees Ground Speed: {vel_h:.2f} m/s Ascent Rate: {vel_v:.2} m/s Temperature: {temp:.1f} C Humidity: {humidity:.1f} % Pressure: {pressure:.1f} hPa """ if flask_telemetry_store[rs_id]["latest_telem"]["vel_v"] > -5: icon = flask.request.host_url + "static/img/balloon-green.png" else: icon = flask.request.host_url + "static/img/parachute-green.png" # Add folder fol = kml.newfolder(name=rs_id) # HAB Placemark pnt = fol.newpoint( name=rs_id, altitudemode=AltitudeMode.absolute, description=rs_data.format( **flask_telemetry_store[rs_id]["latest_telem"] ), ) pnt.iconstyle.icon.href = icon pnt.coords = [ ( flask_telemetry_store[rs_id]["latest_telem"]["lon"], flask_telemetry_store[rs_id]["latest_telem"]["lat"], flask_telemetry_store[rs_id]["latest_telem"]["alt"], ) ] linestring = fol.newlinestring(name="Track") linestring.coords = coordinates linestring.altitudemode = AltitudeMode.absolute linestring.extrude = 1 linestring.stylemap.normalstyle.linestyle.color = "ff03bafc" linestring.stylemap.highlightstyle.linestyle.color = "ff03bafc" linestring.stylemap.normalstyle.polystyle.color = "AA03bafc" linestring.stylemap.highlightstyle.polystyle.color = "CC03bafc" # Add LOS line linestring = fol.newlinestring(name="LOS") linestring.altitudemode = AltitudeMode.absolute linestring.coords = [ ( autorx.config.global_config["station_lon"], autorx.config.global_config["station_lat"], autorx.config.global_config["station_alt"], ), ( flask_telemetry_store[rs_id]["latest_telem"]["lon"], flask_telemetry_store[rs_id]["latest_telem"]["lat"], flask_telemetry_store[rs_id]["latest_telem"]["alt"], ), ] except Exception as e: logging.error( "KML - Could not parse data from RS %s - %s" % (rs_id, str(e)) ) return ( re.sub("<Document.*>", "<Document>", kml.kml()), 200, {"content-type": "application/vnd.google-earth.kml+xml"}, )
if os.path.isfile(output_filename): #Check if the Output file already exists print("Output-File already exists! Do you want to overwrite?") i = input() while i not in ["YES", "NO"]: i = input("YES or NO?") if i == "NO": quit() print("STARTING") print('The File {} will be "translated" into {}'.format( input_filename, output_filename)) fileinput = open(input_filename, 'r') kml = Kml(name="Tracks", open=1) fol = kml.newfolder(name='Track') trk = fol.newgxtrack(name='EFB GPS Mouse') trk.altitudemode = AltitudeMode.absolute read = {} number = 0 for line in fileinput: read[number] = str(line.split()) number = number + 1 for i in range(len(read)): # parse DATA----------------------------------------------------------- if i > 4: # first line of log have no information JepLogLine = read[i].split("'") # for part in range (28): #debug
# Attach the model to the track trk.model = model_car trk.model.link.href = car_dae # Add all the information to the track trk.newwhen(car["when"]) trk.newgxcoord(car["coord"]) # Style of the Track trk.iconstyle.icon.href = "" trk.labelstyle.scale = 1 trk.linestyle.width = 4 trk.linestyle.color = '7fff0000' # Add GPS measurement marker fol = kml.newfolder(name="GPS Measurements") sharedstyle = Style() sharedstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' for m in range(len(latitude)): if GPS[m]: pnt = fol.newpoint(coords = [(longitude[m],latitude[m])]) pnt.style = sharedstyle # Saving #kml.save("Extended-Kalman-Filter-CTRV.kml") kml.savekmz("Extended-Kalman-Filter-CTRV.kmz") # <codecell> print('Exported KMZ File for Google Earth')
def vessel_kml( env, vessels, fname="vessel_movements.kml", icon="http://maps.google.com/mapfiles/kml/shapes/sailing.png", size=1, scale=1, stepsize=120, ): """Create a kml visualisation of vessels. Env variable needs to contain epoch to enable conversion of simulation time to real time. Vessels need logs that contain geometries in lat, lon as a function of time.""" # create a kml file containing the visualisation kml = Kml() fol = kml.newfolder(name="Vessels") shared_style = Style() shared_style.labelstyle.color = "ffffffff" # White shared_style.labelstyle.scale = size shared_style.iconstyle.color = "ffff0000" # Blue shared_style.iconstyle.scale = scale shared_style.iconstyle.icon.href = icon # each timestep will be represented as a single point for vessel in vessels: geom_x = [] geom_y = [] for geom in vessel.log["Geometry"]: geom_x.append(geom.x) geom_y.append(geom.y) vessel.log["Geometry - x"] = geom_x vessel.log["Geometry - y"] = geom_y time_stamp_min = min(vessel.log["Timestamp"]).timestamp() time_stamp_max = max(vessel.log["Timestamp"]).timestamp() steps = int(np.floor((time_stamp_max - time_stamp_min) / stepsize)) timestamps_t = np.linspace(time_stamp_min, time_stamp_max, steps) times = [] for t in vessel.log["Timestamp"]: times.append(t.timestamp()) vessel.log["timestamps_t"] = timestamps_t vessel.log["timestamps_x"] = np.interp(timestamps_t, times, vessel.log["Geometry - x"]) vessel.log["timestamps_y"] = np.interp(timestamps_t, times, vessel.log["Geometry - y"]) for log_index, value in enumerate(vessel.log["timestamps_t"][:-1]): begin = datetime.datetime.fromtimestamp( vessel.log["timestamps_t"][log_index]) end = datetime.datetime.fromtimestamp( vessel.log["timestamps_t"][log_index + 1]) pnt = fol.newpoint( name=vessel.name, coords=[( vessel.log["timestamps_x"][log_index], vessel.log["timestamps_y"][log_index], )], ) pnt.timespan.begin = begin.isoformat() pnt.timespan.end = end.isoformat() pnt.style = shared_style # include last point as well begin = datetime.datetime.fromtimestamp( vessel.log["timestamps_t"][log_index + 1]) # end = datetime.datetime.fromtimestamp(vessel.log["timestamps_t"][log_index + 1]) pnt = fol.newpoint( name=vessel.name, coords=[( vessel.log["timestamps_x"][log_index + 1], vessel.log["timestamps_y"][log_index + 1], )], ) pnt.timespan.begin = begin.isoformat() # pnt.timespan.end = end.isoformat() pnt.style = shared_style kml.save(fname)