本文整理汇总了Python中simplekml.Kml类的典型用法代码示例。如果您正苦于以下问题:Python Kml类的具体用法?Python Kml怎么用?Python Kml使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Kml类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exportToKml2
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")
示例2: density_kml
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)
示例3: test_kml_simple
def test_kml_simple(self):
coordinates = [
(-76.0, 38.0, 0.0),
(-76.0, 38.0, 10.0),
(-76.0, 38.0, 20.0),
(-76.0, 38.0, 30.0),
(-76.0, 38.0, 100.0),
(-76.0, 38.0, 30.0),
(-76.0, 38.0, 60.0),
]
# Create Coordinates
start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
start.save()
for coord in coordinates:
self.create_log_element(*coord)
end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
end.save()
kml = Kml()
UasTelemetry.kml(user=self.user,
logs=UasTelemetry.by_user(self.user),
kml=kml,
kml_doc=kml)
for coord in coordinates:
tag = self.coord_format.format(coord[1], coord[0],
units.feet_to_meters(coord[2]))
self.assertTrue(tag in kml.kml())
示例4: exportToKml
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")
示例5: test_kml_filter
def test_kml_filter(self):
coordinates = [
(-76.0, 38.0, 0.0),
(-76.0, 38.0, 10.0),
(-76.0, 38.0, 20.0),
(-76.0, 38.0, 30.0),
(-76.0, 38.0, 100.0),
(-76.0, 38.0, 30.0),
(-76.0, 38.0, 60.0),
]
filtered_out = [(0.1, 0.001, 100), (0.0, 0.0, 0)]
# Create Coordinates
start = TakeoffOrLandingEvent(user=self.user, uas_in_air=True)
start.save()
for coord in coordinates:
self.create_log_element(*coord)
for coord in filtered_out:
self.create_log_element(*coord)
end = TakeoffOrLandingEvent(user=self.user, uas_in_air=False)
end.save()
kml = Kml()
UasTelemetry.kml(user=self.user,
logs=UasTelemetry.by_user(self.user),
kml=kml,
kml_doc=kml)
for filtered in filtered_out:
tag = self.coord_format.format(filtered[1], filtered[0],
filtered[2])
self.assertTrue(tag not in kml.kml())
for coord in coordinates:
tag = self.coord_format.format(coord[1], coord[0], coord[2])
self.assertTrue(tag in kml.kml())
示例6: create_kml
def create_kml(start_dt, traces):
mintime = datetime(2100,1,1)
maxtime = datetime(1901,1,1)
bbox_nw = (sys.maxint, sys.maxint)
bbox_se = (-sys.maxint, -sys.maxint)
kml = Kml(name="Tracer")
doc = kml.newdocument()
fol = doc.newfolder(name="Traces")
i = 0
for id_, trace in traces:
trace = list(trace)
trk = fol.newgxtrack(name='Trace id: %s' % id_)
times = [start_dt + timedelta(seconds=int(p['time'])) for p in trace]
trk.newwhen([format_date(t) for t in times])
places = [
(float(p['lon']), float(p['lat']), 0)
for p in trace
]
trk.newgxcoord(places)
m = min(places, key=operator.itemgetter(0))
if m[0] < bbox_nw[0] and not (m[0] == 0.0 or m[1] == 0.0):
bbox_nw = m[:2]
m = max(places, key=operator.itemgetter(0))
if m[0] > bbox_se[0] and not (m[0] == 0.0 or m[1] == 0.0):
bbox_se = m[:2]
mintime = min([mintime] + times)
maxtime = max([maxtime] + times)
trk.altitudemode = 'relativeToGround'
trk.stylemap.normalstyle.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png'
trk.stylemap.normalstyle.linestyle.color = CATEGORICAL_COLORS[i % len(CATEGORICAL_COLORS)]
trk.stylemap.normalstyle.linestyle.width = 5
trk.stylemap.normalstyle.labelstyle.scale = 1
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 = CATEGORICAL_COLORS[i % len(CATEGORICAL_COLORS)]
trk.stylemap.highlightstyle.linestyle.width = 8
i += 1
doc.lookat.gxtimespan.begin = format_date(mintime)
doc.lookat.gxtimespan.end = format_date(maxtime)
doc.lookat.longitude = bbox_nw[0] + (bbox_se[0] - bbox_nw[0]) / 2
doc.lookat.latitude = bbox_nw[1] + (bbox_se[1] - bbox_nw[1]) / 2
doc.lookat.range = 13000.00
#doc.lookat.longitude, doc.lookat.latitude = list(list(traces)[0][1])[0]
return kml.kml()
示例7: make_kml
def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,
figs, colorbar=None, **kw):
"""TODO: LatLon bbox, list of figs, optional colorbar figure,
and several simplekml kw..."""
kml = Kml()
altitude = kw.pop('altitude', 1e0) #2e7)
roll = kw.pop('roll', 0)
tilt = kw.pop('tilt', 0)
altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
longitude=np.mean([urcrnrlon, llcrnrlon]),
altitude=altitude, roll=roll, tilt=tilt,
altitudemode=altitudemode)
kml.document.camera = camera
draworder = 0
for fig in figs: # NOTE: Overlays are limited to the same bbox.
draworder += 1
ground = kml.newgroundoverlay(name='GroundOverlay')
ground.draworder = draworder
ground.visibility = kw.pop('visibility', 1)
ground.name = kw.pop('name', 'overlay')
#ground.color = kw.pop('color', '9effffff') ##kw.pop('color', '9effffff')
ground.atomauthor = kw.pop('author', 'PyHum')
ground.latlonbox.rotation = kw.pop('rotation', 0)
ground.description = kw.pop('description', 'Matplotlib figure')
ground.gxaltitudemode = kw.pop('gxaltitudemode',
'clampToSeaFloor')
ground.icon.href = fig
ground.latlonbox.east = llcrnrlon
ground.latlonbox.south = llcrnrlat
ground.latlonbox.north = urcrnrlat
ground.latlonbox.west = urcrnrlon
if colorbar: # Options for colorbar are hard-coded (to avoid a big mess).
screen = kml.newscreenoverlay(name='ScreenOverlay')
screen.icon.href = colorbar
screen.overlayxy = OverlayXY(x=0, y=0,
xunits=Units.fraction,
yunits=Units.fraction)
screen.screenxy = ScreenXY(x=0.015, y=0.075,
xunits=Units.fraction,
yunits=Units.fraction)
screen.rotationXY = RotationXY(x=0.5, y=0.5,
xunits=Units.fraction,
yunits=Units.fraction)
screen.size.x = 0
screen.size.y = 0
screen.size.xunits = Units.fraction
screen.size.yunits = Units.fraction
screen.visibility = 1
kmzfile = kw.pop('kmzfile', 'overlay.kmz')
kml.savekmz(kmzfile)
示例8: from_locations
def from_locations(self, doc_name, track_name, locations):
when = {}
for l in locations:
try:
if(l.bssid not in when):
when[l.bssid]=[]
when[l.bssid].append({"time": l.time.strftime("%Y-%m-%dT%H:%M:%SZ-05:00"), "coords": (l.lon,l.lat)})
except:
continue
kml = Kml(name=doc_name)
doc = kml.newdocument(name=track_name)
示例9: writekml
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)
示例10: make_kml
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)
示例11: __init__
def __init__(self, line_limit_point, pathDirectory):
self.kml = Kml()
self.init()
self.kml_interest_line_already_meeted = {}
self.kml_interest_point_already_meeted = {}
self.line_limit_point = line_limit_point
self.pathDirectory = pathDirectory
self.midday = (12,0,)
示例12: from_networks
def from_networks(self, doc_name, networks):
kml = Kml(name=doc_name)
for n in networks:
p = kml.newpoint(name=str(n))
p.coords=[(n.lastlon,n.lastlat)]
if(not n._lasttime):
lasttime = "<i>None</i>"
else:
lasttime = n.formated_lasttime
p.timestamp.when = n.lasttime.strftime("%Y-%m-%dT%H:%M:%SZ-05:00")
if(not n.frequency):
frequency = "<i>None</i>"
else:
frequency = "%s MHz" % n.frequency
p.description = self._network_format % {"bssid": n.bssid, "ssid": (n.ssid or "<i>None</i>"), "capabilities": n.capabilities, "frequency": frequency, "lasttime": lasttime}
return kml
示例13: convert
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()
示例14: Kml
car["gps"].append((longitude[i], latitude[i], 0))
# In[31]:
from simplekml import Kml, Model, AltitudeMode, Orientation, Scale, Style, Color
# In[32]:
# The model path and scale variables
car_dae = r'https://raw.githubusercontent.com/balzer82/Kalman/master/car-model.dae'
car_scale = 1.0
# Create the KML document
kml = Kml(name=d.strftime("%Y-%m-%d %H:%M"), open=1)
# Create the model
model_car = Model(altitudemode=AltitudeMode.clamptoground,
orientation=Orientation(heading=75.0),
scale=Scale(x=car_scale, y=car_scale, z=car_scale))
# Create the track
trk = kml.newgxtrack(name="EKF", altitudemode=AltitudeMode.clamptoground,
description="State Estimation from Extended Kalman Filter with CTRA Model")
# Attach the model to the track
trk.model = model_car
trk.model.link.href = car_dae
# Add all the information to the track
示例15: sortNneaList
UIDtoColor = {"E016246604C06B7A" : "http://maps.gstatic.com/mapfiles/ms2/micons/red-dot.png",
"E016246604C06BA0" : "http://maps.gstatic.com/mapfiles/ms2/micons/blue-dot.png",
"E016246604C070DE" : "http://maps.gstatic.com/mapfiles/ms2/micons/yellow-dot.png",
"E016246604C0862C" : "http://maps.gstatic.com/mapfiles/ms2/micons/green-dot.png",
"E016246604C0938B" : "http://maps.gstatic.com/mapfiles/ms2/micons/pink-dot.png",
"E016246604C05492" : "http://maps.gstatic.com/mapfiles/ms2/micons/ltblue-dot.png",
"E016246604C09352" : "http://maps.gstatic.com/mapfiles/ms2/micons/orange-dot.png",
"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