def test_trivial_kml_document(self): """Tests the creation of a trivial OGC KML document.""" doc = KML.kml() schema = Schema("ogckml22.xsd") self.assertTrue(schema.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"/>')
def test_fromstring_invalid_kml_document(self): "Tests the parsing of an invalid KML string" test_kml = '<bad_element />' try: tree = fromstring(test_kml, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def test_parse_invalid_kml_document(self): "Tests the parsing of an invalid KML document" fileobject = StringIO('<bad_element />') try: tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def test_parse_kml_file_with_cdata(self): "Tests the parsing of a local KML file, with a CDATA description string" test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_tutorial/using_the_cdata_element.kml' ) # parse with validation with open(test_datafile) as f: doc = parse(f, schema=Schema('ogckml22.xsd')) self.assertEqual( etree.tostring(doc).decode(), '<kml xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<Placemark>' '<name>CDATA example</name>' '<description>' '<![CDATA[\n' ' <h1>CDATA Tags are useful!</h1>\n' ' <p><font color="red">Text is <i>more readable</i> and \n' ' <b>easier to write</b> when you can avoid using entity \n' ' references.</font></p>\n' ' ]]>' '</description>' '<Point>' '<coordinates>102.595626,14.996729</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>' ) # parse without validation with open(test_datafile) as f: doc2 = parse(f) self.assertEqual( etree.tostring(doc2).decode(), '<kml xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<Placemark>' '<name>CDATA example</name>' '<description>' '<![CDATA[\n' ' <h1>CDATA Tags are useful!</h1>\n' ' <p><font color="red">Text is <i>more readable</i> and \n' ' <b>easier to write</b> when you can avoid using entity \n' ' references.</font></p>\n' ' ]]>' '</description>' '<Point>' '<coordinates>102.595626,14.996729</coordinates>' '</Point>' '</Placemark>' '</Document>' '</kml>' )
def test_parse_kml_url_2(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEquals( etree.tostring(tree)[:137], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<Document>' '<name>gx:AnimatedUpdate example</name>' )
def validate_kml(filepath, schema = "https://developers.google.com/kml/schema/kml21.xsd"): """ Validates kml located at filepath. TODO: Even imported kml files do not validate against default xml """ schema_gomaps = Schema(schema) data = "" with open(filepath, "r") as temp: data = temp.read() assert(data != "") doc = parser.fromstring(data) return schema_ogc.assertValid(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)) 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">' '<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>') self.assertTrue(compare_xml(target, doc))
def test_parse_kml_url(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEquals( etree.tostring(tree)[:185], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<!-- required when using gx-prefixed elements -->' '<Placemark>' '<name>gx:altitudeMode Example</name>' )
def test_parse_invalid_ogc_kml_document(self): """Tests the parsing of an invalid KML document. Note that this KML document uses elements that are not in the OGC KML spec. """ url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' fileobject = urllib2.urlopen(url) try: tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertTrue(False) except etree.XMLSyntaxError: self.assertTrue(True) except: self.assertTrue(False)
def task_to_kml_with_pykml(df_task, outdir, filename_base, disp): from lxml import etree from pykml.parser import Schema from pykml.factory import KML_ElementMaker as KML from pykml.factory import GX_ElementMaker as GX s_coords = task_to_string(df_task) (lat, lon) = calculate_center(df_task) #def turn_point_to_placemark(tp): # placemark = KML.Placemark( # KML.name(tp['Name']), # KML.description(tp['Name']), # KML.Point( # KML.coordinates(tp['Lon'], tp['Lat'], tp['Altitude']) # ), # ) # return(placemark) #placemarks = [turn_point_to_placemark(tp) for i, tp in df_task.iterrows()] doc = KML.kml( KML.Placemark( KML.name("Condor task '%s'" % filename_base), KML.LookAt( KML.longitude(lon), KML.latitude(lat), KML.heading(0), KML.tilt(60), KML.range(80000), GX.altitudeMode("relativeToSeaFloor"), #GX.altitudeMode("absolute"), ), KML.LineString( KML.extrude(1), GX.altitudeMode("relativeToSeaFloor"), #GX.altitudeMode("absolute"), KML.coordinates(s_coords), ), ), #*placemarks ) if disp: print(etree.tostring(doc, pretty_print=True)) # output a KML file (named based on the Python script) filename_out = os.path.join(outdir, filename_base + '.kml') print("Output '%s'" % filename_out) outfile = file(filename_out, 'w') outfile.write(etree.tostring(doc, pretty_print=True)) assert Schema('kml22gx.xsd').validate(doc)
def main(argv=None): if argv is None: argv = sys.argv try: try: opts, args = getopt.getopt(argv[1:], "h", ["help"]) except getopt.error, msg: raise Usage(msg) # main code schema = Schema("kml22gx.xsd") filename = argv[1] with open(filename) as f: kmldoc = parse(f, schema=schema) print(write_python_script_for_kml_document(kmldoc))
def test_parse_kml_url(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/KML_Samples.kml' #url = 'http://kml-samples.googlecode.com/svn/trunk/kml/Document/doc-with-id.kml' #url = 'http://code.google.com/apis/kml/documentation/kmlfiles/altitudemode_reference.kml' #url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' fileobject = urllib2.urlopen(url) tree = parse(fileobject, schema=Schema("ogckml22.xsd")) self.assertEquals( etree.tostring(tree)[:78], '<kml xmlns="http://www.opengis.net/kml/2.2">' '<Document>' '<name>KML Samples</name>' )
def test_parse_kml_file(self): "Tests the parsing of a local KML file, with validation" test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml' ) # parse with validation with open(test_datafile) as f: doc = parse(f, schema=Schema('kml22gx.xsd')) # parse without validation with open(test_datafile) as f: doc = parse(f) self.assertTrue(True)
def test_parse_kml_url_2(self): "Tests the parsing of a KML URL" url = 'http://code.google.com/apis/kml/documentation/kmlfiles/animatedupdate_example.kml' try: fileobject = urllib.request.urlopen(url) tree = parse(fileobject, schema=Schema('kml22gx.xsd')) self.assertEqual( etree.tostring(tree)[:137], '<kml xmlns="http://www.opengis.net/kml/2.2" ' 'xmlns:gx="http://www.google.com/kml/ext/2.2">' '<Document>' '<name>gx:AnimatedUpdate example</name>') except urllib.error.URLError: print('Unable to access the URL. Skipping test...')
def schema_invalid(file): 'Check if it is a valid schema' with open(file, 'r') as f: #The files supplied are most likely part of the google extension schema, so validate it against that root = parser.fromstring(f.read()) #Put the read cursor back at the start of the file f.seek(0) schema_gx = Schema("kml22gx.xsd") #If the kml file does not use a valid schema if not schema_gx.validate(root): return True else: return False
def test_count_elements(self): """Tests the counting of elements in a KML document.""" from pykml.util import count_elements test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml') with open(test_datafile) as f: doc = parse(f, schema=Schema('kml22gx.xsd')) summary = count_elements(doc) self.assertTrue(summary.has_key('http://www.opengis.net/kml/2.2')) self.assertEqual( 4, summary['http://www.opengis.net/kml/2.2']['Placemark']) self.assertTrue(summary.has_key('http://www.google.com/kml/ext/2.2')) self.assertEqual(5, summary['http://www.google.com/kml/ext/2.2']['FlyTo']) self.assertEqual(2, summary['http://www.google.com/kml/ext/2.2']['Wait'])
def test_write_python_script_for_kml_document_with_comments(self): """Tests the creation of an OGC KML document with several comments""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'simple_file_with_comments.kml' ) schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile # Useful for debugging with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') #print temp_kml_file # Useful for debugging with open(temp_kml_file, 'w') as f: exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml') # test that the original and generated documents are equivalent self.assertTrue(compare_etree(doc.getroot(), doc2.getroot()))
def test_write_python_script_for_kml_document_with_namespaces(self): """Tests the creation of an OGC KML document with several namespaces""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_developers_guide/complete_tour_example.kml' ) schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile #uncomment to print the temporary filename with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file # set the PYTHONPATH variable so that it references the root # of the pyKML library import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') #print temp_kml_file with open(temp_kml_file, 'w') as f: exit_code = subprocess.call(["python",tfile], stdout=f, env=current_env) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml')
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 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)) 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">' '<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>' )
KML.name("Play me!"), GX.Playlist( GX.FlyTo( GX.duration(3), GX.flyToMode("bounce"), KML.Camera( KML.longitude(170.157), KML.latitude(-43.671), KML.altitude(9700), KML.heading(-6.333), KML.tilt(33.5), )), GX.AnimatedUpdate( GX.duration(5), KML.Update( KML.targetHref(), KML.Change( KML.IconStyle(KML.scale(10.0), targetId="mystyle")))), GX.Wait(GX.duration(5)))))) print(etree.tostring(doc, pretty_print=True)) # output a KML file (named based on the Python script) outfile = file(__file__.rstrip('.py') + '.kml', 'w') outfile.write(etree.tostring(doc, pretty_print=True)) schema = Schema('kml22gx.xsd') import ipdb ipdb.set_trace() schema.validate(doc)
def test_write_python_script_for_kml_document_with_cdata(self): """Tests the creation of an OGC KML document with a cdata tag""" import os import tempfile from pykml.parser import parse from pykml.factory import write_python_script_for_kml_document test_datafile = path.join( path.dirname(__file__), 'testfiles', 'google_kml_tutorial/using_the_cdata_element.kml' ) file = 'test/testfiles/' schema = Schema('kml22gx.xsd') with open(test_datafile) as f: doc = parse(f, schema=schema) script = write_python_script_for_kml_document(doc) self.assertEquals( 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' ' KML.Placemark(\n' ' KML.name(\'CDATA example\'),\n' ' KML.description(\n' ' \'<h1>CDATA Tags are useful!</h1> \'\n' ' \'<p><font color="red">Text is <i>more readable</i> and \'\n' ' \'<b>easier to write</b> when you can avoid using entity \'\n' ' \'references.</font></p> \'\n' ' ),\n' ' KML.Point(\n' ' KML.coordinates(\'102.595626,14.996729\'),\n' ' ),\n' ' ),\n' ' ),\n' ')\n' 'print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n' ) # create a temporary python file handle, tfile = tempfile.mkstemp(suffix='.py') #print tfile with open(tfile, 'w') as f: f.write(script) # execute the temporary python file to create a KML file import subprocess current_env = os.environ.copy() current_env["PYTHONPATH"] = os.path.abspath( os.path.join(path.dirname(__file__),'../..') ) handle, temp_kml_file = tempfile.mkstemp(suffix='.kml') with open(temp_kml_file, 'w') as f: exit_code = subprocess.call( ["python",tfile], stdout=f, env=current_env ) self.assertEqual(exit_code, 0) # parse and validate the KML generated by the temporary script doc2 = parse(temp_kml_file, schema=schema) # test that the root element is as expected self.assertEqual(doc2.docinfo.root_name, 'kml')
def test_initialize_schema_remote_url(self): schema = Schema("http://code.google.com/apis/kml/schema/kml22gx.xsd") self.assertTrue(isinstance(schema.schema, etree.XMLSchema))
def test_initialize_schema(self): """Tests the creation Schema instance""" schema = Schema("ogckml22.xsd") self.assertTrue(isinstance(schema.schema, etree.XMLSchema))
from pykml.helpers import set_max_decimal_places import gpxpy import gpxpy.gpx from bs4 import BeautifulSoup as bs from tqdm import tqdm logging.basicConfig(level=logging.DEBUG) # parse kml root = parser.parse(sys.stdin).getroot() set_max_decimal_places(root, max_decimals={'longitude': 6, 'latitude': 6}) logging.info('kml22gx validation: %r', Schema('kml22gx.xsd').validate(root)) logging.info('ogckml22 validation: %r', Schema('ogckml22.xsd').validate(root)) # https://developer.mozilla.org/en-US/docs/Web/XPath/Functions # https://devhints.io/xpath placemarks = root.xpath('//k:Placemark', namespaces={'k': 'http://www.opengis.net/kml/2.2'}) logging.info(f'found {len(placemarks)} placemarks') # TODO read these fields from the kml file itself! # TODO make the mapping to their display names configurable # fields in KML file downloaded from FS fields = { 'RECAREANAM': 'Name: ',
for t in drange(0, 15, tstep): pm = kml.Placemark( kml.name(str(t)), kml.Point( kml.altitudeMode("absolute"), kml.coordinates("{lon},{lat},{alt}".format( lon=loc0['longitude'] + vx * t, lat=loc0['latitude'] + vy * t, alt=loc0['altitude'] + vz * t + 0.5 * g * t**2, )), )) tour_doc.Folder.append(pm) flyto = gx.FlyTo( gx.duration(tstep), gx.flyToMode("smooth"), kml.Camera( kml.longitude(loc0['longitude'] + vx * t), kml.latitude(loc0['latitude'] + vy * t), kml.altitude(loc0['altitude'] + vz * t + 0.5 * g * t**2), kml.heading(loc0['heading'] + vh * t), kml.tilt(loc0['tilt'] + vt * t), kml.altitudeMode("absolute"), )) tour_doc.Folder[GX_ns + "Tour"].Playlist.append(flyto) assert Schema('kml22gx.xsd').validate(tour_doc) print(etree.tostring(tour_doc, pretty_print=True)) # output a KML file (named based on the Python script) outfile = file(__file__.rstrip('.py') + '.kml', 'w') outfile.write(etree.tostring(tour_doc, pretty_print=True))
# bring in app from app import app # import packages import urllib.request from flask import render_template, request from lxml import etree from pathlib import Path from pykml import parser from pykml.parser import Schema #load in GMP schema scheme = Schema("GMP_Schema.xsd") # route requests for / and /index to index.html @app.route("/", methods=["GET", "POST"]) @app.route("/index", methods=["GET", "POST"]) def index(): return render_template("index.html", err_message="") # route requests for /fileprocess @app.route("/fileprocess", methods=["GET", "POST"]) def valid1(): if request.method == "POST": # make sure a file was actually chosen if request.files["kml"].filename != "": # save uploaded file kmlfile = request.files["kml"] kmlfile.seek(0) kml = kmlfile.read() # validate KML file
GX.AnimatedUpdate( GX.duration(2.0), KML.Update( KML.targetHref(), KML.Change( KML.Placemark(GX.balloonVisibility(0), targetId=feature['name'].replace(' ', '_')))))) # fly to a space viewpoint tour_doc.Document[gxns + "Tour"].Playlist.append( GX.FlyTo( GX.duration(5), GX.flyToMode("bounce"), KML.LookAt( KML.longitude(feature['lon']), KML.latitude(feature['lat']), KML.altitude(0), KML.heading(0), KML.tilt(0), KML.range(10000000.0), KML.altitudeMode("relativeToGround"), )), ) # check that the KML document is valid using the Google Extension XML Schema assert (Schema("kml22gx.xsd").validate(tour_doc)) print etree.tostring(tour_doc, pretty_print=True) # output a KML file (named based on the Python script) outfile = file(__file__.rstrip('.py') + '.kml', 'w') outfile.write(etree.tostring(tour_doc, pretty_print=True))
def points_to_kml_with_yattag(df_points, df_task, outdir, filename_base, disp): from yattag import Doc, indent from lxml import etree from pykml.parser import Schema doc, tag, text = Doc().tagtext() s_coords = task_to_string(df_points) #(lat, lon) = calculate_center(df_points) #doc.asis('<?xml version="1.0" encoding="UTF-8"?>') with tag('kml'): doc.attr(("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")) with tag('Document'): with tag('name'): text("Condor task '%s'" % filename_base) for i, tp in df_task.iterrows(): id = i + 1 with tag('Placemark'): with tag('name'): text("%d: %s" % (id, tp.Name)) with tag('description'): text(""" <dl> <dt>Lat: </dt><dd>{lat}</dd> <dt>Lon: </dt><dd>{lon}</dd> <dt>Alt: </dt><dd>{alt}</dd> </dl> <dl> <dt>Google search: </dt><dd><a href="https://www.google.fr/?#safe=off&q={name}">{name}</a></dd> </dl> """.format(lat=tp.Lat, lon=tp.Lon, alt=tp.Altitude, name=tp.Name)) with tag('Point'): with tag('coordinates'): text("%.5f,%.5f,%.1f" % (tp.Lon, tp.Lat, tp.Altitude)) with tag('Placemark'): #with tag('LookAt'): # with tag('longitude'): # text("%.5f" % lon) # with tag('latitude'): # text("%.5f" % lat) # with tag('heading'): # text("%d" % 0) # with tag('tilt'): # text("%d" % 60) # with tag('range'): # text("%d" % 80000) # with tag('gx:altitudeMode'): # text('relativeToSeaFloor') with tag('LineString'): # with tag('extrude'): # text("%d" % 1) # with tag('gx:altitudeMode'): # text('relativeToSeaFloor') with tag('coordinates'): text(s_coords) result = indent(doc.getvalue(), indentation=' ' * 4, newline='\r\n') if disp: print(result) filename_out = os.path.join(outdir, "trace_" + filename_base + '.kml') print("Output '%s'" % filename_out) outfile = file(filename_out, 'w') outfile.write(result) doc = etree.fromstring(result) assert Schema('kml22gx.xsd').validate(doc)
y="0", xunits="fraction", yunits="fraction"), ), balloonstyle, id="earthquake-style-{threshold}".format(threshold=threshold), )) doc.append(KML.Folder()) # read in a csv file, and create a placemark for each record url = "http://earthquake.usgs.gov/earthquakes/catalogs/eqs7day-M2.5.txt" fileobject = urllib.request.urlopen(url) for row in csv.DictReader(fileobject): timestamp = datetime.strptime(row["Datetime"], "%A, %B %d, %Y %H:%M:%S %Z") pm = KML.Placemark( KML.name("Magnitude={0}".format(row['Magnitude'])), KML.TimeStamp(KML.when(timestamp.strftime('%Y-%m-%dT%H:%M:%SZ')), ), KML.styleUrl("#earthquake-style-{thresh}".format( thresh=int(float(row['Magnitude'])))), makeExtendedDataElements(row), KML.Point(KML.coordinates("{0},{1}".format(row["Lon"], row["Lat"])))) doc.Folder.append(pm) # check if the schema is valid from pykml.parser import Schema schema_gx = Schema("kml22gx.xsd") schema_gx.assertValid(doc) print(etree.tostring(doc, pretty_print=True))