def CELLID(): #搜索并限定小区名称 result_enodeb_cell = k.drop_duplicates([u'CELL_CELLID']) cellname=result_enodeb_cell[u'CELL_CELLID'] cellname=list(cellname) fold1=KML.Folder() for i in range(0,len(cellname)): result_enodeb_cell2 = k.loc[(k[u'CELL_CELLID'] == cellname[i])] # 选择经纬度点 lon = result_enodeb_cell2[u"wgsLon"] lat = result_enodeb_cell2[u"wgsLat"] lon = list(lon) lat = list(lat) # 简单判断文件中的经纬度个数是否一致 if len(lon) != len(lat): print 'lon != lat nums' # 使用第一个点创建Folder name=cellname[i] ford = KML.Folder( KML.name(name), KML.Placemark( KML.Point(KML.coordinates(str(lon[0]) + ',' + str(lat[0]) + ',0')) ) ) # 将剩余的点追加到Folder中 for i in range(1, len(lon)): ford.append(KML.Placemark( KML.Point(KML.coordinates(str(lon[i]) + ',' + str(lat[i]) + ',0'))) ) fold1.append(ford) # 使用etree将KML节点输出为字符串数据 content = etree.tostring(etree.ElementTree(fold1), pretty_print=True) filename = "E:/google.kml" with open(filename.decode('utf-8', 'ignore'), 'a+') as fp: fp.write(content)
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 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")
def checkEnd(self): # print 'ckecking......' if (self.preTime == self.navfixTruth_.header.stamp.secs): self.checkTimes = self.checkTimes + 1 if (self.checkTimes > 1 and (self.finishSaving == 0)): print 'bag file finished, you can save the llh into .kml file now' # save the conventional positioning result to .kml file fold = KML.Folder( KML.Placemark( KML.Point( KML.coordinates( str(self.lon_[0]) + ',' + str(self.lat_[0]) + ',0')))) for i in range(1, len(self.lon_)): fold.append( KML.Placemark( KML.Point( KML.coordinates( str(self.lon_[i]) + ',' + str(self.lat_[i]) + ',0')))) content = etree.tostring(etree.ElementTree(fold), pretty_print=True) with open( '/home/wenws/20180305/carbour/1/conventional_kml.kml', 'w') as fp: fp.write(content) # save the proposed positioning result into .kml file fold = KML.Folder( KML.Placemark( KML.Point( KML.coordinates( str(self.lonProp_[0]) + ',' + str(self.latProp_[0]) + ',0')))) for i in range(1, len(self.lonProp_)): fold.append( KML.Placemark( KML.Point( KML.coordinates( str(self.lonProp_[i]) + ',' + str(self.latProp_[i]) + ',0')))) content = etree.tostring(etree.ElementTree(fold), pretty_print=True) with open('/home/wenws/20180305/carbour/1/Proposed_kml.kml', 'w') as fp: fp.write(content) self.finishSaving = 1 print 'finishing saving two .kml files ' self.preTime = self.navfixTruth_.header.stamp.secs
def write_kml(list_of_networks): has_data = False doc = KML.Document( KML.name("PH5 Events"), KML.Style(KML.IconStyle( KML.color('FF1400FF'), KML.scale('1.25'), KML.Icon( KML.href('http://maps.google.com/mapfiles/' + 'kml/shapes/open-diamond.png'))), id='star'), ) for network in list_of_networks: network_folder = KML.Folder( KML.name("Network Code: " + str(network.code) + " reportnum: " + network.reportnum)) for shot_line in network.shot_lines: folder = KML.Folder( KML.name("ShotLine " + str(shot_line.name[-3:]))) for shot in shot_line.shots: place_marker = (KML.Placemark( KML.styleUrl("#star"), KML.name(network.code + '.' + str(shot.shot_id)), KML.description('Shot size: ' + str(shot.mag) + ' ' + shot.mag_units + '\n Shot Time: ' + shot.start_time + '\n\n' + shot.description), KML.Point( KML.coordinates( str(shot.lon) + ',' + str(shot.lat) + ',' + str(shot.elev))))) folder.append(place_marker) has_data = True network_folder.append(folder) doc.append(network_folder) if has_data: if outfile and hasattr(outfile, 'write'): target = outfile elif outfile: target = open(outfile, 'w') else: target = sys.stdout target.write( etree.tostring(etree.ElementTree(doc), pretty_print=True)) else: raise NoDataError("Request resulted in no data being returned")
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 coords2kml(lons, lats, antnames=None, kmlfile='sites/KSC_Antenna_Sites_7m.kml'): """ Use a list of longitudes and latitudes to create a kml file for Google Earth to visualize :param lons: longitudes of the antennnas in degrees, float array :param lats: latitudes of the antennnas in degrees, float array :param antnames: (optional) names of the antennas, string array :return sitefile: output Google Earth kml file """ from pykml.factory import KML_ElementMaker as KML from lxml import etree if not antnames: antnames = [str(i + 1) for i in range(len(lons))] fld = KML.Folder() for (antname, lon, lat) in zip(antnames, lons, lats): pm = KML.Placemark( KML.name(antname), KML.Point(KML.coordinates('{0:.13f}, {1:.13f}'.format(lon, lat)))) fld.append(pm) with open(kmlfile, 'w') as f: f.write('<kml xmlns="http://www.opengis.net/kml/2.2"> \n') f.write('<Document> \n') f.write(etree.tostring(fld, pretty_print=True)) f.write('</Document> \n') f.write('</kml> \n')
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_cluster(data, cluster_name): lon = data['wgs_lon'] lat = data['wgs_lat'] if len(lon) != len(lat): print('lon != lat nums,请检查数据的经纬度信息') sys.exit(0) # 创文件夹,添加第一个点 kml_cluster = KML.Folder( KML.name(str(cluster_name)), KML.styleUrl("#m_ylw-pushpin"), KML.Placemark( KML.styleUrl("#m_ylw-pushpin"), KML.description('ECI:' + str(int(data["ECI"].iloc[0])), 'SINR:' + str(round(data["SINR"].iloc[0], 1)), 'RSRP:' + str(round(data["RSRP"].iloc[0], 1))), KML.Point( KML.styleUrl("#m_ylw-pushpin"), KML.coordinates( str(lon.iloc[0]) + ',' + str(lat.iloc[0]) + ',0')))) # 添加后面的采样点 for i in range(1, len(lon)): kml_cluster.append( KML.Placemark( KML.description('ECI:' + str(int(data["ECI"].iloc[i])), 'SINR:' + str(round(data["SINR"].iloc[i], 1)), 'RSRP:' + str(round(data["RSRP"].iloc[i], 1))), KML.Point( KML.coordinates( str(lon.iloc[i]) + ',' + str(lat.iloc[i]) + ',0')))) # print etree.tostring(etree.ElementTree(kml_file ),pretty_print=True) return kml_cluster
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 placemark_KML(jsonFilePath, kmlPath): f = open(jsonFilePath, 'r') jsonDecodes = json.load(f) coordi = [] for value in jsonDecodes: #提取poi经纬度和name信息,并将百度坐标系转换为GPS84坐标系 converCoordiGCJ = cc.bd09togcj02(value['location']['lng'], value['location']['lat']) converCoordiGPS84 = cc.gcj02towgs84(converCoordiGCJ[0], converCoordiGCJ[1]) coordi.append( (converCoordiGPS84[0], converCoordiGPS84[1], value['name'])) f.close() #print(coordi) folderKML = KML.Folder( KML.Placemark( KML.name(coordi[0][2]), KML.Point( KML.coordinates( str(coordi[0][0]) + ',' + str(coordi[0][1]) + ',0')))) #使用pykml库建立<Folder></Folder>跟标签,并追加第一个地标 for i in range(1, len(coordi)): folderKML.append( KML.Placemark( KML.name(coordi[i][2]), KML.Point( KML.coordinates( str(coordi[i][0]) + ',' + str(coordi[i][1]) + ',0')))) #在Folder标签下追加剩余的所有地标 content = etree.tostring(etree.ElementTree(folderKML), encoding='unicode', pretty_print=True) #将元素序列化为编码字符串 print(content) with codecs.open(kmlPath, 'w', "UTF-8") as kp: #指定文件编码格式为"UTF-8",写入地标文件 kp.write(content)
def store_transit_line_as_kml(transitRouteHtmlFile, transitName, transitOutputKmlFile): page = open(transitRouteHtmlFile, 'r') tree = html.fromstring(page.read()) # stations = tree.xpath('//*[@id="ivu_trainroute_table"]/tbody/tr/td[3]/text()') stations = tree.xpath( '//*[@id="HFSResult"]/div[2]/div/table/tbody/tr/td[2]/a/text()') folder = KML.Folder() coords = "" for station in stations: lng, lat = geocode_location(station) coord = "{}, {} ".format(lng, lat) place = KML.Placemark(KML.name(station), KML.Point(KML.coordinates(coord))) coords += coord folder.append(place) line = KML.Placemark(KML.name(transitName), KML.LineString(KML.coordinates(coords))) folder.append(line) #print(etree.tostring(folder, pretty_print=True)) save_to_klm(transitOutputKmlFile, folder)
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 draw_plate(platefile_url, output_dir): if os.path.exists(output_dir): print "Output directory already exists: %s" % output_dir print "Replace? (y/n)", answer = raw_input() if answer.lower() != 'y': exit(0) else: print "Creating %s" % output_dir os.makedirs(output_dir) level = 0 keep_drilling = True netlinks = [] hit_regions = [] folder = KML.Folder() kml = KML.kml(folder) if options.planet: kml.set('hint', "target=%s" % options.planet) while keep_drilling and level <= options.max_levels: print "Drawing level %d..." % level netlink = draw_level(level, platefile_url, output_dir, hit_regions) keep_drilling = bool(netlink) if netlink: netlinks.append(netlink) for netlink in netlinks: folder.append(netlink) print "Writing root.kml" with open(os.path.join(output_dir, 'root.kml'), 'w') as outfile: outfile.write(etree.tostring(kml, pretty_print=True)) level += 1 print "Done." sys.exit(0)
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 get_fld(self): if not self.pm_list: return None self.fld = KML.Folder(self.pm_list[0]) for pm in self.pm_list[1:]: self.fld.append(pm) return self.fld
def make_KML(C,B): fld = KML.Folder() new_dict = {} for i in C: new_dict[i] = "%s, %s"%(C[i][1],C[i][2]) place_in_parse = 0 for i in new_dict: fld1 = KML.Folder( KML.name("%s, recurrence %s"%(i,C[i][0]))) fld1.append( KML.Placemark( KML.Point( KML.coordinates(new_dict[i])), KML.name("Mean Spot %s"%(i)), KML.description("Longitude = %s\n Latitude = %s\n Recurrence: %s\n"%(C[i][1],C[i][2],C[i][0])))) for j in np.arange(C[i][0]) + place_in_parse: coords = "%s, %s"%(B[j][1][2],B[j][1][3]) spot = j - place_in_parse fld1.append( KML.Placemark( KML.Point( KML.coordinates(coords)), KML.name( "Spot %s"%(spot) ), KML.description("Longitude = %s\n Latitude = %s\n Filename: %s\n"%(B[j][1][2],B[j][1][3],B[j][2])))) place_in_parse += C[i][0] new_dict[i] = fld1 for i in new_dict: fld.append(new_dict[i]) outfile = file(__file__.rstrip('.py')+'.freq'+'.kml','w') outfile.write(etree.tostring(fld, pretty_print=True)) print "Created frequency file"
def Folder(Ddeploy): # Make a folder to put the drifter's points into # Note: for now the deployment Placemark is going in here, but it may move out # later. folder = K.Folder( K.name('Drifter positions'), K.description('Drifter positions at roughly daily intervals'), K.Style(K.ListStyle(K.listItemType('checkHideChildren')))) return folder
def quakeLs2kml(quakeLs, filename): fold = KML.Folder() for quakeL in quakeLs: for quake in quakeL: fold.append(lalodep2Place(quake.loc[0], quake.loc[1], quake.loc[2])) content = etree.tostring(etree.ElementTree(fold), pretty_print=True) #print(type(content)) with open(filename, 'wb') as fp: fp.write(content)
def initfolder(kmldoc, foldername): folder = KML.Folder( KML.name(foldername), KML.visibility('0'), KML.open('0'), ) kmldoc.append(folder) return folder
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 gen_kml_enb( data_wgs, level=3 ): #level1=tac,level2=enb,level3=cell,如果data_wgs数据已经包含,所以gongcan_l表就不需要了 data_wgs = data_wgs[[ 'p_day', 'CELL_RSRP', 'CELL_SINR', 'CELL_CELLID', 'eNBID', '区县', '频段', '站型', '方位角', 'wgs_lon', 'wgs_lat' ]] data_wgs["ECI"] = data_wgs["CELL_CELLID"] # print(data_wgs.head()) # data_wgs=pd.merge(data_wgs,gongcan_l[['ECI','eNBID','跟踪区']],left_on='CELL_CELLID',right_on="ECI",how="left") data_wgs.dropna(inplace=True) cell_list = data_wgs.CELL_CELLID.astype( int).drop_duplicates() #用于获得这些小区的共站同方向小区,然后再取其覆盖采样点生成google地图文件 cell_list = cell_list.to_list() ENB_list = data_wgs.eNBID.astype(int).drop_duplicates().to_list() # import os # filename = os.path.basename(file_csv) for i, ENB in enumerate(ENB_list): ENB_data = data_wgs[data_wgs['eNBID'] == ENB] classify_list = ENB_data['CELL_CELLID'].drop_duplicates().to_list() # classify_list=sorted(list(classify_list)) for j, clas in enumerate( classify_list): #这里按照ENB输出点,所以用ENB——list替代了cell_list point_data = ENB_data[ENB_data['CELL_CELLID'] == clas] if j == 0: #clas==classify_list[0]: cell_kml = KML.Folder( KML.name("ENB:" + str(ENB)), gen_kml_point(point_data, clas)) #加个document根目录,append的时候避免树结构错乱 else: cell_kml.append(gen_kml_point(point_data, clas)) if i == 0: ENB_kml = KML.Folder(KML.name('_反向覆盖小区采样点' + str(ENB)), cell_kml) else: ENB_kml.append(cell_kml) return ENB_kml
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 callgnss_ins_navsat(self,data): self.uck_bestPos_ = NavSatFix() self.uck_bestPos_ = data self.ukf_lat_.append(float(self.uck_bestPos_.latitude)) self.ukf_lon_.append(float(self.uck_bestPos_.longitude)) fold = KML.Folder(KML.Placemark(KML.Point(KML.coordinates(str(self.ukf_lon_[0]) + ',' + str(self.ukf_lat_[0]) + ',0')))) for i in range(1, len(self.ukf_lon_)): fold.append(KML.Placemark( KML.Point(KML.coordinates(str(self.ukf_lon_[i]) + ',' + str(self.ukf_lat_[i]) + ',0')))) content = etree.tostring(etree.ElementTree(fold), pretty_print=True) with open('Berkeley_gnss_ins.kml', 'w') as fp: fp.write(content)
def get_tags_by_city(tags, city): map_api = baidu.MapApi() file_name = get_file_name_by_city(city) kml_name = get_kml_file_by_city(city) fold = KML.Folder() with open(kml_name, 'w', encoding='utf-8') as kml_f: with open(file_name, 'w', encoding='utf-8', newline='\n') as f: print("Start...") f.write("{},{},{},{}\n".format('name', 'lat', 'lng', 'tags')) for tag in tags: sub_folder = KML.Folder() sub_folder.append(KML.name(tag)) data = map_api.place_api.get_place_all(tag, city) for item in data: try: name = item['name'] lng = float(item['location']['lng']) lat = float(item['location']['lat']) [g_lng, g_lat] = Transfer.bd09_to_wgs84(lng, lat) # Write data in CSV f.write("{},{},{},{}\n".format(name, g_lng, g_lat, tag)) # Write data in kml sub_folder.append( KML.Placemark( KML.name(name), KML.Point( KML.coordinates( str(g_lng) + "," + str(g_lat))))) except: logging.exception('Error: Parsing json file ') fold.append(sub_folder) f.close() output = etree.tostring(fold, pretty_print=True) kml_f.write(output.decode('utf-8')) kml_f.close() print("sucess") pass
def build_kml(self, filename): if self.pm_list: # 建立fld fld = KML.Folder(self.pm_list[0]) for pm in self.pm_list[1:]: fld.append(pm) # 解析fld content = etree.tostring( fld, pretty_print=True, ) with open(filename, 'wb') as fp: fp.write(content) return self.pm_list
def get_folder(element: KML.Folder, folder_path: list) -> KML.Folder: name = folder_path[0] folder_name = element.xpath( f"./t:Folder/*[text()='{name}']", namespaces={"t": "http://www.opengis.net/kml/2.2"}, ) if len(folder_name) == 0: folder = KML.Folder(KML.name(name)) element.append(folder) else: folder = folder_name[0].getparent() if len(folder_path) > 1: folder = get_folder(folder, folder_path[1:]) return folder
def main(): global folder namesKML = ['diff_solar', 'len_pattern', 'frequency'] for nameKML in namesKML: folder = KML.Folder() for i in range(1, 9): style = KML.Style(KML.PolyStyle(KML.color(colors[str(i)]), KML.colorMode('normal')), id="color" + str(i)) folder.append(style) drawPatterns('patternsbyday', nameKML) outfile = open(nameKML + '.kml', 'wb') outfile.write(etree.tostring(folder, pretty_print=True)) outfile.close()
def route_folder_generator(root, placemark_name, ROW_offset, buffer_offset): """ Generating Folder KML with Placemark main, ROW, and buffer inside """ route, raw_route = get_coordinate('MainPipeline', placemark_name, root) ROW_L, ROW_R = get_offset(route, ROW_offset) buffer_L, buffer_R = get_offset(route, buffer_offset) pm_main = placemark_generator('000', 'main', GREEN, 4, raw_route) pm_ROW = placemark_generator('001', 'ROW', BLUE, 4, [ROW_L, ROW_R]) pm_buffer = placemark_generator('002', 'buffer', RED, 4, [buffer_L, buffer_R]) folder_kml = KML.Folder(KML.name(placemark_name), pm_main, pm_ROW, pm_buffer) return folder_kml
def build_test_folder(): pm1 = KML.Placemark(KML.name("Hello World!"), KML.Point(KML.coordinates("-64.5253,18.4607"))) print(pm1.__dict__) print(etree.tostring(pm1, pretty_print=True)) pm2 = KML.Placemark(KML.name("A second placemark!"), KML.Point(KML.coordinates("-64.5358,18.4486"))) fld = KML.Folder(pm1, pm2) print() print(etree.tostring(fld, pretty_print=True)) save_to_klm('test.kml', fld) return fld