本文整理匯總了Python中simplekml.Kml.save方法的典型用法代碼示例。如果您正苦於以下問題:Python Kml.save方法的具體用法?Python Kml.save怎麽用?Python Kml.save使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類simplekml.Kml
的用法示例。
在下文中一共展示了Kml.save方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: density_kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def density_kml(kml_path, city, dicts, borders,
scaling=(lambda x: x)):
def rgb_to_bgr(color):
return "{rgb[4]}{rgb[5]}{rgb[2]}{rgb[3]}{rgb[0]}{rgb[1]}".format(
rgb=color)
def add_folder(kml, data):
def cell_to_color(value, color, scaling):
norm_value = scaling(value)
return '{0:02x}{1}'.format(int(norm_value * 200), color)
folder_dict = data['dict']
# normalizing
maximum = data['max']
norm_scaling = lambda x: scaling(x / maximum)
# make a kml of polygons
folder = kml.newfolder(name=data['name'])
color = rgb_to_bgr(data['color'])
folder = dict_to_kml(folder, borders, folder_dict, cell_to_color,
color, norm_scaling)
return kml
kml = Kml()
for data in dicts:
kml = add_folder(kml, data)
kml.save(kml_path)
示例2: exportToKml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def exportToKml() :
# KML
kml = Kml()
for aMergedWayTupleKey in tramRoutes :
aMergedWayTuple = tramRoutes[aMergedWayTupleKey]
aMergedWay = aMergedWayTuple[1]
lineNames = ','.join(aMergedWayTuple[0])
coords = list()
for aCoordTuple in aMergedWay :
lat = aCoordTuple[0]
lon = aCoordTuple[1]
coords.append((lon,lat))
lin = kml.newlinestring(name="Pathway", description='-', coords= coords)
r = lambda: random.randint(0,255)
randomColor = '#ff%02X%02X%02X' % (r(),r(),r())
lin.style.linestyle.color = randomColor
lin.style.linestyle.width= 10 # 10 pixels
kml.save("singlestyle.kml")
示例3: exportToKml2
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def exportToKml2() :
# KML
kml = Kml()
for aGroupedWayKey in subRoutes :
aGroupedWay = subRoutes[aGroupedWayKey][0]
lineNames = ','.join(aGroupedWay.lines)
coords = list()
for aNodeKey in aGroupedWay.nodesList :
if type(aNodeKey) is str :
aNode = nodesDict[aNodeKey]
lat = aNode.lat
lon = aNode.lon
elif type(aNodeKey) is OsmNode:
lat = aNodeKey.lat
lon = aNodeKey.lon
else :
lat = aNodeKey[0]
lon = aNodeKey[1]
coords.append((lon,lat))
lin = kml.newlinestring(name="Pathway", description='-', coords= coords)
r = lambda: random.randint(0,255)
randomColor = '#ff%02X%02X%02X' % (r(),r(),r()) #random ARGB color
lin.style.linestyle.color = randomColor
lin.style.linestyle.width= 10 # 10 pixels
kml.save("singlestyle.kml")
示例4: writekml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def writekml(inarray, kmlfilename):
kml = Kml()
sharedstyle = Style()
sharedstyle.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/wht-blank.png'
sharedstyle.iconstyle.color = "ffffffff"
sharedstyle.iconstyle.ColorMode = "random"
for indiv in numpy.nditer(inarray):
desc = adddescription(indiv)
lat =float(indiv[()]['Lat'])
lon =float(indiv[()]['Long'])
pnt = kml.newpoint(name=str(indiv[()]['GivenNames']) + " " +str(indiv[()]['FamilyName']), description=desc,
coords = [(lon,lat)])
pnt.style = sharedstyle
kml.save(kmlfilename)
示例5: make_kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def make_kml(parsed_users, output_file, verbosity):
"""This function reads the user data supplied by ``parsed_users``, it then generates
KML output and writes it to ``output_file``.
Args:
parsed_users (list): A list of lists, each sub_list should have 4 elements: ``[latitude, longitude, name, comment]``
output_file (open): Location to save the KML output
verbosity (int): If set to be >= ``1`` it will print out the string passed to ``message()``
"""
kml = Kml()
message("Making and writing KML to " + output_file, verbosity)
for user in parsed_users:
# Generate a KML point for the user.
kml.newpoint(name=user[2], coords=[(user[1], user[0])], description=user[3])
kml.save(output_file)
示例6: convert
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def convert(self, output):
output_filename = '{}.{}'.format(KMLParser.RESULT_FILENAME, output)
if output in ['kml', 'kmz']: #check if value is in a list
kmlinstance = Kml()
folder = kmlinstance.newfolder()
folder.name = "My Places"
for name, lat, lon in self.content:#tuples can be decomposed in a for loop. This is the same as "for (x,y,z) in self.content" or "for t in self.content" and then using t[0] etc.
folder.newpoint(name=name, coords=[(lat,lon)])
kmlinstance.save( output_filename )
elif output in ['terminal', 'txt']:
newcontent = [ '%s\t->\t%.4f %.4f'%(name, float(lat),float(lon)) for name, lat, lon in self.content ] #list comprehensions rock!!
if output == 'txt':
f = open(output_filename, 'w')
f.write( '\n'.join(newcontent) )
f.close()
elif output is 'terminal':
print '\n'.join(newcontent)
elif output == 'json':
newcontent = [ {'name': name, 'coordinates': {'latitude':lat, 'longitude':lon} } for name, lat, lon in self.content ]
f = open(output_filename, 'w')
json.dump(newcontent, f, indent=2)
f.close()
示例7: sortNneaList
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
"E0162466025BF373" : "http://maps.gstatic.com/mapfiles/ms2/micons/purple-dot.png"}
def sortNneaList(x,y):
return int( (x.dateEvent.newTime - y.dateEvent.newTime).total_seconds() ) #warning, this method don care about milli and microseconds
nmeaLogs = sorted(nmeaLogs,cmp=sortNneaList)
from simplekml import Kml
kml = Kml()
currentNmeaLogDate = None
for nmeaLog in nmeaLogs:
if currentNmeaLogDate == None:
currentNmeaLogDate = nmeaLog.dateEvent.newTime
elif nmeaLog.dateEvent.newTime.day != currentNmeaLogDate.day or nmeaLog.dateEvent.newTime.month != currentNmeaLogDate.month or nmeaLog.dateEvent.newTime.year != currentNmeaLogDate.year:
kml.save(kmlDirectory+"skidump_"+str(currentNmeaLogDate.day)+"_"+str(currentNmeaLogDate.month)+"_"+str(currentNmeaLogDate.year)+".kml")
currentNmeaLogDate = nmeaLog.dateEvent.newTime
kml = Kml()
tab = []
firstPos = None
for position in nmeaLog.NewPosition:
if firstPos == None:
firstPos = position
#ne pas mettre les 0.0
if position.longitude == 0.0 and position.latitude == 0.0:
continue
tab.append( ( position.longitude,position.latitude) )
示例8:
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
# Create a schema for extended data: heart rate, cadence and power
schema = kml.newschema()
schema.newgxsimplearrayfield(name='heartrate', type=Types.int, displayname='Heart Rate')
schema.newgxsimplearrayfield(name='cadence', type=Types.int, displayname='Cadence')
schema.newgxsimplearrayfield(name='power', type=Types.float, displayname='Power')
# Create a new track in the folder
trk = fol.newgxtrack(name='2010-05-28T01:16:35.000Z')
# Apply the above schema to this track
trk.extendeddata.schemadata.schemaurl = schema.id
# Add all the information to the track
trk.newwhen(when) # Each item in the give nlist will become a new <when> tag
trk.newgxcoord(coord) # Ditto
trk.extendeddata.schemadata.newgxsimplearraydata('heartrate', heartrate) # Ditto
trk.extendeddata.schemadata.newgxsimplearraydata('cadence', cadence) # Ditto
trk.extendeddata.schemadata.newgxsimplearraydata('power', power) # Ditto
# Styling
trk.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
trk.stylemap.normalstyle.linestyle.color = '99ffac59'
trk.stylemap.normalstyle.linestyle.width = 6
trk.stylemap.highlightstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
trk.stylemap.highlightstyle.iconstyle.scale = 1.2
trk.stylemap.highlightstyle.linestyle.color = '99ffac59'
trk.stylemap.highlightstyle.linestyle.width = 8
# Save the kml to file
kml.save("GxTrack.kml")
示例9: convert_to_html
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
for lon in lons:
for lat in lats:
model_results = model.get_point(lat, lon)
result_html = convert_to_html(model_results)
pnt = fol.newpoint()
pnt.name = "CRUST 1.0 (%.1f,%.1f)" % (lat, lon)
pnt.description = result_html
pnt.coords = [(lon, lat)]
pnt.style = style
# Save the KML
print "Writing KML file..."
outfile = 'CRUST_1.0'
kml.save('../%s.kml' % outfile)
# Try to compress it to KMZ, if we can, the delete the kml, otherwise
# we're done and we'll show a message indicating the outcome. zlib is
# required for this, otherwise the file size won't be reduced
try:
import zlib
compression = zipfile.ZIP_DEFLATED
print "zlib present: will be stored in compressed format"
except:
compression = zipfile.ZIP_STORED
print "zlib not present: will be stored in uncompressed format"
with zipfile.ZipFile('../%s.kmz' % outfile, 'w') as zf:
print "Zipping KML file to KMZ..."
zf.write('../%s.kml' % outfile, compress_type=compression)
示例10: csv_to_kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def csv_to_kml(input_filename):
# open input file
csv_file = open(input_filename,'rU')
reader = csv.DictReader(csv_file)
# preamble
input_filename_base, input_filename_ext = os.path.splitext(input_filename)
# open output file
kml_file = open(input_filename_base + '.kml','w')
kml_file.write(r"""<?xml version="1.0" encoding="utf-8" ?>
<kml xmlns="http://www.opengis.net/kml/2.2">
""")
kml_file.write("<Document><name>%s</name>" % input_filename_base)
kml_file.write(r""" <Style id="grid1k"><IconStyle> <Icon> <color>ff0000</color> </Icon> </IconStyle></Style>""")
kml_file.write(r"""
<Schema name="sample" id="sample">
<SimpleField name="Name" type="string"></SimpleField>
<SimpleField name="Description" type="string"></SimpleField>
<SimpleField name="GID" type="string"></SimpleField>
</Schema>
""")
gids_unique = set()
gids = []
locs_1k = []
# main loop
for line in reader:
kml_file.write(' <Placemark>\n')
kml_file.write(' <name>GID=%s</name>\n' % (line['GID_100m']))
kml_file.write('\t<ExtendedData><SchemaData schemaUrl=\"#sample\">\n')
kml_file.write(' <SimpleField name="GID">%s</SimpleField>\n' % (line['GID_100m']))
kml_file.write('\t\t</SchemaData></ExtendedData>\n')
kml_file.write(" <Point><coordinates>%s,%s</coordinates></Point>\n" % (line['x'], line['y']))
kml_file.write(' </Placemark>\n')
gids_unique.add(line['GID_1k'])
gids.append(line['GID_1k'])
locs_1k.append([line['x_1k'], line['y_1k']])
# epilogue
kml_file.write('\t</Document>\n\t</kml>')
csv_file.close()
kml_file.close()
gids_unique = list(gids_unique)
locs_1k_unique = []
for gid in gids_unique:
locs_1k_unique.append([locs_1k[k] for k, x in enumerate(map(lambda x: x==gid, gids)) if x][0])
for i, loc in enumerate(locs_1k_unique):
kml=Kml()
proj_para = "+proj=laea +ellps=WGS84 +lon_0=20 +lat_0=5 +units=m +no_defs"
project = pyproj.Proj(proj_para)
loc_laea = list(project(loc[0], loc[1]))
center_pt = kml.newpoint(name=gids_unique[i], description="1k by 1k grid", coords=[(loc[0], loc[1])])
pol = kml.newpolygon(name="1k grid", description="A pathway in Kirstenbosch",
outerboundaryis=[project(loc_laea[0]-500, loc_laea[1]+500, inverse=True),
project(loc_laea[0]+500, loc_laea[1]+500, inverse=True),
project(loc_laea[0]+500, loc_laea[1]-500, inverse=True),
project(loc_laea[0]-500, loc_laea[1]-500, inverse=True),
project(loc_laea[0]-500, loc_laea[1]+500, inverse=True)],
innerboundaryis=[project(loc_laea[0]-500, loc_laea[1]+500, inverse=True),
project(loc_laea[0]+500, loc_laea[1]+500, inverse=True),
project(loc_laea[0]+500, loc_laea[1]-500, inverse=True),
project(loc_laea[0]-500, loc_laea[1]-500, inverse=True),
project(loc_laea[0]-500, loc_laea[1]+500, inverse=True)])
pol.polystyle.color = 'ff0000ff'
kml.save("csv/"+gids_unique[i]+".kml")
示例11: list
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
#!/usr/bin/python
from simplekml import Kml
import sys
in_file, out_file = sys.argv[1], sys.argv[2];
data = list()
kml = Kml(name = in_file, open = 1)
with open(in_file) as file:
lines = file.readlines()
for x in lines:
# Ignore lines that start with "//".
if x.startswith("//"):
continue
elements = x.split(",")[:3]
group = tuple(elements)
data.append(group)
path = kml.newlinestring(name = "Flight", description = in_file, coords = data)
path.altitudemode = "absolute"
path.extrude = 1
path.style.polystyle.color = "7fff575c"
kml.save(out_file)
示例12: main
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
def main():
parser = argparse.ArgumentParser()
parser.add_argument("pcap", help="path pcap file")
parser.add_argument("-o", "--output", help="Output directory (must already exist)", default="./")
parser.add_argument("-d", "--database", help="Database filename", default="sqlite.db")
parser.add_argument("-k", "--kml", help="KML filename", default="results.kml")
parser.add_argument("-r", "--report", help="Report filename", default="report.txt")
args = parser.parse_args()
# Check if pcap is a valid file
if not os.path.exists(args.pcap):
print "Invalid pcap file. Quitting."
exit(1)
# Check if output path is a valid file
if not os.path.exists(args.output):
print "Invalid output path. Quitting."
exit(1)
### READ PCAP FILE ###
pcap = rdpcap(args.pcap)
files = extract_jpgs(pcap, args.output)
### INITIALIZE DATABASE ###
conn = initdb(os.path.join(args.output,args.database))
### INITIALIZE KML ###
kml = Kml(name=args.kml)
for fname in files:
### EXTRACT EXIF DATA ###
print "[+] Extracting exif data from " + fname
image = Image.open(fname)
exif = extract_exif(conn, image)
### GET MD5 ###
md5hash = get_md5(os.path.basename(fname))
print "[+] Getting md5 hash for " + os.path.basename(fname) + " => " + md5hash
### INSERT INTO DATABASE ###
print "[+] Inserting record into database for " + fname
insert_record(conn, os.path.basename(fname), md5hash, simplejson.dumps(exif))
### WRITE GPS INFO TO KML ###
if exif["GPSInfo"]:
latitude, longitude = get_lat_long(exif['GPSInfo'])
print "[+] Writing GPS info (%s, %s) to KML for %s" % (longitude, latitude, os.path.basename(fname))
descr = '%s, %s' % ( longitude, latitude )
kml.newpoint(name=os.path.basename(fname),
description=descr,
coords=[(longitude, latitude)])
### SAVE KML TO FILE ###
print "[+] Saving KML file to " + os.path.join(args.output, args.kml)
kml.save(os.path.join(args.output, args.kml))
### GENERATE REPORT ###
print "[+] Generating final report as " + os.path.join(args.output, args.report)
with open(os.path.join(args.output, args.report), 'w') as r:
now = strftime("%Y-%m-%d %H:%M:%S", gmtime())
r.write("<==== Extraction Results ====>\n")
r.write("Filename: %s\n" % args.pcap)
r.write("Timestamp: %s GMT \n\n" % now)
for row in conn.execute("SELECT * FROM results"):
r.write("===================\n")
r.write("Image: %s\n" % row[0])
r.write("MD5 Hash: %s\n" % row[1])
if row[2] and row[2] != "null":
r.write("EXIF data:\n")
json = simplejson.loads(row[2])
for i in json:
r.write("\t%s: %s\n" % (i, json[i]))
if i == "GPSInfo":
latitude, longitude = get_lat_long(json['GPSInfo'])
r.write("\t%s (translated): %s, %s\n" % (i, latitude, longitude))
else:
r.write("No EXIF data found\n")
r.write("===================\n\n")
conn.close()
示例13: exit
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
# Check if path is valid directory or file
if not os.path.exists(args.path):
print "Invalid path. Quitting."
exit(1)
# Handle single JPG file or directory of JPG files
if args.directory:
files = [os.path.join(args.path, f) for f in os.listdir(args.path) if re.match(r'[A-Za-z0-9-_]+.*\.(jpg|JPG)$', f)]
else:
files = [ args.path ]
### EXTRACT GPS DATA AND BUILD KML ###
kml = Kml(name=args.name)
cnt = 0
for fname in files:
image = Image.open(fname)
exif = extract_gpsinfo_from_image(image)
latitude, longitude = get_lat_long(exif['GPSInfo'])
print 'Adding %s at %s, %s...' % ( os.path.basename(fname), longitude, latitude )
descr = '%s, %s' % ( longitude, latitude )
kml.newpoint(name=os.path.basename(fname),
description=descr,
coords=[(longitude, latitude)])
cnt = cnt + 1
kml.save(args.output)
#print kml.kml()
print '\nSuccessfully parsed %s files and generated %s' % ( cnt, args.output )
示例14: createRoute
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
#.........這裏部分代碼省略.........
coord[i].append([(x / size), (x % size)])
x += 1
ac = 0
route = []
# Create an optimal route using the A* algorithm following the TSP
for i in range(nAreas):
n, D = mk_matrix(coord[i], distL2)
tour = nearest_neighbor(n, (((nearPoint[i][0] * size)-ac) + nearPoint[i][1]), D)
for j in range(len(tour)):
tmpValue = tour[j] + (size - len(searchArea[i][0]))
col = tmpValue / size
if col == 0 and i > 0:
row = (tmpValue % size) - (size - len(searchArea[i][0]))
if DEBUG:
print(str(tour[j]) + " = " + str(col) + "," + str((tmpValue % size) - (size - len(searchArea[i][0]))))
else:
row = tmpValue % size
if DEBUG:
print(str(tour[j])+" = "+str(col)+","+str(tmpValue % size))
tour[j] = searchArea[i][col][row]
ac += len(coord[i])
route.append(tour)
m = Mission()
m.save()
for userId in range(0, len(userPK)):
m.inSearch.add(Clients.objects.get(pk=userPK[userId]))
try:
drones = Drone.objects.all()[0]
except:
print colored("Oops! No drones found un database", 'red')
return HttpResponse('configerror')
colorArray = [
'ff00008b', # darkred
'ff8b0000', # darkblue
'ff006400', # darkgreen
'ff008cff', # darkorange
'ff9314ff', # darkpink
'ffff0000', # blue
'ff2fffad', # greenyellow
'ff5c5ccd', # indianred
'ffcbc0ff', # pink
'ffe16941', # royalblue
'ff00ffff', # yellow
]
drone_secuencial = 0
# Creates the KML file
from os import mkdir
for r in route:
rm = Route(mission=m, drone=Drone.objects.all()[drone_secuencial], baseLat=base[0], baseLng=base[1], initialWp=0)
rm.save()
示例15: Kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import save [as 別名]
#Converts to KML
kml = Kml()
#folder = kml.newfolder(name="Gliders")
#Defines the kmnl document name
kml.document.name = "GliderProfile"
#Makes a list of styles
stylelist = []
for i in range(len(col)-1):
#if (ma.getmask(x[idx]) == False and ma.getmask(y[idx]) == False and
# ma.getmask(z[idx]) == False and ma.getmask(col[idx]) == False):
sharedstyle = Style()
sharedstyle.linestyle.color = str(colorValHex[i])
sharedstyle.linestyle.width = 10
stylelist.append(sharedstyle)
#Looops over all
for i in range(len(col)-1):
#if (ma.getmask(x[idx]) == False and ma.getmask(y[idx]) == False and
# ma.getmask(z[idx]) == False and ma.getmask(col[idx]) == False):
print x[i],y[i],colorValHexKML[i],-z[i]
lin = kml.newlinestring(name='',description='',coords=[(x[i],y[i],-z[i]),(x[i+1],y[i+1],-z[i+1])])
lin.style.linestyle.color = str(colorValHexKML[i]) #stylelist[i]
lin.style.linestyle.width = 10 #50 pixels
lin.altitudemode = simplekml.AltitudeMode.absolute
kml.save("C:\Users\john.tenhoeve\Documents\stest3.kml")