def gen_kml_tac(data, district_name, path_result): # 创建谷歌图层文件 list_tac = sorted(data['跟踪区'].astype(int).drop_duplicates().tolist()) for tac in list_tac: df_tac_data = data[data['跟踪区'] == tac] list_cluster = sorted( df_tac_data['tac_cluster'].drop_duplicates().tolist()) for cluster in list_cluster: df_cluster_data = df_tac_data[df_tac_data['tac_cluster'] == cluster] # 如果是tac中的第一个cluster,则创建一个tac文件夹,并添加第一个cluster节点 if cluster == list_cluster[0]: kml_tac = KML.Folder(KML.name("跟踪区=" + str(tac)), gen_kml_cluster(df_cluster_data, cluster)) # 添加后面的cluster else: kml_tac.append(gen_kml_cluster(df_cluster_data, cluster)) # 如果是第一个tac,创建kml文件,并添加第一个tac节点 if tac == list_tac[0]: kml_doc = KML.Document(KML.name(district_name), kml_tac) else: kml_doc.append(kml_tac) etree_doc = etree.tostring(etree.ElementTree(kml_doc), pretty_print=True) # with open(path_result + district_name + '.kml', 'wb') as fp: fp.write(etree_doc)
def generate_kml_output(): start = time.time() #TIME KEEPER d = dict() f= open("urls.txt","r") count = 0 #STATUS BAR bar = progressbar.ProgressBar(maxval=65, \ widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.Percentage()]) bar.start() for i in f: i = i.rstrip() o = urlparse.urlparse(i) o = o.netloc lat,lon = kmlfile_location_IP(o) #GET LOCATION INFO val = lon+","+lat d[o] = val count+=1 #STATUS KEEPER bar.update(count) bar.finish() doc = KML.kml(KML.Document()) #CREATE DOC BASE FOR KML for a in d: place_marker = KML.Placemark(KML.name(a),KML.Point(KML.coordinates(d[a])))#CREATE PLACEMAKER AND POINT INKML doc.Document.append(place_marker) fp = open("report.kml","w") fp.write(etree.tostring(doc, pretty_print=True))#PARSE AS XML AND WRITE TO FILE fp.close() f.close() stop=time.time() #PROGRAM OUTPUT print("KML File was written successfully in "+str((stop-start)/60)+" mins. Check report.kml")
def writeKML(points, file_path): kmlDoc = KML.kml() doc = KML.Document() coors_str = '' for i, point in enumerate(points): if i == 0: defaultView = {'lon': float(point[1]), 'lat': float(point[0]), 'alt': 0, 'range': 3108.303488980141, 'tilt': 29.76964560740583, 'heading': 0} if i % 3 == 1: # topic is 10Hz, only record every third point coors_str = coors_str + str(point[1]) + ',' + str(point[0]) + ',' + '0' + ' ' placemark = creatPlacemark(coors_str, defaultView) doc.append(placemark) kmlDoc.append(doc) time_now = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) file_name = time_now + '.kml' kml_file_path = os.path.join(file_path, file_name) with open(kml_file_path, 'wb') as f: f.write(etree.tostring(kmlDoc, pretty_print=True))
def test_basic_kml_document_2(self): """Tests the creation of a basic OGC KML document.""" doc = KML.kml( KML.Document( KML.name("KmlFile"), KML.Placemark( KML.name("Untitled Placemark"), KML.Point( KML.coordinates("-95.265,38.959,0") ) ) ) ) # validate against a local schema self.assertTrue(Schema("ogckml22.xsd").validate(doc)) # validate against a remote schema self.assertTrue(Schema("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").validate(doc)) self.assertEquals( etree.tostring(doc), '<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<name>KmlFile</name>' '<Placemark>' '<name>Untitled Placemark</name>' '<Point>' '<coordinates>-95.265,38.959,0</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>' )
def convertFolder(self, inputPath, outputName, outputDir): kmzPaths = self.getKMZs(inputPath) colors = self.getColors() root = KML.kml(KML.Document()) folders = [] for index, kmzPath in enumerate(kmzPaths): folder = KML.Folder() folder.append(KML.name(os.path.basename(kmzPath))) color = colors[index % len(colors)] folder.append(self.getStyle(color)) kml_str = self.getKmlStrFromPath(os.path.join(inputPath, kmzPath)) if kml_str is None: return root = parser.fromstring(kml_str) for style in root.Document.Style: root.Document.remove(style) for placemark in root.Document.Placemark: placemark.Point.altitudeMode = 'absolute' lon, lat, alt = str(placemark.Point.coordinates).split(',') placemark.styleUrl = "#{}".format(color) folder.append(placemark) folders.append(folder) root.Document.remove(root.Document.name) root.Document.append(KML.name(outputName)) for folder in folders: root.Document.append(folder) outputPath = os.path.join(outputDir, outputName + ".kmz") kml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' kml_str += etree.tostring(root, pretty_print=True).decode('UTF-8') with ZipFile(outputPath, 'w') as zip: zip.writestr('doc.kml', kml_str)
def newKML(): doc = KML.Document() jet = plt.get_cmap('jet') colorList = {} for k in range(11): colorList[k] = matplotlib.colors.rgb2hex(jet(k/10.0))[1:] for (colorName, colorCode) in colorList.iteritems(): style = KML.Style( KML.IconStyle( KML.color("FF{}".format(colorCode)), KML.scale(0.6) ), KML.LabelStyle(KML.scale(0.5)), id="house_{}".format(colorName) ) styleMap = KML.StyleMap( KML.Pair( KML.key("normal"), KML.styleUrl("house_{}".format(colorName)) ), id="stylemap_house_{}".format(colorName)) doc.append(style) doc.append(styleMap) return doc
def get_kml(data): kml = KML.kml(KML.Document(KML.open(1))) for dt, sessions in data.items(): dt_fld = KML.Folder(KML.name(dt)) for session in sessions: fld = KML.Folder( KML.name(session['title']), KML.Placemark( KML.name('Traverse dt: {}, object: {}'.format(session['traverse']['dt'], session['title'])), KML.Point(KML.coordinates("{longitude},{latitude},0".format(**session['traverse']['coord']))) ), KML.Placemark( KML.name('Track - {title}'.format(**session)), KML.LineString( KML.coordinates( '\n'.join( "{longitude},{latitude},0".format(**coord['coord']) for coord in session['coords']) ) ) ) ) dt_fld.append(fld) kml.Document.append(dt_fld) kml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + lxml.etree.tostring(kml, pretty_print=True).decode() return kml_str
def TranslateShpFileToKML(file): print 'Translating file %s' % file basename = os.path.splitext(os.path.basename(file))[0] doc = KML.kml( KML.Document( KML.name('US Census Tracts ' + basename), KML.Style( KML.LineStyle( KML.color('ff00ff00'), KML.width(2) ), KML.PolyStyle( KML.color('66006600') ), id="ts" ) ) ) ProcessShpFile(file, basename, doc) kmlFilename = os.path.join(os.path.dirname(file), basename + '.kml') print 'Writing output file %s' % kmlFilename outputFile = open(kmlFilename, 'w+') outputFile.write(etree.tostring(doc, pretty_print=True)) outputFile.close()
def writeKML(points, urlDic, path): kmlDoc = KML.kml() doc = KML.Document() for point in points: style, colorTag = creatStyle(point[-1], urlDic) placemark = creatPlacemark(point, colorTag) doc.append(style) doc.append(placemark) kmlDoc.append(doc) print(etree.tostring(kmlDoc, pretty_print=True)) kmlFileName = path + '/KYXZ.kml' txtFileName = path + '/KYXZ.txt' # for inspect with open(kmlFileName, 'wb') as f: f.write(etree.tostring(kmlDoc, pretty_print=True)) with open(txtFileName, 'wb') as f: f.write(etree.tostring(kmlDoc, pretty_print=True)) # for inspect os.system('kill $(ps -A | grep earth | awk \'{print $1}\')') command = 'google-earth-pro ' + kmlFileName os.system(command)
def genSummaryStub(Ddeploy): # Start off with some background info root = K.kml( K.Document( ATOM.author(ATOM.name(KMLauthor)), ATOM.link(href=homepage), K.name(Ddeploy['name']), K.description(Ddeploy['purpose']), )) root.insert( 0, etree.Comment( '\nKML generated automatically by drifterSummaryKML.py\n')) doc = root.xpath('//default:Document', \ namespaces={'gx': 'http://www.google.com/kml/ext/2.2',\ 'atom': 'http://www.w3.org/2005/Atom',\ 'default': 'http://www.opengis.net/kml/2.2'}) # create and add the pieces of the stub doc[0].append( etree.Comment("\nStyle definition for drifter's positions\n")) doc[0].append(K.styleUrl('#drifter_info')) doc[0].append(genKMLstub.SurfaceStyle()) doc[0].append( etree.Comment("\nStyle definition for drifter's trackline\n")) doc[0].append(genKMLstub.TrackStyle(Ddeploy)) return root
def createKMLFromContainer(data, filename): iconColors = [ "ff0000ff", "ff00ff00", "ffff0000", "ff00ffff", "ffff00ff", "ffffff00" ] doc = KML.Document() for i, color in enumerate(iconColors): doc.append( KML.Style(KML.IconStyle(KML.color(color), ), id="report-style-" + str(i))) doc.append(KML.Folder("all")) colorIndex = 0 for tIndex, task in enumerate(data): print task for hIndex, house in enumerate(task.info["houses"]): pm = KML.Placemark( KML.styleUrl("#report-style-" + str(colorIndex % len(iconColors))), KML.name(str(tIndex) + "-" + str(hIndex)), KML.Point( KML.coordinates("{0},{1}".format( house["geometry"]["coordinates"][0], house["geometry"]["coordinates"][1])))) doc.Folder.append(pm) colorIndex += 1 out = open(filename, "wb") out.write(etree.tostring(doc, pretty_print=True)) out.close()
def gen_kml(self): """ Generate a KML file with keypoints on the locations of the pictures, including height :return: """ style_dot = "sn_shaded_dot" style_path = "red_path" doc = KML.kml( KML.Document( KML.Name("GPS of the images"), KML.Style( KML.IconStyle( KML.scale(0.4), KML.Icon( KML.href( "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png" )), ), id=style_dot, ), KML.Style(KML.LineStyle( KML.color('7f0000ff'), KML.width(6), GX.labelVisibility('1'), ), id=style_path))) # create points for i, gps in enumerate(self.tagged_gps): ii = i + 1 doc.Document.append( KML.Placemark( KML.styleUrl('#{0}'.format(style_dot)), KML.Point( KML.extrude(True), KML.altitudeMode('absolute'), KML.coordinates("{},{},{}".format( gps.lon, gps.lat, gps.alt))), KML.name(str(ii)) if ii % 5 == 0 or ii == 1 else KML.name())) # create the path doc.Document.append( KML.Placemark( KML.styleUrl('#{0}'.format(style_path)), KML.LineString( KML.altitudeMode('absolute'), KML.coordinates(' '.join([ "{},{},{}".format(gps.lon, gps.lat, gps.alt) for gps in self.tagged_gps ]))))) s = etree.tostring(doc) file_path = self.output + 'GoogleEarth_points.kml' f = open(file_path, 'w') f.write(s) f.close() print '[INFO] KML file generated on:', file_path
def genFinalStub(): # using information in the dictionary of deployment qualities, make KML # Start off with some background info root = K.kml( K.Document( ATOM.author(ATOM.name(KMLauthor)), ATOM.link(href=homepage), K.name(final_title), K.description( 'To track the ultimate fate of all released drifters'), )) root.insert( 0, etree.Comment( '\nKML generated automatically by drifterSummaryKML.py\n')) doc = root.xpath('//default:Document', \ namespaces={'gx': 'http://www.google.com/kml/ext/2.2',\ 'atom': 'http://www.w3.org/2005/Atom',\ 'default': 'http://www.opengis.net/kml/2.2'}) # create and add the pieces of the stub doc[0].append( etree.Comment("\nStyle definition for drifter's positions\n")) doc[0].append(K.styleUrl('#drifter_info')) doc[0].append(genKMLstub.SurfaceStyle()) return root
def test_write_python_script_for_kml_document(self): """Tests the creation of a trivial OGC KML document.""" from pykml.factory import write_python_script_for_kml_document doc = KML.kml( KML.Document( ATOM.author(ATOM.name("J. K. Rowling")), ATOM.link(href="http://www.harrypotter.com"), KML.Placemark(KML.name("Hogwarts"), KML.Point(KML.coordinates("1,1"))))) script = write_python_script_for_kml_document(doc) self.assertEqual( script, 'from lxml import etree\n' 'from pykml.factory import KML_ElementMaker as KML\n' 'from pykml.factory import ATOM_ElementMaker as ATOM\n' 'from pykml.factory import GX_ElementMaker as GX\n' '\n' 'doc = KML.kml(\n' ' KML.Document(\n' ' ATOM.author(\n' ' ATOM.name(\'J. K. Rowling\'),\n' ' ),\n' ' ATOM.link( href="http://www.harrypotter.com",\n' '),\n' ' KML.Placemark(\n' ' KML.name(\'Hogwarts\'),\n' ' KML.Point(\n' ' KML.coordinates(\'1,1\'),\n' ' ),\n' ' ),\n' ' ),\n' ')\n' 'print(etree.tostring(etree.ElementTree(doc),pretty_print=True).decode())\n' )
def test_kml_document_with_atom_element(self): """Tests the creation of a KML document with an ATOM element.""" doc = KML.kml( KML.Document( ATOM.author(ATOM.name("J. K. Rowling")), ATOM.link(href="http://www.harrypotter.com"), KML.Placemark(KML.name("Hogwarts"), KML.Point(KML.coordinates("1,1"))))) self.assertTrue(Schema("kml22gx.xsd").validate(doc)) target = etree.fromstring( '<kml ' 'xmlns:atom="http://www.w3.org/2005/Atom" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2" ' 'xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<atom:author>' '<atom:name>J. K. Rowling</atom:name>' '</atom:author>' '<atom:link href="http://www.harrypotter.com"/>' '<Placemark>' '<name>Hogwarts</name>' '<Point>' '<coordinates>1,1</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>') self.assertTrue(compare_xml(target, doc))
def test_getXmlWithCDATA(self): '''tests the format_as_cdata function''' kmlobj = KML.kml( KML.Document( KML.Placemark(KML.name('foobar'), KML.styleUrl('#big_label'), KML.description('<html>'), KML.text('<html>'), KML.linkDescription('<html>'), KML.displayName('<html>')))) target = etree.fromstring( '<kml' ' xmlns:atom="http://www.w3.org/2005/Atom"' ' xmlns:gx="http://www.google.com/kml/ext/2.2"' ' xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<Placemark>' '<name>foobar</name>' '<styleUrl>#big_label</styleUrl>' '<description><![CDATA[<html>]]></description>' '<text><![CDATA[<html>]]></text>' '<linkDescription><![CDATA[<html>]]></linkDescription>' '<displayName><![CDATA[<html>]]></displayName>' '</Placemark>' '</Document>' '</kml>') # Use xmldiff to compare the generated XML tree. self.assertTrue(compare_xml(target, kmlobj))
def update_kml(self, request, response): change = KML.Change() create = KML.Create() delete = KML.Delete() doc = KML.Document(targetId=KmlPlacemark.DOC_ID) for id_, kpm in self.placemarks.items(): if kpm.is_new: style_url = KmlStyleUtils.get_style_url_for_callsign(kpm.callsign) model_url = None # KmlStyleUtils.get_model_url_for_callsign(kpm.callsign, request.host_url) placemark = kpm.get_placemark(style_url, model_url) doc.append(placemark) kpm.is_new = False else: kpm.generate_update(change = change, create = create, delete = delete) if doc.countchildren() > 0: create.append(doc) update = KML.Update(KML.targetHref(request.path_url)) if change.countchildren() > 0: update.append(change) if create.countchildren() > 0: update.append(create) if delete.countchildren() > 0: update.append(delete) network_link_control = KML.NetworkLinkControl(update) return KML.kml(network_link_control)
def writeKML(points, urlDic, path): """ 功能:生成kml文件。该kml文件由任务文件转化得来。程序自动打开google earth并加载此kml文件,用于检查任务点\n 输入:任务点列表,点颜色url链接,任务文件所在路径\n 输出:无。函数生成KYXZ.kml和KYXZ.txt两个文件 """ kmlDoc = KML.kml() doc = KML.Document() for point in points: style, colorTag = creatStyle(point[-1], urlDic) placemark = creatPlacemark(point, colorTag) doc.append(style) doc.append(placemark) kmlDoc.append(doc) print(etree.tostring(kmlDoc, pretty_print=True)) kmlFileName = path + '/KYXZ.kml' kmlFileName_old = path + '/1.kml' txtFileName = path + '/KYXZ.txt' # for inspect with open(kmlFileName, 'wb') as f: f.write(etree.tostring(kmlDoc, pretty_print=True)) with open(txtFileName, 'wb') as f: f.write(etree.tostring(kmlDoc, pretty_print=True)) # for inspect command = 'rm ' + kmlFileName_old os.system(command) os.system('kill $(ps -A | grep earth | awk \'{print $1}\')') command = 'google-earth-pro ' + kmlFileName os.system(command)
def __init__(self, path): self.path = path self.json_file = '' self.fld = KML.Document( KML.name('new.kml'), KML.open('1'), KML.Style(KML.IconStyle( KML.scale('1.3'), KML.Icon( KML.href( 'http://maps.google.com/mapfiles/kml/pushpin/ylw-pushpin.png' ), ), KML.hotSpot( x="20", y="2", xunits="pixels", yunits="pixels", ), ), id="color1"), KML.Style(KML.LineStyle(KML.color('ff00ffff'), KML.width('2')), id='type1'), KML.Style(KML.LineStyle(KML.color('ffffff00')), id='type2'), KML.styleMap( KML.pair(KML.key('normal'), KML.styleUrl('#type1')), KML.Pair(KML.key('highlight'), KML.styleUrl('#type2'))))
def CreateLogosKML(): kml = KML.kml( KML.Document( KML.Folder( KML.ScreenOverlay( KML.name('Logos'), KML.Icon(KML.href('http://lg1:81/SF/Logos.png')), KML.overlayXY(x="0", y="1", xunits="fraction", yunits="fraction"), KML.screenXY(x="0.02", y="0.9", xunits="fraction", yunits="fraction"), KML.rotationXY(x="0", y="0", xunits="fraction", yunits="fraction"), KML.size(x="0.5", y="0.5", xunits="fraction", yunits="fraction"))))) f = open( global_vars.kml_destination_path + 'slave_{}.kml'.format(global_vars.screen_for_logos), "w") out = etree.tostring(kml, pretty_print=True).decode("utf-8") f.write(out) f.close()
def test_getXmlWithCDATA(self): '''tests the format_as_cdata function''' from pykml.util import format_xml_with_cdata kmlobj = KML.kml( KML.Document( KML.Placemark(KML.name('foobar'), KML.styleUrl('#big_label'), KML.description('<html>'), KML.text('<html>'), KML.linkDescription('<html>'), KML.displayName('<html>')))) self.assertEqual( etree.tostring(format_xml_with_cdata(kmlobj)), '<kml xmlns:gx="http://www.google.com/kml/ext/2.2"' ' xmlns:atom="http://www.w3.org/2005/Atom"' ' xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<Placemark>' '<name>foobar</name>' '<styleUrl>#big_label</styleUrl>' '<description><![CDATA[<html>]]></description>' '<text><![CDATA[<html>]]></text>' '<linkDescription><![CDATA[<html>]]></linkDescription>' '<displayName><![CDATA[<html>]]></displayName>' '</Placemark>' '</Document>' '</kml>')
def CreateDateAndColorbarKML(date): kml = KML.kml( KML.Document( KML.Folder( KML.ScreenOverlay( KML.name('Colorbar'), KML.Icon(KML.href('http://lg1:81/SF/colorbar.png')), KML.overlayXY(x="0", y="1", xunits="fraction", yunits="fraction"), KML.screenXY(x="0.75", y="0.8", xunits="fraction", yunits="fraction"), KML.rotationXY(x="0", y="0", xunits="fraction", yunits="fraction"), KML.size(x="0.25", y="0.6", xunits="fraction", yunits="fraction"))))) filename = 'slave_{}.kml'.format(global_vars.screen_for_colorbar) if date: filename = 'historic_' + str(date) + "_" + filename print(filename) if date: kml.Document.Folder.append( KML.ScreenOverlay( KML.name('Date'), KML.Icon( KML.href( 'http://chart.apis.google.com/chart?chst=d_text_outline&chld=FFFFFF|20|h|000000|_|{}' .format(date))), KML.overlayXY(x="0", y="1", xunits="fraction", yunits="fraction"), KML.screenXY(x="0.02", y="0.95", xunits="fraction", yunits="fraction"), KML.rotationXY(x="0", y="0", xunits="fraction", yunits="fraction"), KML.size(x="0.4", y="0.05", xunits="fraction", yunits="fraction"))) f = open(global_vars.kml_destination_path + filename, "w") out = etree.tostring(kml, pretty_print=True).decode("utf-8") f.write(out) f.close()
def writeKMLFile(self,srcFileName=None, tgtFileName=None): ''' read json data from response file (srcFileName), parse longitude, latitude and amplitude. then write data in kml format (for google earth and oruxmaps) to tgtFileName format is: Keyhole Markup Language (.kml) First, use Google Earth to draw a sketch and then save it as .kml file. Then, use the parser from pykml to parse the previous .kml file and use the write_python_script_for_kml_document from pykml.factory to create script for it. Last, modify the script to adapt the usage here and write this function ''' if tgtFileName == None: return "target File name is empty!" pathName,fileName = os.path.split(tgtFileName) fileNameTrunk, fileNameExt = os.path.splitext(fileName) kmlFileName = os.path.join(pathName,fileNameTrunk+".kml") #check sourceFileName and read file contents if os.path.isfile(srcFileName) == False: self.tgtTxt.SetValue(srcFileName + " does NOT exist!!!") return "File not exist!" utf8_json_data = json.loads(open(srcFileName).read(),encoding='utf-8') #if os.path.isfile(fName) == False: return "Not a file name!" if utf8_json_data == None: return "utf8_json_data is empty!" strList = ["%s,%s,%s" % (i[2],i[1],i[3]) for i in utf8_json_data] strCoords = " ".join(strList) print "kmlFileName in writeKMLFile is: " + kmlFileName #pathName,fileName = os.path.split(kmlFileName) #fileNameTrunk, fileNameExt = os.path.splitext(fileName) from lxml import etree from pykml.factory import KML_ElementMaker as KML # from pykml.factory import ATOM_ElementMaker as ATOM # from pykml.factory import GX_ElementMaker as GX doc = KML.kml( KML.Document( KML.name(unicode(fileNameTrunk)+u".kml"), KML.Placemark( KML.name(unicode(fileNameTrunk)), KML.LineString( KML.tessellate('1'), KML.coordinates(strCoords), ), ), ), ) #print etree.tostring(etree.ElementTree(doc),pretty_print=True) #outfile = file(tgtFileName.rstrip('.plt')+'.kml','w') outfile = file(kmlFileName,'w') outfile.write(etree.tostring(doc, encoding='UTF-8', xml_declaration=True, pretty_print=True))
def write_network_link_file(region_docs, ts_obj, box_list, lod, net_link_file): """Write 1) the list of KML.Document() into data KML file and 2) the root kml file for the list""" ## 1. Create directory to store regioalized KML data files links_dir = os.path.splitext(net_link_file)[0] if not os.path.isdir(links_dir): os.makedirs(links_dir) print("create KML region links directory: {}".format(os.path.basename(links_dir))) ## 2. Create root KML element and KML Document element kml = KML.kml() kml_document = KML.Document() ## 3. Generate a new network link element for each region for num, (region_doc, box) in enumerate(zip(region_docs, box_list)): region_kml_file = os.path.join(links_dir, "region_{}.kml".format(num)) ## 3.1 Write the first region_document to a file and move it to the proper subdircetory kml_1 = KML.kml() kml_1.append(region_doc) with open(region_kml_file, 'w') as f: f.write(etree.tostring(kml_1, pretty_print=True).decode('utf-8')) ## 3.2 Flatten lats and lons data lats, lons = flatten_lat_lon(box, ts_obj) ## 3.3 Define new NetworkLink element network_link = KML.NetworkLink( KML.name('Region {}'.format(num)), KML.visibility(1), KML.Region( KML.Lod( KML.minLodPixels(lod[0]), KML.maxLodPixels(lod[1]) ), KML.LatLonAltBox( KML.north(lats[0] + 0.5), KML.south(lats[-1] - 0.5), KML.east(lons[0] + 0.5), KML.west(lons[-1] - 0.5) ) ), KML.Link( KML.href(os.path.relpath(region_kml_file, start=os.path.dirname(links_dir))), KML.viewRefreshMode('onRegion') ) ) ## 3.4 Append new NetworkLink to KML document kml_document.append(network_link) kml.append(kml_document) ## 4. Write the full KML document to the output file and move it to the proper directory with open(net_link_file, 'w') as f: f.write(etree.tostring(kml, pretty_print=True).decode('utf-8')) return net_link_file
def createKML(docid, iconurl): return KML.kml( KML.Document( KML.Style( KML.IconStyle( KML.scale(1.0), KML.Icon(KML.href(iconurl)), ), id=docid, )))
def run(self): self.counter = self.counter + 1 self.origin = osr.SpatialReference () self.origin.ImportFromEPSG(self.EPSG) stylename = "export_dm" doc = KML.kml() document = KML.Document() docname = KML.Name("DynaMind Export") document.append(docname) doc.append(document) document.append( KML.Style( KML.LineStyle( KML.width(3), KML.color(self.rgb_to_hex( 0,255,255,255)), ), KML.PolyStyle( KML.color(self.rgb_to_hex( 0,255,255,255)), ), id="#SWMM", ) ) fld = KML.Folder() city = self.getData("City") uuids = city.getUUIDs(View(self.ViewName, COMPONENT, READ)) objectid_total = 0 for uuid in uuids: #getLinks building = city.getComponent(uuid) objects = [] if self.Type == "COMPONENT": center = Node(building.getAttribute("centroid_x").getDouble(), building.getAttribute("centroid_y").getDouble(),0.0) LinkAttributes = building.getAttribute("Geometry").getLinks() for attribute in LinkAttributes: objects.append(attribute.uuid) self.createPlacemarkForSelection(city.getComponent(uuid), uuid, center, fld) if self.Type == "FACE": objects.append(uuid) self.createPlacemarkAsLineRing(city, objects, fld) document.append(self.create_syles(city, uuid)) if self.Type == "EDGE": objects.append(uuid) self.createPlacemarkAsLineString(city, objects, fld) doc.Document.append(fld) text_file = open(self.Filename+"_"+str(self.counter)+str(".kml"), "w") text_file.write(etree.tostring(doc, pretty_print=True)) text_file.close()
def init_kml(KMLname): # start with a base KML tour and playlist tour_doc = KML.kml( KML.Document( GX.Tour( KML.name(KMLname), GX.Playlist(), ), ) ) return tour_doc
def export_kml(filename, pos): """ Export position in LLA to KML """ fld = kml.Document() for i in range(len(pos)): fld.append( kml.Placemark( kml.Point( kml.coordinates( str(pos[0]) + "," + str(pos[1]) + "," + str(pos[1]))))) file = open(str(filename) + ".kml", "w") file.write(str(parser.etree.tostring(fld))) file.close()
def generate_kml_template(self, styleKey): """Create a .kml file skeleton""" self.doc = KML.kml(KML.name(self.document_name), KML.Document(KML.name(self.document_name))) self.doc = self.append_style(self.doc, styleKey) self.doc.Document.append( KML.Folder(KML.name(self.document_name), KML.open(1), KML.Placemark(KML.name(self.document_name), ))) return self.doc
def setUp(self): self.kml = KML.kml( KML.Document( KML.Folder( KML.name("Folder0"), KML.Placemark( KML.name("Placemark0"), KML.Point(KML.coordinates("0,0,0")), KML.altitudeMode("relativeToGround"), KML.styleUrl("#style_test"), KML.description("Description: test placemark 0"), KML.ExtendedData( KML.SchemaData( KML.SimpleData("TEST0").set("name", "test0"), ), ), ), KML.Placemark( KML.name("Placemark1"), KML.Point(KML.coordinates("0,0,0")), KML.altitudeMode("relativeToGround"), KML.styleUrl("#style_test"), KML.description("Description: test placemark 1"), KML.ExtendedData( KML.SchemaData( KML.SimpleData("TEST1").set("name", "test1"), ), ), )), KML.Folder( KML.name("Folder1"), KML.Placemark( KML.name("Placemark0"), KML.Point(KML.coordinates("0,0,0")), KML.altitudeMode("relativeToGround"), KML.styleUrl("#style_test"), KML.description("Description: test placemark 0"), KML.ExtendedData( KML.SchemaData( KML.SimpleData("TEST0").set("name", "test0"), ), ), ), KML.Placemark( KML.name("Placemark1"), KML.Point(KML.coordinates("0,0,0")), KML.altitudeMode("relativeToGround"), KML.styleUrl("#style_test"), KML.description("Description: test placemark 1"), KML.ExtendedData( KML.SchemaData( KML.SimpleData("TEST1").set("name", "test1"), ), ), )))) kmldata.save_kml(self.kml, "Default.kml")