def create_reference_point_element(inps, lats, lons, ts_obj): star_file = "star.png" colormap = mpl.cm.get_cmap(inps.colormap) # set colormap norm = mpl.colors.Normalize(vmin=inps.vlim[0], vmax=inps.vlim[1]) ref_yx = (int(ts_obj.metadata['REF_Y']), int(ts_obj.metadata['REF_X'])) ref_lalo = (lats[ref_yx[0], ref_yx[1]], lons[ref_yx[0], ref_yx[1]]) reference_point = KML.Placemark( KML.Style( KML.IconStyle( KML.color(get_color_for_velocity(0.0, colormap, norm)), KML.scale(1.), KML.Icon(KML.href("{}".format(star_file))) ) ), KML.description("Reference point <br /> \n <br /> \n" + generate_description_string(ref_lalo, ref_yx, 0.00, 0.00, 0.00, 1.00) ), KML.Point( KML.coordinates("{}, {}".format(ref_lalo[1], ref_lalo[0])) ) ) return reference_point, star_file
def getCountryNodes(Placemarks, hostname): """ extrahiert für in der Karte verwendete Länder die Country-Placemarks (Polygone) aus countryKMLPath aus, passt sie an und liefert sie als Liste zurück """ countryNames = countrySet(Placemarks) fileobj = open(countryKMLPath, "r") countryText = fileobj.read() fileobj.close() del fileobj countryNodeList = [] countryRoot = parser.fromstring(countryText) countryPlacemarks = countryRoot.Document.findall( "{http://www.opengis.net/kml/2.2}Placemark") for countryPlacemark in countryPlacemarks: if countryPlacemark.name.text in countryNames: point = countryPlacemark.MultiGeometry.find( "{http://www.opengis.net/kml/2.2}Point") countryPlacemark.MultiGeometry.remove(point) newStyleUrl = KML.styleUrl(hostname + "/UserMap/" + "styles.kml" + "#country") countryPlacemark.append(newStyleUrl) typeNode = KML.type("country") countryPlacemark.append(typeNode) countryNodeList.append(countryPlacemark) return countryNodeList
def create_network_link_element(name, kml_file, ts_obj): lats, lons = flatten_lalos(None, ts_obj) network_link = KML.NetworkLink( KML.name(name), KML.visibility(1), KML.Region( KML.Lod( KML.minLodPixels(0), KML.maxLodPixels(1800) ), KML.LatLonAltBox( KML.north(lats[-1] + 0.5), KML.south(lats[0] - 0.5), KML.east(lons[-1] + 0.5), KML.west(lons[0] - 0.5) ) ), KML.Link( KML.href(kml_file), KML.viewRefreshMode('onRegion') ) ) return network_link
def mission_route(): """ Flask route that dynamically generates a KML of the current mission as specified in the mission YAML. """ # Retrieve origin and create a list of KML attributes origin = mission_planner.environment.origin kml_list = [KML.name("SRR Mission")] # Add placemarks for each mission waypoint. for task in mission_planner.mission: kml_list.append(frame_placemark(origin, task.name, task.location.x, task.location.y, marker='waypoint.png', color='ffff0000')) if not task.is_point: kml_list.append( bounds_placemark(origin, task.name + " bounds", task.bounds)) # Create a KML document with this environment represented. doc = KML.kml( KML.Document( *kml_list ) ) return etree.tostring(doc)
def to_placemark(t): if t.route is None: return None geometries = [] for ls in t.route: g = [] for lon, lat in ls: g.append('{},{}'.format(lon, lat)) coordinates = ' '.join(g) geometry = KML.LineString( KML.coordinates(coordinates)) geometries.append(geometry) name = t.number if t.company is not None: name = '{} {}'.format(t.company, t.number) href = 'https://angkot.web.id/route/#/{}/'.format(t.id) return KML.Placemark( KML.name(name), ATOM.link(href=href), ATOM.updated(t.updated.isoformat()), KML.MultiGeometry(*geometries))
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 creatStyle(attr, urlDic): if attr == 0: colorTag = 'ylw' url = urlDic[colorTag] elif attr == 1: colorTag = 'blue' url = urlDic[colorTag] elif attr == 2: colorTag = '2' url = urlDic[colorTag] elif attr == 3: colorTag = '3' url = urlDic[colorTag] elif attr == 4: colorTag = '4' url = urlDic[colorTag] elif attr == 5: colorTag = '5' url = urlDic[colorTag] else: colorTag = 'else' url = urlDic[colorTag] style = KML.Style(KML.IconStyle( KML.scale(1.2), KML.Icon(KML.href(url), ), ), id=colorTag) return style, colorTag
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 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 add_placemark_line_string(self, data, pm_name, style, kml_doc): kml_doc.Document.Folder.append( KML.Placemark( KML.name(pm_name.upper()), KML.MultiGeometry( KML.styleUrl('#{0}'.format(style)), KML.Point( KML.extrude(0), KML.altitudeMode("relativeToGround"), KML.coordinates("{lon},{lat},{alt}".format( lon=float(data[4]), lat=float(data[5]), alt=50, ) ) ), KML.LineString( KML.coordinates( '{0},{1},{2} '.format(float(data[2]),float(data[3]),data[6]), '{0},{1},{2} '.format(float(data[0]),float(data[1]),data[6]) ), ), ), id=pm_name.replace(' ', '_') ) ) return kml_doc
def creatStyle(attr, urlDic): """ 功能:生成style标签\n 输入:任务文件中任务点属性,点颜色url链接\n 输出:kml文件style对象,点颜色标签 """ if attr == 0: colorTag = 'ylw' url = urlDic[colorTag] elif attr == 1: colorTag = 'blue' url = urlDic[colorTag] elif attr == 2: colorTag = '2' url = urlDic[colorTag] elif attr == 3: colorTag = '3' url = urlDic[colorTag] elif attr == 4: colorTag = '4' url = urlDic[colorTag] elif attr == 5: colorTag = '5' url = urlDic[colorTag] else: colorTag = 'else' url = urlDic[colorTag] style = KML.Style(KML.IconStyle( KML.scale(1.2), KML.Icon(KML.href(url), ), ), id=colorTag) return style, colorTag
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)) data = etree.tostring(doc, encoding='ascii') expected = \ b'<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' \ b'xmlns:atom="http://www.w3.org/2005/Atom" ' \ b'xmlns="http://www.opengis.net/kml/2.2">' \ b'<Document>' \ b'<name>KmlFile</name>' \ b'<Placemark>' \ b'<name>Untitled Placemark</name>' \ b'<Point>' \ b'<coordinates>-95.265,38.959,0</coordinates>' \ b'</Point>' \ b'</Placemark>' \ b'</Document>' \ b'</kml>' self.assertXmlEquivalentOutputs(data, expected)
def to_kml(self, round=None): from pykml.factory import KML_ElementMaker as KML poly = KML.Polygon( KML.tesselate("1") ) outer = KML.outerBoundaryIs() inner = KML.innerBoundaryIs() has_inner = False for i in range(len(self.poly)): cnt = self.poly[i] coords = '' for p in cnt: coords += ','.join(map(str, p)) + ' ' ring = KML.LinearRing( KML.coordinates(coords) ) #hole = self.poly.isHole(i) #if hole == False: outer.append(ring) #else: # inner.append(ring) # has_inner = True poly.append(outer) if has_inner: poly.append(inner) return poly
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 extend(infos, expocode): extended = KML.ExtendedData( KML.Data( KML.value(expocode), name='expocode', ), *infos) return extended
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 kml(name, lat,lon): return KML.Placemark( KML.name(name), KML.Point( KML.coordinates( "%(long).04f,%(lat).04f" % { 'lat': lat, 'long': lon } ) ) )
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 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 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 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 generate_kml(places): doc = KML.kml( KML.Document( KML.Name("Awesome places"), KML.Style( KML.IconStyle( KML.scale(1.2), KML.Icon( KML.href("http://maps.google.com/mapfiles/kml/pal4/icon28.png") ), ) ) ) ) for data in places: pm = KML.Placemark( KML.name(data.get("name")), KML.Point(KML.coordinates(str(data.get("lng")) + "," + str(data.get("lat")))) ) doc.Document.append(pm) result = etree.tostring(doc, pretty_print=True) result.replace("placemark", "Placemark") result.replace("point", "Point") return result
def debugging(latitude, longitude) : global initLat, initLon, me, ne, lat, lon, carryY, carryX, fld, filebool, angles lat=latitude lon=longitude #lat=filt(lat, a) #lon=filt(lon, a) #print lat, lon lat_rad = lat *math.pi/180.0 lon_rad = lon *math.pi/180.0 if(filebool == True) : pm = KML.Placemark(KML.name("Placemark %d" % count), KML.Point(KML.coordinates("%f,%f" % (lat, lon)))) fld.append(pm) count = count + 1 try : #print angles[2] if(initLat == 0) : br.sendTransform((0, 0, 0), tf.transformations.quaternion_from_euler(0, 0, carryYaw, "sxyz"), rospy.Time.now(), 'base_link', 'dummy') (trans, rot) = listener.lookupTransform('map', 'base_link', rospy.Time()) angles = tf.transformations.euler_from_quaternion(rot) initLat = lat_rad initLon = lon_rad me = earth_radius*(1-earth_ecc*earth_ecc)/((1-earth_ecc*earth_ecc*math.sin(lat_rad)*math.sin(lat_rad))**1.5) ne = earth_radius/((1-earth_ecc*earth_ecc*math.sin(lat_rad)*math.sin(lat_rad))**0.5) br.sendTransform((0, 0, 0), tf.transformations.quaternion_from_euler(0, 0, -(carryYaw + angles[2])), rospy.Time.now(), 'map', 'world') #br.sendTransform((0, 0, 0), tf.transformations.quaternion_from_euler(0, 0, carryYaw), rospy.Time.now(), 'world', 'map') else : carryY=(lon_rad - initLon)*(ne+h)*math.cos(lat_rad) carryX=(lat_rad - initLat)*(me+h) print carryYaw #br.sendTransform((carryX -trans[0], carryY -trans[1], 0), tf.transformations.quaternion_from_euler(0, 0, carryYaw -angles[2], "sxyz"), rospy.Time.now(), 'base_link', 'world') br.sendTransform((-carryX, -carryY, 0), tf.transformations.quaternion_from_euler(0, 0, carryYaw, "sxyz"), rospy.Time.now(), 'base_link', 'dummy') except(tf.LookupException, tf.ConnectivityException, tf.ExtrapolationException) : print "exception"
def plot_kml(galaxy): """ Hacky function to dump a galaxy to a kml. Be sure pykml is installed before using. """ from pykml.factory import KML_ElementMaker as KML from lxml import etree fld = KML.kml() for system in galaxy: a = KML.Placemark( KML.name('foo'), KML.Point( KML.coordinates('%f,%f' % (galaxy[system]["position_x"],galaxy[system]["position_y"])) ) ) fld.append(a) for dest in galaxy[system]['destinations']: a = KML.Placemark( KML.name("foo"), KML.LineString( KML.coordinates( "%s,%s %s,%s" % (galaxy[system]["position_x"],galaxy[system]["position_y"], galaxy[dest]["position_x"],galaxy[dest]["position_y"]) ) ) ) fld.append(a) f = open("test.kml", 'wa') f.write(etree.tostring(fld, pretty_print=True)) f.close()
def create_reference_point_element(inps, lats, lons, ts_obj): """Create reference point element""" colormap = mpl.cm.get_cmap(inps.colormap) # set colormap norm = mpl.colors.Normalize(vmin=inps.vlim[0], vmax=inps.vlim[1]) ref_yx = (int(ts_obj.metadata['REF_Y']), int(ts_obj.metadata['REF_X'])) ref_lalo = (lats[ref_yx[0], ref_yx[1]], lons[ref_yx[0], ref_yx[1]]) ref_point = KML.Placemark( KML.Style( KML.IconStyle( KML.color(get_hex_color(0.0, colormap, norm)), KML.scale(1.), KML.Icon( KML.href("{}".format(os.path.basename(inps.star_file))) ) ) ), KML.description("Reference point <br /> \n <br /> \n" + get_description_string(ref_lalo, ref_yx, 0.00, 0.00, 0.00, 1.00) ), KML.Point( KML.coordinates("{}, {}".format(ref_lalo[1], ref_lalo[0])) ) ) return ref_point
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 navigation_route(): """ Flask route that dynamically generates a KML of the current navigation outputs from the navigation module. """ # Retrieve origin and create a list of KML attributes origin = mission_planner.environment.origin rover_position = mission_planner.navigator.position rover_rotation = mission_planner.navigator.rotation rover_location = (rover_position, rover_rotation) goal = mission_planner.navigator.goal kml_list = [KML.name("SRR Navigation")] # Add placemark for rover location estimate. kml_list.append(frame_placemark( origin, "Rover", rover_position.x, rover_position.y, rover_rotation, marker='rover.png')) # Add placemark for navigation goal. if goal is not None: global_goal = srr.util.to_world(rover_location, goal) kml_list.append(frame_placemark( origin, "Goal", global_goal.x, global_goal.y, marker='goal.png', color='ff00ffff')) # Create a KML document with this environment represented. doc = KML.kml( KML.Document( *kml_list ) ) return etree.tostring(doc)
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") ) ) ) ) self.assertTrue(Schema("kml22gx.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 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 test_to_wkt_list_simple_polygon(self): """Tests the to_wkt_list function for a polygon with inner rings.""" from pykml.util import to_wkt_list # create a polygon poly = KML.Polygon( KML.extrude('1'), KML.altitudeMode('relativeToGround'), KML.outerBoundaryIs( KML.LinearRing( KML.coordinates( '-122.366278,37.818844,30 ' '-122.365248,37.819267,30 ' '-122.365640,37.819861,30 ' '-122.366669,37.819429,30 ' '-122.366278,37.818844,30 ' ), ), ), ) poly_wkt_list = to_wkt_list(poly) self.assertEqual(len(poly_wkt_list), 1) self.assertEqual( poly_wkt_list[0], ('POLYGON ((-122.366278 37.818844 30, ' '-122.365248 37.819267 30, ' '-122.365640 37.819861 30, ' '-122.366669 37.819429 30, ' '-122.366278 37.818844 30))') )
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 create_lod(minpix, maxpix): lod = KML.Lod( KML.minLodPixels(minpix), KML.maxLodPixels(maxpix), ) assert_valid(lod) return lod
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 setToKMLPolygon (inputSet, isMultiGeometry): """initializes container list for Polygon Coordinates""" PolygonCoords = [] """Adds input coordinates to container list""" for eachCoord in inputSet: PolygonCoords.append(CoordinateToString(eachCoord, isMultiGeometry)) """initializes string which contains polygon coordinates """ PolygonCoordinatesString = '' for PolygonCoord in PolygonCoords: PolygonCoordinatesString = PolygonCoordinatesString + str(PolygonCoord) """Creates the KML polygon object""" KMLPolygon = KML.Polygon( KML.outerBoundaryIs( KML.LinearRing( KML.coordinates( PolygonCoordinatesString ) ) ) ) return KMLPolygon
def addPointsCustom(doc, dataframe, latLabel, longLabel, valueLabel, bins, skipNull=1): if len(dataframe.index) == 0: return doc if (len(bins) != 10): raise ValueError("Expected bins to have 10 entries, got {}".format(len(bins))) plottedCoord = [] for i in dataframe.index: # get color if pd.isnull(dataframe.loc[i, valueLabel]): colorName = 0 else: diff = np.array(bins) - dataframe.loc[i, valueLabel] colorName = 10 for (x, d) in enumerate(diff): if d > 0: colorName = x break #add placemark to KML if not pd.isnull(dataframe.loc[i, valueLabel]) or skipNull == 0: coordStr = "{} {}".format(dataframe.loc[i, longLabel], dataframe.loc[i, latLabel]) if coordStr not in plottedCoord: point = KML.Placemark( KML.description("{:5f}".format(dataframe.loc[i, valueLabel])), KML.styleUrl("stylemap_house_{}".format(colorName)), KML.Point( KML.coordinates("{},{},0".format(dataframe.loc[i, longLabel],dataframe.loc[i, latLabel])) ) ) doc.append(point) plottedCoord.append(coordStr) return doc
def test_basic_kml_document(self): """Tests the creation of a basic KML with Google Extensions .""" doc = KML.kml( GX.Tour( GX.Playlist( GX.SoundCue( KML.href("http://dev.keyhole.com/codesite/cntowerfacts.mp3") ), GX.Wait( GX.duration(10) ), GX.FlyTo( GX.duration(5), GX.flyToMode("bounce"), KML.LookAt( KML.longitude(-79.387), KML.latitude(43.643), KML.altitude(0), KML.heading(-172.3), KML.tilt(10), KML.range(1200), KML.altitudeMode("relativeToGround"), ) ) ) ) ) self.assertTrue(Schema("kml22gx.xsd").validate(doc)) self.assertEqual( etree.tostring(doc).decode(), '<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">' '<gx:Tour>' '<gx:Playlist>' '<gx:SoundCue>' '<href>http://dev.keyhole.com/codesite/cntowerfacts.mp3</href>' '</gx:SoundCue>' '<gx:Wait>' '<gx:duration>10</gx:duration>' '</gx:Wait>' '<gx:FlyTo>' '<gx:duration>5</gx:duration>' '<gx:flyToMode>bounce</gx:flyToMode>' '<LookAt>' '<longitude>-79.387</longitude>' '<latitude>43.643</latitude>' '<altitude>0</altitude>' '<heading>-172.3</heading>' '<tilt>10</tilt>' '<range>1200</range>' '<altitudeMode>relativeToGround</altitudeMode>' '</LookAt>' '</gx:FlyTo>' '</gx:Playlist>' '</gx:Tour>' '</kml>' )
def init_kml_canvas(self): from pykml.factory import KML_ElementMaker as KML kml = KML.kml( KML.Document( KML.name('kartograph map') ) ) return kml
def create_latlonalt_square(north, south, west, east): box = KML.LatLonAltBox( KML.north(north), KML.south(south), KML.east(east), KML.west(west), ) #assert_valid(box) return box
def main(): print(dir(KML)) pm1 = KML.Placemark(KML.name("name"), KML.Point(KML.coordinates("-64.5253,18.4607"))) print(dir(KML)) print(etree.tostring(pm1, pretty_print=True)) #TODO: implement pass
def get_network_link(self, path, refresh = 1): return \ KML.NetworkLink( KML.Link( KML.href(path), KML.refreshMode('onInterval'), KML.refreshInterval(str(refresh)), ), )
def get_placemark(self, style_url=None, model_url=None): label = self.callsign+KmlStyleUtils.get_callsign_info(self.callsign) track = self.get_track(model_url) placemark = KML.Placemark(id=self.pm_id) placemark.append(KML.name(label)) placemark.append(KML.description(self.get_description())) if style_url is not None: placemark.append(KML.styleUrl(style_url)) placemark.append(track) return placemark
def make_netlink(url, region, name=None): netlink = KML.NetworkLink() if name: netlink.name = KML.name(name) if region: netlink.Region = region.kml_region() netlink.Link = KML.Link(KML.href(url), KML.viewRefreshMode("onRegion")) assert_valid(netlink) return netlink
def initfolder(kmldoc, foldername): folder = KML.Folder( KML.name(foldername), KML.visibility('0'), KML.open('0'), ) kmldoc.append(folder) return folder
def addToKML(self, ip, lonLat): pm = KML.Placemark( KML.name(ip), KML.Point( KML.coordinates(lonLat[0]+','+lonLat[1]) ) ) if args.d: print(etree.tostring(pm, pretty_print=True)) fld.append(pm)
def get_kml_doc(llhs): """Generates a KML document from a Pandas table of single point solutions. Requires columns lat, lon, and height. """ from pykml.parser import Schema from pykml.factory import KML_ElementMaker as KML from pykml.factory import GX_ElementMaker as GX center = llhs[['lat', 'lon', 'height']].mean() elts = lambda e: '%s,%s,%d' % (e['lon'], e['lat'], e['height']) coords = ' '.join(llhs.apply(elts, axis=1).values) xml_coords = KML.coordinates(coords) doc = KML.kml( KML.Placemark( KML.name("gx:altitudeMode Example"), KML.LookAt( KML.longitude(center.lon), KML.latitude(center.lat), KML.heading(center.height), KML.tilt(70), KML.range(6300), GX.altitudeMode("relativeToSeaFloor"),), KML.LineString( KML.extrude(1), GX.altitudeMode("relativeToSeaFloor"), xml_coords ) ) ) return doc
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 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 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 build_test_kml(): """build a simple KML file with a simple LineString, for testing purposes""" from pykml.factory import KML_ElementMaker as KML from pykml.factory import GX_ElementMaker as GX from lxml import etree from django.http import HttpResponse kml = KML.kml( KML.Placemark( KML.name("build_test_kml output"), KML.LookAt( KML.longitude(146.806), KML.latitude(12.219), KML.heading(-60), KML.tilt(70), KML.range(6300), GX.altitudeMode("relativeToSeaFloor"), ), KML.LineString( KML.extrude(1), GX.altitudeMode("relativeToSeaFloor"), KML.coordinates( "146.825,12.233,400 " "146.820,12.222,400 " "146.812,12.212,400 " "146.796,12.209,400 " "146.788,12.205,400" ), ), ) ) kml_str = etree.tostring(kml) return HttpResponse(kml_str, content_type="application/vnd.google-earth.kml")
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 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 test_basic_kml_document(self): """Tests the creation of a basic KML with Google Extensions .""" doc = KML.kml( GX.Tour( GX.Playlist( GX.SoundCue( KML.href('http://dev.keyhole.com/codesite/cntowerfacts.mp3') ), GX.Wait( GX.duration(10) ), GX.FlyTo( GX.duration(5), GX.flyToMode('bounce'), KML.LookAt( KML.longitude(-79.387), KML.latitude(43.643), KML.altitude(0), KML.heading(-172.3), KML.tilt(10), KML.range(1200), KML.altitudeMode('relativeToGround'), ) ) ) ) ) self.assertTrue(Schema('kml22gx.xsd').validate(doc)) data = etree.tostring(doc, encoding='ascii') expected = \ b'<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' \ b'xmlns:atom="http://www.w3.org/2005/Atom" ' \ b'xmlns="http://www.opengis.net/kml/2.2">' \ b'<gx:Tour>' \ b'<gx:Playlist>' \ b'<gx:SoundCue>' \ b'<href>http://dev.keyhole.com/codesite/cntowerfacts.mp3</href>' \ b'</gx:SoundCue>' \ b'<gx:Wait>' \ b'<gx:duration>10</gx:duration>' \ b'</gx:Wait>' \ b'<gx:FlyTo>' \ b'<gx:duration>5</gx:duration>' \ b'<gx:flyToMode>bounce</gx:flyToMode>' \ b'<LookAt>' \ b'<longitude>-79.387</longitude>' \ b'<latitude>43.643</latitude>' \ b'<altitude>0</altitude>' \ b'<heading>-172.3</heading>' \ b'<tilt>10</tilt>' \ b'<range>1200</range>' \ b'<altitudeMode>relativeToGround</altitudeMode>' \ b'</LookAt>' \ b'</gx:FlyTo>' \ b'</gx:Playlist>' \ b'</gx:Tour>' \ b'</kml>' self.assertXmlEquivalentOutputs(data, expected)
def execute(self): """ Execute the command. """ def __kml_table(data): """ Helper method for creating the table of network data for the kml file. @param data: The parsed network data @type data: dict @return: Formatted kml table representation of the data. @rtype: string """ kml_text = " <div style='height:400px;width:500px;overflow:auto'>\n <table width='500'>\n" for key, value in data.items(): kml_text += " <tr><td>{0}</td><td>{1}</td></tr>\n".format(key, value) kml_text += " </table>\n </div>\n" return kml_text networks = self.__network_service.list_models(source_file=self.__source_file) if len(networks) > 0: placemarks = [] for network in networks: name = network.essid encryption = network.encryption href = "http://maps.google.com/mapfiles/kml/paddle/grn-stars.png" if not str(encryption).__contains__('WPA'): href = "http://maps.google.com/mapfiles/kml/paddle/red-stars.png" pm = KML_ElementMaker.Placemark( KML_ElementMaker.name(name), KML_ElementMaker.description(__kml_table(network.as_dict())), KML_ElementMaker.Style( KML_ElementMaker.IconStyle( KML_ElementMaker.Icon( KML_ElementMaker.href(href) ), ), ), KML_ElementMaker.Point( KML_ElementMaker.coordinates("{0},{1}".format(network.longitude, network.latitude)) ) ) placemarks.append(pm) fold = KML_ElementMaker.Folder() for placemark in placemarks: fold.append(placemark) self.__ofile.write(etree.tostring(fold, pretty_print=True))