本文整理匯總了Python中simplekml.Kml.newpoint方法的典型用法代碼示例。如果您正苦於以下問題:Python Kml.newpoint方法的具體用法?Python Kml.newpoint怎麽用?Python Kml.newpoint使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類simplekml.Kml
的用法示例。
在下文中一共展示了Kml.newpoint方法的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: make_kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [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)
示例2: writekml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [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)
示例3: from_networks
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
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
示例4: Kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
Styling points, linestrings, polygons and TOC items.
"""
import os
from simplekml import Kml, ListItemType, Color
kml = Kml(name="Styling", open=1)
# Make all the items into radio buttons
kml.document.liststyle.listitemtype = ListItemType.radiofolder
# Change the icon of the document in the TOC
kml.document.liststyle.itemicon.href = "http://maps.google.com/mapfiles/kml/shapes/parks.png"
# A normal Point with both a LabelStyle and IconStyle
pnt = kml.newpoint(name="Kirstenbosch Normal", description="A style map.", coords=[(18.431486,-33.988)])
pnt.labelstyle.color = 'ff0000ff'
pnt.labelstyle.scale = 2 # Text twice as big
pnt.labelstyle.color = "ffff0000"
pnt.iconstyle.color = 'ffff0000' # Blue
pnt.iconstyle.scale = 3 # Icon thrice as big
pnt.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/info-i.png' # Culry 'information i
# A Point with a styleMap. The Text changes from blue to red on mouse over.
pnt = kml.newpoint(name="Kirstenbosch StyleMap", coords=[(18.432314,-33.988862)])
pnt.stylemap.normalstyle.labelstyle.color = 'ffff0000'
pnt.stylemap.highlightstyle.labelstyle.color = 'ff0000ff'
# A red thick LineString
lin = kml.newlinestring(name="Pathway", description="A pathway in Kirstenbosch",
coords=[(18.43312,-33.98924), (18.43224,-33.98914), (18.43144,-33.98911), (18.43095,-33.98904)])
示例5: or
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
if firstPos.newTime.hour < 12 or (firstPos.newTime.hour == 12 and firstPos.newTime.minute < 30):
#blue line
line.style.linestyle.color = 'ffff0000'
else:
#red line
line.style.linestyle.color = 'ff0000ff'
if nmeaLog.dumpLog != None :
for dumpFile in nmeaLog.dumpLog.dumps:
if dumpFile.latitude == None or dumpFile.longitude == None or (dumpFile.latitude == 0.0 and dumpFile.longitude == 0.0):
continue
dumpTime = str(dumpFile.dumpEvent.newTime.hour)+":"+str(dumpFile.dumpEvent.newTime.minute)+":"+str(dumpFile.dumpEvent.newTime.second)
point = kml.newpoint(name="dump_"+str(dumpFile.UID)+"_"+dumpTime, description="",coords=[(dumpFile.longitude,dumpFile.latitude)])
if dumpFile.UID in UIDtoColor:
point.style.iconstyle.icon.href = UIDtoColor[dumpFile.UID]
else:
print " warning unknown UID : "+str(dumpFile.UID)
else:
print " warning, no dumpLog linked to "+str(nmeaLog)
kml.save(kmlDirectory+"skidump_"+str(currentNmeaLogDate.day)+"_"+str(currentNmeaLogDate.month)+"_"+str(currentNmeaLogDate.year)+".kml")
###### build a file with all the cable car #######################################################################
kml = Kml()
for line in lineList:
示例6: Kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
"""
This shows the use of the 3 different types of extended data: Data, Simple Data and Simple Array Data, as well as prettying up the data.
"""
import os
from simplekml import Kml, Types, Snippet, Color
# The KML
kml = Kml(name="ExtendedData", open=1)
# Data Example---------------------------------------------------------------------------------------------------------
# Create and style a point
pnt = kml.newpoint(name='1. World of Birds (Data)', coords =[(18.361960,-34.016543)])
pnt.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/1.png'
# Add the Data to the point
pnt.extendeddata.newdata(name='birds', value=400, displayname="Bird Species")
pnt.extendeddata.newdata(name='aviaries', value=100, displayname="Aviaries")
pnt.extendeddata.newdata(name='visitors', value=10000, displayname="Annual Visitors")
# Simple Data Example -------------------------------------------------------------------------------------------------
# Create a schema
schema = kml.newschema(name='WOW')
schema.newsimplefield(name='birds', type='int', displayname='Bird Species')
schema.newsimplefield(name='aviaries', type='int', displayname='Aviaries')
schema.newsimplefield(name='visitors', type='int', displayname='Annual Visitors')
# Create and style a point
pnt = kml.newpoint(name='2. World of Birds (Simple Data)', coords =[(18.361960,-34.017224)])
示例7: csv_to_kml
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [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")
示例8: kmlManager
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
class kmlManager(object):
def init(self):
self.kml_list_start_time = None
self.kml_list = []
self.kml_interest_line_list = []
self.kml_interest_point_list = []
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,)
def addPointOfInterest(self,point):
if point.descr not in self.kml_interest_point_already_meeted: #not yet printed ?
self.kml_interest_point_already_meeted[point.descr] = True
self.kml_interest_point_list.append(point)
def addLineOfInterest(self, line):
if line.descr not in self.kml_interest_line_already_meeted: #not yet printed ?
self.kml_interest_line_already_meeted[line.descr] = True
self.kml_interest_line_list.append(line)
def addLinePoint(self,gpoint, utcdatetime, colorMarker):
if self.line_limit_point > 0:#don't want to write the line of the road ?
if len(self.kml_list) == 0: #set start time
self.kml_list_start_time = utcdatetime
self.kml_list.append( (gpoint.lat, gpoint.lon,) )
if len(self.kml_list) >= self.line_limit_point:
#kml process
if len(self.kml_list) > 0:
line = self.kml.newlinestring(name="From "+self.kml_list_start_time.isoformat()+" to "+utcdatetime.isoformat(), description="", coords=self.kml_list)
#if past midday, colour the line in red
if utcdatetime.hour < self.midday[0] or (utcdatetime.hour == self.midday[0] and utcdatetime.minute < self.midday[1]):
line.style.linestyle.color = 'afff0000'#morning, blue line
else:
line.style.linestyle.color = 'af0000ff'#afternoon, red line
#write the meeted line of interest
for interest_line in self.kml_interest_line_list:
#line
line = self.kml.newlinestring(name=interest_line.descr, description="", coords=((interest_line.start.lat,interest_line.start.lon,), (interest_line.end.lat,interest_line.end.lon,),))
line.style.linestyle.color = 'af00ff00' #green
#start point
point = self.kml.newpoint(name="Start point of "+interest_line[2], description="",coords=(interest_line.start.lat,interest_line.start.lon,))
point.style.iconstyle.icon.href = "http://maps.google.com/mapfiles/dd-start.png"
#end point
point = self.kml.newpoint(name="End point of "+interest_line[2], description="",coords=(interest_line.end.lat,interest_line.end.lon,))
point.style.iconstyle.icon.href = "http://maps.google.com/mapfiles/dd-end.png"
#write the meeted point of interest
for interest_point in self.kml_interest_point_list:
point = self.kml.newpoint(name=interest_point.name, description=interest_point.descr,coords=( (interest_point.lat, interest_point.lon,), ))
point.style.iconstyle.icon.href = colorMarker.getColorPath(interest_point.name)
#save the file (for every line written, overwrite the file)
date = datetime.datetime.now()
self.kml.save(self.pathDirectory+"skidump_"+str(date.day)+"_"+str(date.month)+"_"+str(date.year)+".kml")
#reset list
self.init()
def addEventPointList(self,l):
#get point of interest from proxy
self.kml_interest_point_list.extend(l)
示例9: main
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [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()
示例10: exit
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [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 )
示例11: createRoute
# 需要導入模塊: from simplekml import Kml [as 別名]
# 或者: from simplekml.Kml import newpoint [as 別名]
#.........這裏部分代碼省略.........
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()
tmpRoute = []
tmpCounter = 0
kmlName = 'IBRI' + str(m.id) + 'R' + str(rm.id)
kml = Kml(name=kmlName)
kml.newpoint(name="Base", coords=[(base[1], base[0])])
pnt = kml.newlinestring(name='Route {}'.format(tmpCounter))
coords = []
for wp in r:
coords.append((wp[1], wp[0], altitude))
tmpRoute.append(WayPoint(route=rm, lat=wp[0], lng=wp[1], ref=tmpCounter))
tmpCounter += 1
pnt.coords = coords
pnt.style.linestyle.width = 6
pnt.style.linestyle.color = colorArray[drone_secuencial % len(colorArray)]
pnt.altitudemode = AltitudeMode.relativetoground
pnt.lookat.gxaltitudemode = GxAltitudeMode.relativetoseafloor
pnt.lookat.latitude = coords[0][0]
pnt.lookat.longitude = coords[0][1]
pnt.lookat.range = 122
pnt.lookat.heading = 0.063
pnt.lookat.tilt = 0
tmpRoute.append(WayPoint(route=rm, lat=base[0], lng=base[1], ref=tmpCounter))
kml.newpoint(name="Back to base", coords=[(base[1], base[0])])
rm.initialWp = len(tmpRoute)-2 # -2 for the last tmp counter and array 0 position
rm.save()
WayPoint.objects.bulk_create(tmpRoute)
place = KML_DIR + '/IBRI' + str(m.id)
try:
mkdir(place)
except Exception as e:
print colored(e, 'red')
pass
place = place + '/' + kmlName + '.kml'
place.replace('//', '/')
try:
kml.save(place) # Saving
except Exception as e:
print colored(e, 'red')
return HttpResponse('errorKmlPath')
drone_secuencial += 1
preshared = u'' + PRESHAREDKEY
return HttpResponse(AESCipher(preshared).encrypt(json.dumps([m.pk, route])))