def saveKmlFile(self,fileName,stopSignal,leftTurn,rightTurn): """ giving points separate images for better distinction between points """ kml=simplekml.Kml() styleRight = simplekml.Style() styleRight.labelstyle.color = simplekml.Color.red styleRight.labelstyle.scale = 2 styleRight.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/paddle/1.png" styleStop = simplekml.Style() styleStop.labelstyle.color = simplekml.Color.cyan styleStop.labelstyle.scale = 2 styleStop.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png" for dataIndex in range(len(stopSignal)): pnt = kml.newpoint(name='StopSignal: {0}'.format(dataIndex)) pnt.coords = [stopSignal[dataIndex][:2]] pnt.style = styleStop for dataIndex in range(len(leftTurn)): pnt = kml.newpoint(name='LeftTurn: {0}'.format(dataIndex)) pnt.coords = [leftTurn[dataIndex][:2]] for dataIndex in range(len(rightTurn)): pnt = kml.newpoint(name='RightTurn: {0}'.format(dataIndex)) pnt.coords = [rightTurn[dataIndex][:2]] pnt.style = styleRight kml.save(fileName)
def kml_export(self): kml = simplekml.Kml() point_style = simplekml.Style() point_style.labelstyle.color = simplekml.Color.blue point_style.labelstyle.scale = float(self.node_size.text()) point_style.iconstyle.icon.href = self.path_edit.text() for node in self.controller.view.nodes.values(): point = kml.newpoint(name=node.name, description=node.description) point.coords = node.coords point.style = point_style line_style = simplekml.Style() line_style.linestyle.color = simplekml.Color.red line_style.linestyle.width = self.line_width.text() for link in self.controller.view.links.values(): line = kml.newlinestring(name=link.name, description=link.description) line.coords = link.coords line.style = line_style filepath = QFileDialog.getSaveFileName( self, 'KML export', 'project', '.kml' ) selected_file = ''.join(filepath) kml.save(selected_file) self.close()
def kml_export(self, _): kml = simplekml.Kml() point_style = simplekml.Style() point_style.labelstyle.color = simplekml.Color.blue point_style.labelstyle.scale = float(self.node_size.text()) point_style.iconstyle.icon.href = self.path_edit.text() for node in self.network.nodes.values(): point = kml.newpoint(name=node.name, description=node.description) point.coords = [(node.longitude, node.latitude)] point.style = point_style line_style = simplekml.Style() line_style.linestyle.color = simplekml.Color.red line_style.linestyle.width = self.line_width.text() for link in self.network.pn['plink'].values(): line = kml.newlinestring(name=link.name, description=link.description) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = line_style filepath = QFileDialog.getSaveFileName(self, 'KML export', 'project', '.kml') selected_file = ''.join(filepath) kml.save(selected_file) self.close()
def GIStoKML(points, weights, name): weight_colors = { 4: '88ff3399', 5: '88ff3333', 6: '88ffff33', 7: '8833ff33', 8: '8833ffff', 9: '883399ff', 10: '883333ff' } kml = simplekml.Kml() for i in range(len(points)): pnt = kml.newpoint() #pnt.name = str(weights[i]) pnt.coords = [(points[i][0], points[i][1])] pntstyle = simplekml.Style() pntstyle.iconstyle.color = weight_colors[weights[i]] pntstyle.iconstyle.scale = 0.5 pntstyle.iconstyle.icon.href = "resources\\Solid_white.png" pnt.style = pntstyle kml.save("visualization/" + name + ".kml") print("Pilot location predictions available (see Google Earth)")
def create_contours(container, document): """Create a KML file containing MMI contour lines. Args: container (ShakeMapOutputContainer): Results of model.conf. datadir (str): Path to data directory where output KMZ will be written. document (Element): LXML KML Document element. """ # TODO - label contours? gx:labelVisibility doesn't seem to be working... folder = document.newfolder(name='Contours', visibility=0) mmi_line_styles = create_line_styles() pgm_line_style = skml.Style(linestyle=skml.LineStyle(width=3)) ic = skml.IconStyle(scale=0) component = list(container.getComponents())[0] imts = container.getIMTs(component) for imt in imts: line_strings = contour(container.getIMTGrids(imt, component), imt, DEFAULT_FILTER_SIZE, None) # make a folder for the contours imt_folder = folder.newfolder(name='%s Contours' % imt, visibility=0) for line_string in line_strings: if imt == 'MMI': val = '%.1f' % line_string['properties']['value'] else: val = '%g' % line_string['properties']['value'] line_list = [] for segment in line_string['geometry']['coordinates']: ctext = [] for vertex in segment: ctext.append((vertex[0], vertex[1])) ls = skml.LineString(coords=ctext) line_list.append(ls) lc = len(ctext) if lc < 10: dopts = [] elif (ctext[0][0] == ctext[-1][0] and ctext[0][1] == ctext[-1][1]): if lc < 30: dopts = [0, int(lc/2)] elif lc < 60: dopts = [0, int(lc/3), int(2*lc/3)] else: dopts = [0, int(lc/4), int(lc/2), int(3*lc/4)] else: dopts = [int(lc/2)] for i in dopts: p = imt_folder.newpoint(name=val, coords=[ctext[i]], visibility=0) p.style.iconstyle = ic mg = imt_folder.newmultigeometry(geometries=line_list, visibility=0, name="%s %s" % (imt, val)) if imt == 'MMI': mg.style = mmi_line_styles[val] else: mg.style = pgm_line_style
def draw_group(portals, tofile='group.kml'): import simplekml styles = [ 'http://s.binux.me/ingress/icons/smallSQGreenIcons/blank.PNG', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker1.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker2.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker3.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker4.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker5.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker6.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker7.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker8.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker9.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker10.png', 'http://s.binux.me/ingress/icons/smallSQGreenIcons/marker11.png', ] for key, value in enumerate(list(styles)): tmp = simplekml.Style() tmp.iconstyle.icon.href = value styles[key] = tmp kml = simplekml.Kml() for portal in portals: pnt = kml.newpoint(name=portal.guid, coords=[ (portal.lngE6 * 1e-6, portal.latE6 * 1e-6), ]) pnt.style = styles[portal.group] kml.save(tofile)
def make_kml(data_t, name='红色栅格', cc='ff0000ff', xiankuan=0, namea='grid_id', list_data='list_data', description='description'): style = simplekml.Style() #style.linestyle.color = simplekml.Color.changealphaint(150, cc) # 最终线条上色 style.polystyle.outline = xiankuan style.polystyle.color = simplekml.Color.changealphaint(125, cc) # 最终形状上色 lod1 = simplekml.Lod(minlodpixels=3, maxlodpixels=-1, minfadeextent=None, maxfadeextent=None) grid_red = kml.newfolder(name=name) for grid, list_data, description_str in zip(data_t[namea], data_t[list_data], data_t[description]): pol_r = grid_red.newpolygon(name=grid, outerboundaryis=list_data[0]) pol_r.description = description_str pol_r.altitudemode = simplekml.AltitudeMode.clamptoground lon_dd, lat_dd, lon1_dd, lat1_dd = list_data[1] latlonaltbox = simplekml.LatLonAltBox(east=lon_dd, north=lat_dd, south=lat1_dd, west=lon1_dd, minaltitude=None, maxaltitude=None, altitudemode=None) pol_r.region.latlonaltbox = latlonaltbox pol_r.region.lod = lod1 pol_r.style = style
def plotDay(dbc, imei, sYear, sMonth, sDay): startDate = datetime(sYear, sMonth, sDay) s = startDate.strftime('%y-%m-%d') + " 00:00:00" e = startDate.strftime('%y-%m-%d') + " 23:59:59" stmt = "select * from imei{0} where stamp >= \"{1}\" and stamp <= \"{2}\" and latgps is not null and longgps is not null order by stamp".format( imei, s, e) import simplekml kml = simplekml.Kml() # This results in a single styles fol = kml.newfolder(name="temp") style = simplekml.Style() style.labelstyle.color = simplekml.Color.red # Make the text red style.labelstyle.scale = 2 # Make the text twice as big style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' lastRow = "" lastRowTime = "" lastTrip = "1" for l in dbc.SQLSelectGenerator(stmt): if l is not None and abs(l[3]) > 1 and abs(l[4]) > 1: if lastRow == "": lastRow = l lastRowTime = l[0] elif ((l[0] - lastRowTime).total_seconds() >= 10): # only consider rows 10 seconds apart lastTrip = ("2" if lastTrip == "1" else "1") pnt = fol.newpoint(name=lastTrip, coords=[ (l[4], l[3]) ]) # KML requires long, lat pnt.style = style # (sharedstyle1 if lastTrip == "1" else sharedstyle2) lastRow = l lastRowTime = l[0] kml.save("/Users/tcarpent/Desktop/test16.kml")
def lines_kml(df, file_name, wkt_column=None, name_column=None, description_columns='all', exclude_columns=None, altitude=0, width=3, \ color=simplekml.Color.red, alpha=200, color_mode=simplekml.ColorMode.normal, label_visibility=False): """ Generate KML file with LineStrings/MultiLineStrings layer Parameters: ----------- df - pandas dataframe with WKT geometry; file_name - name of the KML file; wkt_column - column name of the dataframe with WKT geometry (if ommited, the last column will be taken); name_column - column name of the dataframe with names for the geometries (if ommited, the dataframe index will be taken); descrition_columns - list of column names that will be set in description balloon. If set 'all', all the columns but wkt_column and name_column will be taken; exclude_columns - list of column names that will be excluded from the description_columns; altitude - an altitude value for the geometries; width - width of the lines; color - a color for the geometries (read more: https://simplekml.readthedocs.io/en/latest/constants.html?#color) alpha - level of opacity from 0 to 255; color_mode - normal/random; label_visibility - whether labels will be visible or not; """ file_name = _process_file_name(file_name) description_columns = _process_description_columns(df, wkt_column, name_column, description_columns, exclude_columns) kml = simplekml.Kml() sharedstyle = simplekml.Style() sharedstyle = _process_color('LineString', sharedstyle, color_mode, color, alpha) sharedstyle.linestyle.width = width sharedstyle.linestyle.gxlabelvisibility = label_visibility for index, row in df.iterrows(): shape = wkt.loads(row[wkt_column]) if wkt_column else wkt.loads( row[-1]) name = str(row[name_column]) if name_column else str(index) description = _process_description(row, description_columns) logging.debug(f'shape_type: {shape.type}') if shape.type == 'LineString': outer_boundary, _ = _process_boundaries(dump_coords(shape), altitude) ls = kml.newlinestring( name=name, description=description, coords=outer_boundary, altitudemode=simplekml.AltitudeMode.relativetoground) ls.extrude = 1 ls.style = sharedstyle elif shape.type == 'MultiLineString': multils = kml.newmultigeometry(name=name, description=description) for coords_list in dump_coords(shape): outer_boundary, _ = _process_boundaries(coords_list, altitude) ls = multils.newlinestring( coords=outer_boundary, altitudemode=simplekml.AltitudeMode.relativetoground) ls.extrude = 1 multils.style = sharedstyle else: print(f'{name} has bad geometry') kml.save(file_name)
def points_kml(df, file_name, wkt_column=None, name_column=None, description_columns='all', exclude_columns=None, altitude=0, label_scale=0.8, \ color=simplekml.Color.white, alpha=255, color_mode=simplekml.ColorMode.normal, icon_href='http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png'): """ Generate KML file with Points/MultiPoints layer Parameters: ----------- df - pandas dataframe with WKT geometry; file_name - name of the KML file; wkt_column - column name of the dataframe with WKT geometry (if ommited, the last column will be taken); name_column - column name of the dataframe with names for the geometries (if ommited, the dataframe index will be taken); descrition_columns - list of column names that will be set in description balloon. If set 'all', all the columns but wkt_column and name_column will be taken; exclude_columns - list of column names that will be excluded from the description_columns; altitude - an altitude value for the geometries; label_scale - scale of the label; color - a color for the geometries (read more: https://simplekml.readthedocs.io/en/latest/constants.html?#color) alpha - level of opacity from 0 to 255; color_mode - normal/random; icon_href - href for the icons; """ file_name = _process_file_name(file_name) description_columns = _process_description_columns(df, wkt_column, name_column, description_columns, exclude_columns) kml = simplekml.Kml() sharedstyle = simplekml.Style() sharedstyle.iconstyle.icon.href = icon_href sharedstyle = _process_color('Point', sharedstyle, color_mode, color, alpha) sharedstyle.labelstyle.scale = label_scale for index, row in df.iterrows(): shape = wkt.loads(row[wkt_column]) if wkt_column else wkt.loads( row[-1]) name = str(row[name_column]) if name_column else str(index) description = _process_description(row, description_columns) logging.debug(f'shape_type: {shape.type}') if shape.type == 'Point': outer_boundary, _ = _process_boundaries(dump_coords(shape), altitude) pnt = kml.newpoint( name=name, description=description, coords=outer_boundary, altitudemode=simplekml.AltitudeMode.relativetoground) pnt.extrude = 1 pnt.style = sharedstyle elif shape.type == 'MultiPoint': multipnt = kml.newmultigeometry(name=name, description=description) for coords_list in dump_coords(shape): outer_boundary, _ = _process_boundaries(coords_list, altitude) pnt = multipnt.newpoint( coords=outer_boundary, altitudemode=simplekml.AltitudeMode.relativetoground) pnt.extrude = 1 multipnt.style = sharedstyle else: print(f'{name} has bad geometry') kml.save(file_name)
def AddLocations(kml_doc, locations, name, icon="paddle/red-circle"): style = simplekml.Style() style.labelstyle.color = simplekml.Color.black # Make the text black style.labelstyle.scale = 0.5 # Make the text half as big style.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/{icon}.png" for point in locations: pnt = kml_doc.newpoint(name=name) pnt.coords = [(point[0], point[1])] pnt.style = style
def main(argv): inputfile = '' # .json iconurl = 'https://www.iconfinder.com/icons/1249982/download/png/512' outputfile = '' # .kml try: opts, args = getopt.getopt(argv, "hi:u:", ["inputfile=", "iconurl="]) except getopt.GetoptError: print('wiglej2k.py -i <inputfile> -u <icon_url>') sys.exit(2) for opt, arg in opts: if opt == '-h': print('wiglej2k.py -i <inputfile> -u <iconurl>') sys.exit() elif opt in ("-i", "--inputfile"): inputfile = arg outputfile = str(arg).replace('json', 'kml') elif opt in ("-u", "--iconurl"): iconurl = arg if inputfile: with open(inputfile) as json_file: json_data = json.load(json_file) # Create KMl file kml_data = simplekml.Kml() kml_data.document.name = outputfile.replace('.kml', '') devices_collection = kml_data.newfolder(name="Devices") sharedstyle = simplekml.Style() sharedstyle.iconstyle.icon.href = iconurl count = 0 print(f'Parsing Devices:') for device in json_data["results"]: name = device['ssid'] latitude = device["trilat"] longitude = device["trilong"] description = '' for key, value in device.items(): description += f'{key}: {value}\n' print(f'{name} at {longitude}, {latitude}') pnt = devices_collection.newpoint(name=name, description=description, coords=[(longitude, latitude)]) pnt.style = sharedstyle count += 1 print(f'Added {count} devices to KML file {outputfile}.') kml_data.save(outputfile) else: print('Please select input file using -i <inputfile>') sys.exit()
def kml_point_styles(): kml_styles = [] for i in range(0, 9): ballon_color = point_iconcolor(i) icon_color = simplekml.Color.changealpha('99', ballon_color) kml_style_pos = simplekml.Style() kml_style_neg = simplekml.Style() kml_style_pol_50 = simplekml.Style() kml_style_pol_99 = simplekml.Style() kml_style_pos.labelstyle.scale = 0 kml_style_neg.labelstyle.scale = 0 kml_style_pos.iconstyle.scale = 1.5 kml_style_neg.iconstyle.scale = 1.5 kml_style_pos.balloonstyle.bgcolor = ballon_color kml_style_neg.balloonstyle.bgcolor = ballon_color kml_style_pol_50.linestyle.width = 3 kml_style_pol_50.linestyle.color = icon_color kml_style_pol_99.linestyle.width = 6 kml_style_pol_99.linestyle.color = icon_color kml_styles.append( [kml_style_neg, kml_style_pos, kml_style_pol_50, kml_style_pol_99]) kml_styles[0][0].iconstyle.icon.href = 'icons/bolt_white.png' kml_styles[0][1].iconstyle.icon.href = 'icons/bolt_white_up.png' kml_styles[1][0].iconstyle.icon.href = 'icons/bolt_purple.png' kml_styles[1][1].iconstyle.icon.href = 'icons/bolt_purple_up.png' kml_styles[2][0].iconstyle.icon.href = 'icons/bolt_blue.png' kml_styles[2][1].iconstyle.icon.href = 'icons/bolt_blue_up.png' kml_styles[3][0].iconstyle.icon.href = 'icons/bolt_gray.png' kml_styles[3][1].iconstyle.icon.href = 'icons/bolt_gray_up.png' kml_styles[4][0].iconstyle.icon.href = 'icons/bolt_yellowgreen.png' kml_styles[4][1].iconstyle.icon.href = 'icons/bolt_yellowgreen_up.png' kml_styles[5][0].iconstyle.icon.href = 'icons/bolt_yellow.png' kml_styles[5][1].iconstyle.icon.href = 'icons/bolt_yellow_up.png' kml_styles[6][0].iconstyle.icon.href = 'icons/bolt_orange.png' kml_styles[6][1].iconstyle.icon.href = 'icons/bolt_orange_up.png' kml_styles[7][0].iconstyle.icon.href = 'icons/bolt_coral.png' kml_styles[7][1].iconstyle.icon.href = 'icons/bolt_coral_up.png' kml_styles[8][0].iconstyle.icon.href = 'icons/bolt_red.png' kml_styles[8][1].iconstyle.icon.href = 'icons/bolt_red_up.png' return kml_styles
def AddPolygons(kml_doc, polygons, name): style = simplekml.Style() style.linestyle.color = simplekml.Color.black style.linestyle.width = 4 style.polystyle.outline = 1 style.polystyle.color = simplekml.Color.changealphaint( 0, simplekml.Color.red) for polygon in polygons: poly = kml_doc.newpolygon(outerboundaryis=polygon) poly.name = name poly.style = style
def create_line_styles(): """Create line styles for contour KML. Args: """ line_styles = {} cpalette = ColorPalette.fromPreset('mmi') for mmi in np.arange(0, 11, 0.5): pid = '%.1f' % mmi rgb = cpalette.getDataColor(mmi, color_format='hex') line_style = skml.LineStyle(color=flip_rgb(rgb), width=2.0) style = skml.Style(linestyle=line_style) line_styles[pid] = style return line_styles
def map_all_houses(data, filename): shared_style = simplekml.Style() shared_style.iconstyle.color = "ff0000ff" shared_style.labelstyle.scale = 0.5 shared_style.iconstyle.scale = 0.5 kml = simplekml.Kml() for task_index, task in enumerate(data): for house in task.info["houses"]: pnt = kml.newpoint(name=str(task_index)) pnt.coords = [(house["geometry"]["coordinates"][0], house["geometry"]["coordinates"][1])] pnt.style = shared_style kml.save(filename)
def __init__(self, controller): super().__init__() self.controller = controller self.setWindowTitle('Export to Google Earth') node_size = QLabel('Node label size') self.node_size = QLineEdit('1') line_width = QLabel('Line width') self.line_width = QLineEdit('1') export = QPushButton('Export to KML') export.clicked.connect(self.kml_export) self.styles = {} for subtype in node_subtype: point_style = simplekml.Style() point_style.labelstyle.color = simplekml.Color.blue path_icon = join(self.github_path, 'default_{}.gif'.format(subtype)) point_style.iconstyle.icon.href = path_icon self.styles[subtype] = point_style for subtype, cls in link_class.items(): line_style = simplekml.Style() # we convert the RGB color to a KML color, # i.e #RRGGBB to #AABBGGRR kml_color = "#ff{0:02x}{1:02x}{2:02x}".format(*cls.color[::-1]) line_style.linestyle.color = kml_color self.styles[subtype] = line_style layout = QGridLayout() layout.addWidget(node_size, 0, 0) layout.addWidget(self.node_size, 0, 1) layout.addWidget(line_width, 2, 0) layout.addWidget(self.line_width, 2, 1) layout.addWidget(export, 3, 0, 1, 2) self.setLayout(layout)
def export_kml(dataframe, filename): export_start_time = timeit.default_timer() print("Exporting collection to KML...", end="\r", flush=True) kml_data = dataframe[["Location", "Long", "Lat"]] kml_data["GECF"] = ( dataframe["Hole_ID"].apply(lambda x: "CSD Facility ID: " + str(x) if pd.notnull(x) else "") + dataframe["Original_ID"].apply(lambda x: " / FieldID: " + str(x) if pd.notnull(x) else "") + dataframe["Date"].apply(lambda x: " / Date: " + str(x) if pd.notnull(x) else "") + dataframe["Water_Depth"].apply(lambda x: " / Water Depth: " + str(x) + "m " if pd.notnull(x) else "") + dataframe[["mblf_T", "mblf_B"]].apply( lambda x: (" / Sediment Depth: " + (str(x[0]) if pd.notnull(x[0]) else "?") + "-" + (str(x[1]) if pd.notnull(x[1]) else "?") + "m") if (pd.notnull(x[0]) or pd.notnull(x[1])) else "", axis=1, ) + dataframe["Position"].apply(lambda x: " / Position: " + str(x) if pd.notnull(x) else "") + dataframe["IGSN"].apply(lambda x: " / IGSN: " + str(x) if pd.notnull(x) else "") + dataframe["Sample_Type"].apply(lambda x: " / Sample Type: " + str(x) if pd.notnull(x) else "")) kml = simplekml.Kml(name="CSD Core Collection") style = simplekml.Style() style.iconstyle.icon.href = ( "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png") style.iconstyle.scale = 1.2 style.iconstyle.color = "ff0000cc" for _, k in kml_data.iterrows(): if pd.notnull(k[1]) and pd.notnull(k[2]): pnt = kml.newpoint(name=k[0], coords=[(k[1], k[2])], description=k[3]) pnt.style = style kml.save(path=filename) print( f"Collection exported to {filename} in {round(timeit.default_timer()-export_start_time,2)} seconds.", flush=True, )
def map_points(data, filename): colors = ["ffff00ff", "ff00ffff", "ffffff00"] styles = [] for color in colors: style = simplekml.Style() style.iconstyle.color = color style.labelstyle.scale = 0.5 style.iconstyle.scale = 0.5 styles.append(style) kml = simplekml.Kml() for point in data: pnt = kml.newpoint(name=str(point[1])) pnt.coords = [(point[0])] pnt.style = styles[min(point[1] - 1, 2)] kml.save(filename)
def _basestyle(self, icondict=None): """ Return default KML icon style """ basestyle = skml.Style() basestyle.labelstyle.color = skml.Color.hex(self.colors['white']) basestyle.labelstyle.scale = 0.7 basestyle.iconstyle.icon.href = self.iconshapes['square'] basestyle.iconstyle.scale = 0.9 basestyle.iconstyle.color = skml.Color.hex('33FF33') # only show desciption in balloon basestyle.balloonstyle.text = r'$[description]' if icondict is not None: basestyle = self._changestyle(kmlstyle=basestyle, icondef=icondict) return basestyle
def kmlConvert(sitelist): """Converts data stored in the list of objects and converts to KML points. User specifies output file name, .kml file suffix is automatically appended. """ kml = simplekml.Kml() style_dict = { "Red": "http://maps.google.com/mapfiles/kml/paddle/red-blank.png", "Yellow": "http://maps.google.com/mapfiles/kml/paddle/ylw-blank.png", "Green": "http://maps.google.com/mapfiles/kml/paddle/grn-blank.png", "New": "http://maps.google.com/mapfiles/kml/paddle/blu-blank.png" } if args.internal: pass else: if tandemEdSite: site_style.iconstyle.icon.href = "http://www.tandembayarea.org/wp-content/uploads/2015/08/tandemEduMarker.png" else: site_style.iconstyle.icon.href = "http://www.tandembayarea.org/wp-content/uploads/2015/08/tandemPartMarker.png" for site in sitelist: pnt = kml.newpoint() site_style = simplekml.Style() pnt.name = site.name site_style.iconstyle.icon.href = style_dict[site.status] if args.internal: pnt.description = "%s \n\n %s" % (site.staffLead, site.address) else: if tandemEdSite: pnt.description = "For questions about this site please contact %s. \n %s" % ( site.staffLead, site.email) else: pnt.description = "A Tandem Partner Site" pnt.coords = [(site.longitude, site.latitude)] pnt.style = site_style outputfile = raw_input("Please select output filename: ") + ".kml" kml.save(outputfile) print "File saved!" return
def label_kml(label_fname, points): kml = simplekml.Kml() sharedstyle = simplekml.Style() sharedstyle.labelstyle.color = 'ff0000ff' # Red sharedstyle.labelstyle.scale = 0.7 sharedstyle.labelstyle.color = 'ff663333' sharedstyle.iconstyle.scale = 0 # Icon thrice as big for point in points: # print point pnt = kml.newpoint(name=point['label']) pnt.coords = [point['coordinates']] pnt.style = sharedstyle kml.save(label_fname)
def create_epicenter(container, document): """Place a star marker at earthquake epicenter. Args: container (ShakeMapOutputContainer): Results of model.conf. document (Element): LXML KML Document element. """ icon = skml.Icon(href=EPICENTER_URL) iconstyle = skml.IconStyle(icon=icon) style = skml.Style(iconstyle=iconstyle) info = container.getMetadata() lon = info['input']['event_information']['longitude'] lat = info['input']['event_information']['latitude'] point = document.newpoint(name='Earthquake Epicenter', coords=[(lon, lat)], visibility=0) point.style = style
def write_kml( positions, kml_path, kml_thumbnail_size, image_src, image_name, image_style=None ): kml = simplekml.Kml() sharedstyle = simplekml.Style() sharedstyle.balloonstyle.text = "$[description]" for latlon, image in positions: css_style = "" if image_style: css_style = f'style="{image_style(image)}"' desc = f"""<![CDATA[ {image_name(image)}</br></br> <img src="{image_src(image)}" width="{kml_thumbnail_size}" {css_style} /> ]]>""" pnt = kml.newpoint(description=desc, coords=[latlon[::-1]]) pnt.style = sharedstyle try: kml.save(kml_path) except Exception: logger.exception(f"Unable to save KML to {kml_path}")
def plotPoints(pointList, kml, color, size, prefix, lineSkip): numPoints = len(pointList) / 3 style = simplekml.Style() if color == 'blue': style.labelstyle.color = simplekml.Color.blue elif color == 'red': style.labelstyle.color = simplekml.Color.red elif color == 'green': style.labelstyle.color = simplekml.Color.green elif color == 'yellow': style.labelstyle.color = simplekml.Color.yellow else: style.labelstyle.color = simplekml.Color.white if size == 'small': style.labelstyle.scale = 0 style.iconstyle.scale = 0.7 style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/open-diamond.png' style.iconstyle.color = style.labelstyle.color elif size == 'tiny': style.labelstyle.scale = 0 style.iconstyle.scale = 0.5 style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/placemark_circle.png' style.iconstyle.color = style.labelstyle.color # All other words trigger the default # Plot each point counter = 0 for i in range(0, numPoints, lineSkip): point = kml.newpoint(name=prefix+str(i), coords=[(pointList[i*3], pointList[i*3+1], pointList[i*3+2])], \ gxaltitudemode= simplekml.AltitudeMode.absolute) point.style = style point.extrude = 1 counter = counter + 1 print 'Added ' + str(counter) + ' KML points' return kml
def add_icon_style(document, icon_text, icon_scale, label_scale, color): """Create Style tag around Icon in KML. Args: document (Element): LXML KML Document element. icon_text (str): The name of the icon file. icon_scale (float): The icon scale. label_scale (float): The label scale. """ icon = skml.Icon(href=icon_text) icon_style = skml.IconStyle(scale="%.1f" % icon_scale, color=color, icon=icon) label_style = skml.LabelStyle(scale='%.1f' % label_scale) # list_style = skml.ListStyle(listitemtype='checkHideChildren') balloon_style = skml.BalloonStyle(text='$[description]') # style = skml.Style(iconstyle=icon_style, labelstyle=label_style, # liststyle=list_style, balloonstyle=balloon_style) style = skml.Style(iconstyle=icon_style, labelstyle=label_style, balloonstyle=balloon_style) return style
def do_everything(bounding_box): t0 = time.time() # retrieve coordinates from query query_string = request.args bbox = query_string['BBOX'] bbox_list = bbox.split(',') west = float(bbox_list[0]) south = float(bbox_list[1]) east = float(bbox_list[2]) north = float(bbox_list[3]) bbox_polygon = Polygon(((west, south), (east, south), (east, north), (west, north), (west, south))) t1 = time.time() logger.debug("Retrieve bbox values from get request...") logger.debug("Time: " + str(t1 - t0)) # Get the point_data_tuple surveys from the database that are within the bbox sdmc = get_dataset_metadata_cache(db_engine=DATABASE_ENGINE, debug=False) point_data_tuple_list = sdmc.search_dataset_distributions( keyword_list=[ 'AUS', 'ground digital data', 'gravity', 'geophysical survey', 'points' ], protocol='opendap', ll_ur_coords=[[west, south], [east, north]]) logger.debug([[west, south], [east, north]]) t2 = time.time() logger.debug("Retrieve point_data_tuple strings from database...") logger.debug("Time: " + str(t2 - t1)) kml = simplekml.Kml() # ---------------------------------------------------------------------------------------------------------------- # High zoom: show points rather than polygons. if east - west < MAX_BOX_WIDTH_FOR_POINTS: if len(point_data_tuple_list) > 0: # set point style point_style = simplekml.Style() point_style.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/paddle/grn-blank.png" point_style.iconstyle.scale = 0.7 point_style.labelstyle.scale = 0 # removes the label netcdf_file_folder = kml.newfolder( name="Ground Gravity Survey Observations") for point_data_tuple in point_data_tuple_list: logger.debug("Building NETCDF: " + str(point_data_tuple[2])) netcdf2kml_obj = netcdf2kml.NetCDF2kmlConverter( point_data_tuple) t3 = time.time() logger.debug( "set style and create netcdf2kmlconverter instance of point_data_tuple file ..." ) logger.debug("Time: " + str(t3 - t2)) #logger.debug("Number of points in file: " + str(netcdf2kml_obj.npu.point_count)) if netcdf2kml_obj.npu.point_count > 0: ta = time.time() netcdf2kml_obj.build_points(netcdf_file_folder, bbox_list, point_style) tb = time.time() logger.debug("do the things time: " + str(tb - ta)) logger.debug("Build the point ...") dataset_points_region = netcdf2kml_obj.build_region( 100, -1, 200, 800) netcdf_file_folder.region = dataset_points_region netcdf2kml_obj.netcdf_dataset.close( ) # file must be closed after use to avoid errors when accessed again. del netcdf2kml_obj # Delete netcdf2kml_obj to removenetcdf2kml_obj.npu cache file t4 = time.time() return str(netcdf_file_folder) else: logger.debug("No surveys in view") # ---------------------------------------------------------------------------------------------------------------- # Low zoom: show polygons and not points. else: t_polygon_1 = time.time() # set polygon style polygon_style = simplekml.Style() polygon_style.polystyle.color = 'B30000ff' # Transparent red #polygon_style.polystyle.color = 'ff4545' polygon_style.polystyle.outline = 1 polygon_style_background = simplekml.Style() polygon_style_background.polystyle.color = '7FFFFFFF' # Transparent white polygon_style_background.polystyle.outline = 1 if len(point_data_tuple_list) > 0: netcdf_file_folder = kml.newfolder( name="Ground Gravity Survey Extents") for point_data_tuple in point_data_tuple_list: logger.debug("point_data_tuple: " + str(point_data_tuple)) netcdf2kml_obj = netcdf2kml.NetCDF2kmlConverter( point_data_tuple) t_polygon_2 = time.time() logger.debug( "set style and create netcdf2kmlconverter instance from point_data_tuple for polygon ..." ) logger.debug("Time: " + str(t_polygon_2 - t_polygon_1)) try: survey_polygon = wkt.loads(point_data_tuple[3]) except Exception as e: #print(e) continue # Skip this polygon if survey_polygon.intersects(bbox_polygon): #if survey_polygon.within(bbox_polygon): #if not survey_polygon.contains(bbox_polygon): #if survey_polygon.centroid.within(bbox_polygon): #if not survey_polygon.contains(bbox_polygon) and survey_polygon.centroid.within(bbox_polygon): polygon_folder = netcdf2kml_obj.build_polygon( netcdf_file_folder, polygon_style) else: polygon_folder = netcdf2kml_obj.build_polygon( netcdf_file_folder, polygon_style, False) dataset_polygon_region = netcdf2kml_obj.build_region( -1, -1, 200, 800) polygon_folder.region = dataset_polygon_region # insert built polygon region into polygon folder #else: # for surveys with 1 or 2 points. Can't make a polygon. Still save the points? # logger.debug("not enough points") # neww = kml.save("test_polygon.kml") return str(netcdf_file_folder) else: empty_folder = kml.newfolder(name="no points in view") return str(empty_folder)
""".format(txRecord['AuthorizationNumber'], txRecord['Frequency'], txRecord['Latitude'], txRecord['Longitude']) cursor.execute(findRxQuery) rxRecords = cursor.fetchall() link['rx'] = rxRecords ptpLinks.append(link) cnx.close() print("Finding RX licenses done, starting KML generation") kml = simplekml.Kml() bellStyle = simplekml.Style() bellStyle.linestyle.width = 2 bellStyle.linestyle.color = 'ffff0000' # Blue rogersStyle = simplekml.Style() rogersStyle.linestyle.width = 2 rogersStyle.linestyle.color = 'ff0000ff' # Red telusStyle = simplekml.Style() telusStyle.linestyle.width = 2 telusStyle.linestyle.color = 'ff3CFF14' # Green xplornetStyle = simplekml.Style() xplornetStyle.linestyle.width = 2 xplornetStyle.linestyle.color = 'FF1478A0' # Brown
def track_to_kml(hdf_path, kti_list, kpv_list, approach_list, plot_altitude=None, dest_path=None): ''' Plot results of process_flight onto a KML track. :param flight_attrs: List of Flight Attributes :type flight_attrs: list :param plot_altitude: Name of Altitude parameter to use in KML :type plot_altitude: String ''' one_hz = Parameter() kml = simplekml.Kml() with hdf_file(hdf_path) as hdf: # Latitude param, Longitude param, track name, colour coord_params = ( { 'lat': 'Latitude Smoothed', 'lon': 'Longitude Smoothed', 'track': 'Smoothed', 'colour': 'ff7fff7f' }, { 'lat': 'Latitude Prepared', 'lon': 'Longitude Prepared', 'track': 'Prepared', 'colour': 'A11EB3' }, { 'lat': 'Latitude', 'lon': 'Longitude', 'track': 'Recorded', 'colour': 'ff0000ff' }, { 'lat': 'Latitude (Coarse)', 'lon': 'Longitude (Coarse)', 'track': 'Coarse', 'colour': 'ff0000ff' }, ) altitude_absolute_params = ('Altitude QNH', 'Altitude STD', 'Altitude AAL') altitude_relative_params = ('Altitude Radio', ) # Check latitude and longitude pair exist. if not any(c['lat'] in hdf and c['lon'] in hdf for c in coord_params): logger.error( "Cannot write track as coordinate paarmeters not in hdf") return False # Choose best altitude parameter if not specified. if not plot_altitude: altitude_params = itertools.chain(altitude_absolute_params, altitude_relative_params) try: plot_altitude = next(p for p in altitude_params if p in hdf) except StopIteration: logger.warning("Disabling altitude on KML plot as it is " "unavailable.") # Get altitude param from hdf. if plot_altitude: alt = derived_param_from_hdf( hdf[plot_altitude]).get_aligned(one_hz) alt.array = repair_mask(alt.array, frequency=alt.frequency, repair_duration=None) / METRES_TO_FEET else: alt = None if plot_altitude in altitude_absolute_params: altitude_mode = simplekml.constants.AltitudeMode.absolute elif plot_altitude in altitude_relative_params: altitude_mode = simplekml.constants.AltitudeMode.relativetoground else: altitude_mode = simplekml.constants.AltitudeMode.clamptoground ## Get best latitude and longitude parameters. best_lat = None best_lon = None for coord_config in coord_params: lat_name = coord_config['lat'] lon_name = coord_config['lon'] if not lat_name in hdf or not lon_name in hdf: continue lat = hdf[lat_name] lon = hdf[lon_name] best = not best_lat or not best_lon add_track(kml, coord_config['track'], lat, lon, coord_config['colour'], alt_param=alt, alt_mode=altitude_mode, visible=best) add_track(kml, coord_config['track'] + ' On Ground', lat, lon, coord_config['colour'], visible=best) if best: best_lat = derived_param_from_hdf(lat).get_aligned(one_hz) best_lon = derived_param_from_hdf(lon).get_aligned(one_hz) # Add KTIs. for kti in kti_list: kti_point_values = {'name': kti.name} if kti.name in SKIP_KTIS: continue altitude = alt.at(kti.index) if plot_altitude else None kti_point_values['altitudemode'] = altitude_mode if altitude: kti_point_values['coords'] = ((kti.longitude, kti.latitude, altitude), ) else: kti_point_values['coords'] = ((kti.longitude, kti.latitude), ) kml.newpoint(**kti_point_values) # Add KPVs. for kpv in kpv_list: # Trap kpvs with invalid latitude or longitude data (normally happens # at the start of the data where accelerometer offsets are declared, # and this avoids casting kpvs into the Atlantic. kpv_lat = best_lat.at(kpv.index) kpv_lon = best_lon.at(kpv.index) if kpv_lat == None or kpv_lon == None or \ (kpv_lat == 0.0 and kpv_lon == 0.0): continue if kpv.name in SKIP_KPVS: continue style = simplekml.Style() style.iconstyle.color = simplekml.Color.red kpv_point_values = {'name': '%s (%.3f)' % (kpv.name, kpv.value)} altitude = alt.at(kpv.index) if plot_altitude else None kpv_point_values['altitudemode'] = altitude_mode if altitude: kpv_point_values['coords'] = ((kpv_lon, kpv_lat, altitude), ) else: kpv_point_values['coords'] = ((kpv_lon, kpv_lat), ) pnt = kml.newpoint(**kpv_point_values) pnt.style = style # Add approach centre lines. for app in approach_list: try: draw_centreline(kml, app.runway) except: pass if not dest_path: dest_path = hdf_path + ".kml" kml.save(dest_path) return dest_path
def kml_create(lightnings_df): kml_style_red = simplekml.Style() kml_style_red.iconstyle.icon.href = 'icons/bolt_red.png' kml_style_red.iconstyle.scale = 2 kml_style_red.labelstyle.scale = 0 ## kml_style_red.iconstyle.color = simplekml.Color.red kml_style_yellow = simplekml.Style() kml_style_yellow.iconstyle.icon.href = 'icons/bolt_yellow.png' kml_style_yellow.iconstyle.scale = 1.5 kml_style_yellow.labelstyle.scale = 0 #kml_style_yellow.iconstyle.color = simplekml.Color.yellow kml_style_highlighted = simplekml.Style() kml_style_highlighted.iconstyle.icon.href = 'icons/bolt_orange.png' kml_style_highlighted.iconstyle.scale = 2.5 kml_style_highlighted.labelstyle.scale = 1.5 #kml_style_highlighted.iconstyle.color = simplekml.Color.orange ellipse_style_red = simplekml.Style() ellipse_style_red.linestyle.width = 3 ellipse_style_red.linestyle.color = simplekml.Color.red ellipse_style_red.polystyle.fill = 0 ellipse_style_red.polystyle.outline = 1 ellipse_style_yellow = simplekml.Style() ellipse_style_yellow.linestyle.width = 2 ellipse_style_yellow.linestyle.color = simplekml.Color.yellow ellipse_style_yellow.polystyle.fill = 0 ellipse_style_yellow.polystyle.outline = 1 kml = simplekml.Kml() ellipses_fol = kml.newfolder(name=f'Elipses de error') with_timestamp = (max(lightnings_df.Fecha_Hora) - min( lightnings_df.Fecha_Hora)) > datetime.timedelta(minutes=60) for _, row in lightnings_df.iterrows(): point = kml.newpoint(name=row['Fecha_Hora'].strftime("%H:%M:%S")) point.coords = [(row['Longitud'], row['Latitud'])] point.stylemap.highlightstyle = kml_style_highlighted if row['Category']: point.stylemap.normalstyle = kml_style_red else: point.stylemap.normalstyle = kml_style_yellow if with_timestamp: point.timestamp.when = row['Fecha_Hora'].replace( second=0, microsecond=0).isoformat() else: ellipse = ellipses_fol.newpolygon( name=row['Fecha_Hora'].strftime("%H:%M:%S")) ellipse.outerboundaryis = ellipse_polygon(row['Longitud'], row['Latitud'], row["Error_Mayor"], row["Error_Minor"], row["Error_Azimuth"], probability=2) ellipse.visibility = 0 if row['Category']: ellipse.style = ellipse_style_red else: ellipse.style = ellipse_style_yellow point.description = f'''<style> .styled-table {{ border-collapse: collapse; margin: 25px 0; font-size: 0.9em; font-family: sans-serif; min-width: 200px; }} .styled-table tbody tr {{ border-bottom: 1px solid #dddddd; }} </style> <body> <TABLE class="styled-table"> <TR><TH>Hora</TH> <TD>{row['Fecha_Hora'].strftime("%Y/%m/%d %H:%M:%S")}</TD></TR> <TR><TH>Intensidad</TH> <TD>{row["Intensity"]}kA</TD></TR> <TR><TH>Num. sensores</TH> <TD>{row["Sensors_Involved"]} </TD></TR> </TABLE> </body>''' return kml