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")
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")
def prep_sink_kml_per_hour(hours, data_to_show): for hour in hours: ### create the kml file kml = Kml(open=1) ### name columns according to hour of day lon_col = "lon" + str(hour) lat_col = "lat" + str(hour) data_col = "data" + str(hour) ### create lines that represent thermals for i in range(len(data_to_show) - 1): x1 = -data_to_show[lon_col][i] y1 = data_to_show[lat_col][i] z1 = data_to_show[data_col][i] x2 = -data_to_show[lon_col][i + 1] y2 = data_to_show[lat_col][i + 1] z2 = data_to_show[data_col][i + 1] if z1 < -100 or z2 < -100: line_name = "line " + str(i) linestring = kml.newlinestring(name=line_name) linestring.coords = [(x1, y1), (x2, y2)] linestring.altitudemode = simplekml.AltitudeMode.absolute linestring.style.linestyle.width = 3 if z1 > -200 or z2 > -200: linestring.style.linestyle.color = simplekml.Color.green elif z1 > -400 or z2 > -400: linestring.style.linestyle.color = simplekml.Color.blue linestring.style.linestyle.width = 6 else: linestring.style.linestyle.color = simplekml.Color.black linestring.style.linestyle.width = 9 ### linestring.extrude = 1 kml_file_name = "Roldanillo_" + str(hour) + "_sinks.kml" kml.save(path2grid + "hours\\" + kml_file_name)
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")
def google_earth_export(): print('ttt'*100, request.form) form = GoogleEarthForm(request.form) if 'POST' in request.method: kml_file = Kml() for node in filter(lambda obj: obj.visible, Node.query.all()): point = kml_file.newpoint(name=node.name) point.coords = [(node.longitude, node.latitude)] point.style = styles[node.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in filter(lambda obj: obj.visible, Link.query.all()): line = kml_file.newlinestring(name=link.name) line.coords = [ (link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude) ] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = join(current_app.kmz_path, request.form['name'] + '.kmz') kml_file.save(filepath) return render_template( 'google_earth_export.html', form=form )
def prep_wind_kml_per_hour(data_to_show): ### create the kml file kml = Kml(open=1) ### name columns according to hour of day lon_col = "lon" lat_col = "lat" data_col = "data" ### create lines that represent thermals ### calculate centre of the small grid ### place the line segment in the centre ### take wind speed and direction and calculate coordinates ### of the end point of the line segment ### add the arrow pointer for i in range(1, len(data_to_show) - 1): x1 = -data_to_show[lon_col][i] y1 = data_to_show[lat_col][i] z1 = data_to_show[data_col][i] x2 = -data_to_show[lon_col][i + 1] y2 = data_to_show[lat_col][i + 1] z2 = data_to_show[data_col][i + 1] if z1 > 0 or z2 > 0: line_name = "line " + str(i) linestring = kml.newlinestring(name=line_name) linestring.coords = [(x1, y1), (x2, y2)] linestring.altitudemode = simplekml.AltitudeMode.relativetoground linestring.style.linestyle.width = 10 linestring.iconstyle.icon.href = 'http://earth.google.com/images/kml-icons/track-directional/track-0.png' linestring.style.linestyle.color = '99ffac59' kml_file_name = "Roldanillo_wind.kml" kml.save(path2grid + "hours\\" + kml_file_name)
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")
def export_to_kml(self, file_name): coords = list() for i in range(len(self._gps_latitude)): coords.append((self._gps_longitude[i], self._gps_latitude[i])) kml = Kml() lin = kml.newlinestring(name="Track", description="A track.", coords=coords) lin.style.linestyle.color = 'ff0000ff' # Red lin.style.linestyle.width = 2 # 10 pixels kml.save(file_name)
def save_edges_to_kml(edges, paths_save_file_path): line_count = 0 max_path_length = 0 kml = Kml() for idx, edge in enumerate(edges): coordinates_for_line = edge coordinates_for_line = tuple( map(lambda row: (row[1], row[0]), coordinates_for_line)) kml.newlinestring(name='Transmisssion Line %d' % idx, description='', coords=coordinates_for_line) max_path_length = max(max_path_length, len(coordinates_for_line)) line_count += 1 max_path_length = max(max_path_length, len(coordinates_for_line)) pp.pprint(kml) kml.save(paths_save_file_path, format=True) pp.pprint('paths_save_file_path: %s' % os.path.realpath(paths_save_file_path)) pp.pprint('max_path_length: %d' % max_path_length) pp.pprint('line_count: %d' % line_count)
def view(view_type): view_options_form = ViewOptionsForm(request.form) google_earth_form = GoogleEarthForm(request.form) labels = {'node': 'name', 'link': 'name'} if 'view_options' in request.form: # retrieve labels labels = { 'node': request.form['node_label'], 'link': request.form['link_label'] } elif 'google_earth' in request.form: kml_file = Kml() for node in filter(lambda obj: obj.visible, Node.query.all()): point = kml_file.newpoint(name=node.name) point.coords = [(node.longitude, node.latitude)] point.style = styles[node.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in filter(lambda obj: obj.visible, Link.query.all()): line = kml_file.newlinestring(name=link.name) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = join(current_app.kmz_path, request.form['name'] + '.kmz') kml_file.save(filepath) return render_template( '{}_view.html'.format(view_type), view_options_form=view_options_form, google_earth_form=google_earth_form, labels=labels, names=pretty_names, subtypes=node_subtypes, node_table={ obj: OrderedDict([(property, getattr(obj, property)) for property in type_to_public_properties[obj.type]]) for obj in filter(lambda obj: obj.visible, Node.query.all()) }, link_table={ obj: OrderedDict([(property, getattr(obj, property)) for property in type_to_public_properties[obj.type]]) for obj in filter(lambda obj: obj.visible, Link.query.all()) })
def kml(name, lon, lat, code=None, nc=None): from simplekml import Kml, Style from shapely import Polygon, Point if nc is not None: x = nc.variables['XLONG_M'][0, :, :] y = nc.variables['XLAT_M'][0, :, :] xc = nc.variables['XLONG_C'][0, :, :] yc = nc.variables['XLAT_C'][0, :, :] k = Kml() z = zip(name, lon, lat) if code is None else zip(name, lon, lat, code) for s in z: p = k.newpoint(name=s[3] if len(s) == 4 else s[0], coords=[s[1:3]]) p.style.iconstyle.icon.href = "http://maps.google.com/mapfiles/kml/paddle/red-circle.png" p.style.balloonstyle.text = s[0] if nc is not None: i, j, d = nearest(x, y, s[1], s[2]) coords = [(xc[i, j], yc[i, j]), (xc[i, j + 1], yc[i, j]), (xc[i, j + 1], yc[i + 1, j]), (xc[i, j], yc[i + 1, j]), (xc[i, j], yc[i, j])] if Polygon(coords).contains(Point(*s[1:3])): l = k.newlinestring(coords=[s[1:3], (x[i, j], y[i, j])]) r = k.newlinestring(coords=coords) return k
def export_to_google_earth(): kml_file = Kml() for device in fetch_all('Device'): point = kml_file.newpoint(name=device.name) point.coords = [(device.longitude, device.latitude)] point.style = styles[device.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in fetch_all('Link'): line = kml_file.newlinestring(name=link.name) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = app.path / 'google_earth' / f'{request.form["name"]}.kmz' kml_file.save(filepath) return True
def export_to_google_earth(): kml_file = Kml() for node in Node.query.all(): point = kml_file.newpoint(name=node.name) point.coords = [(node.longitude, node.latitude)] point.style = styles[node.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in Link.query.all(): line = kml_file.newlinestring(name=link.name) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = join(current_app.ge_path, request.form['name'] + '.kmz') kml_file.save(filepath) return jsonify({})
def export_to_google_earth(): kml_file = Kml() for device in Device.query.all(): point = kml_file.newpoint(name=device.name) point.coords = [(device.longitude, device.latitude)] point.style = styles[device.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in Link.query.all(): line = kml_file.newlinestring(name=link.name) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = join(current_app.path, 'google_earth', f'{request.form["name"]}.kmz') kml_file.save(filepath) return jsonify({'success': True})
def export_to_google_earth(self, **kwargs: Any) -> None: kml_file = Kml() for device in fetch_all("Device"): point = kml_file.newpoint(name=device.name) point.coords = [(device.longitude, device.latitude)] point.style = self.google_earth_styles[device.icon] point.style.labelstyle.scale = kwargs["label_size"] for link in fetch_all("Link"): line = kml_file.newlinestring(name=link.name) line.coords = [ (link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude), ] line.style = Style() kml_color = f"ff{link.color[5:]}{link.color[3:5]}{link.color[1:3]}" line.style.linestyle.color = kml_color line.style.linestyle.width = kwargs["line_width"] filepath = self.path / "projects" / "google_earth" / f'{kwargs["name"]}.kmz' kml_file.save(filepath)
def prep_lift_kml_per_hour(hours, data_to_show): for hour in hours: ### create the kml file kml = Kml(open=1) ### name columns according to hour of day lon_col = "lon" + str(hour) lat_col = "lat" + str(hour) data_col = "data" + str(hour) ### calculate max lift max_lift = data_to_show[data_col].max() ### create lines that represent thermals for i in range(len(data_to_show) - 1): x1 = -data_to_show[lon_col][i] y1 = data_to_show[lat_col][i] z1 = data_to_show[data_col][i] / max_lift * 100 x2 = -data_to_show[lon_col][i + 1] y2 = data_to_show[lat_col][i + 1] z2 = data_to_show[data_col][i + 1] / max_lift * 100 if z1 > 1 or z2 > 1: line_name = "line " + str(i) linestring = kml.newlinestring(name=line_name) linestring.coords = [(x1, y1, z1), (x2, y2, z2)] linestring.altitudemode = simplekml.AltitudeMode.relativetoground linestring.style.linestyle.width = 3 if z1 < 20 or z2 < 20: linestring.style.linestyle.color = simplekml.Color.yellow elif z1 < 40 or z2 < 40: linestring.style.linestyle.color = simplekml.Color.orange linestring.style.linestyle.width = 5 else: linestring.style.linestyle.color = simplekml.Color.red linestring.style.linestyle.width = 7 ### linestring.extrude = 1 kml_file_name = "Roldanillo_" + str(hour) + "_thermals.kml" kml.save(path2grid + "hours\\" + kml_file_name)
def serialize_list_point_lon_lat_index_as_line_in_kml(list_points, name='point', color=Color.green, scale=1, abolutefilepath ='line.kml'): kml = Kml() point_folderlin = kml.newlinestring(name="line", description="line", coords=list_points) point_folderlin.labelstyle.color=color point_folderlin.style.labelstyle.scale = scale point_folderlin.style.iconstyle.icon.href='http://maps.google.com/mapfiles/kml/paddle/grn-circle-lv.png' point_folder = kml.newfolder(name='points') for point in list_points: lon_lat = [point[0],point[1]] index = point[2] pnt_0 = point_folder.newpoint() pnt_0.name = str(index) pnt_0.coords = [lon_lat] pnt_0.labelstyle.color=color pnt_0.style.labelstyle.scale = scale pnt_0.style.iconstyle.icon.href='http://maps.google.com/mapfiles/kml/paddle/grn-circle-lv.png' kml.save(abolutefilepath)
#!/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)
# 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)]) lin.linestyle.color = Color.red # Red lin.linestyle.width = 10 # 10 pixels # A Polygon with a hole. Half invisible. pol = kml.newpolygon(name="Atrium Garden", outerboundaryis=[(18.43348,-33.98985), (18.43387,-33.99004262216968), (18.43410,-33.98972), (18.43371,-33.98952), (18.43348,-33.98985)], innerboundaryis=[(18.43360,-33.98982), (18.43386,-33.98995), (18.43401,-33.98974), (18.43376,-33.98962), (18.43360,-33.98982)]) pol.polystyle.color = '990000ff' # Red pol.polystyle.outline = 0 # A Point showing off a BalloonStyle pnt = kml.newpoint(name="BallonStyle", coords=[(18.429191, -33.987286)]) pnt.balloonstyle.text = "These are trees and this text is blue with a green background." pnt.balloonstyle.bgcolor = Color.lightgreen pnt.balloonstyle.textcolor = Color.rgb(0, 0, 255)
#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")
def createRoute(request): """ Create Route is one of the main methods in the software because it creates the routes for each drone in the mission. It takes the POST['msg'] information. Then gets the square waypoints grid and divides it in many areas as drones we have. This method is triggered when the operator clicks on the play button. The areas are created and stored in the database and whe it's done we create a KML file/s and stores it in the KML_DIR path under the IBRI folder. @param request: Request petition that is handled by Django @type request: Django request object @return: Http response (JSON) @requires: utils.tsp @see: HttpResponse @see: AESCipher @see: JSON @see: csrf_extemp @see: WayPoint @see: Route @see: KML @see: utils.tsp.py @note: If you want to see how createRoute works, click on see source code. """ if(request.method == 'POST'): # Get the preshared key and decrypt the post message. preshared = u'' + PRESHAREDKEY dec = json.loads(AESCipher(preshared).decrypt(request.POST['msg'])) # Loads the json and stores the values in each variable base = json.loads(dec['base']) # Base point coords = json.loads(dec['wayPoints']) # Waypoints (lat, lng) nearPoint = json.loads(dec['nearPoint']) # NearPoint userPK = json.loads(dec['insearch']) # Users in search altitude = json.loads(dec['altitude']) # Altitude # Number of areas nAreas = len(coords) totalElements = 0 for i in coords: totalElements += len(i) size = int(sqrt(totalElements)) nElements = int(math.floor(math.sqrt(len(coords[0])))) searchArea = [[[] for _ in range(nElements)] for _ in range(nAreas)] ov1 = 0 ov2 = 0 # Area divison for i in range(nAreas): for j in range(nElements): col = j * size if(ov1 == 0): searchArea[i][j] = coords[i][(col-ov2):(col-ov2) + size] else: searchArea[i][j] = coords[i][0:ov1] ov2 = size - ov1 ov1 = 0 if(len(searchArea[i][j]) == 0): searchArea[i].pop() j -= 1 if(size - len(searchArea[i][j]) > 0): ov1 = size - len(searchArea[i][j]) ov2 = 0 else: ov1 = 0 ov2 = 0 coord = [] x = 0 # Assign coordenates to each area for i in range(nAreas): coord.append([]) for j in searchArea[i]: for k in j: 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() 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])))
def write_track_kml(csvreader): """ Inputs: csv contains lon/lat Output: glider track kml file """ coord = [] timerange = [] lat_f = int(cfg.get(section1, "LAT_COLUMN")) lon_f = int(cfg.get(section1, "LON_COLUMN")) date_f = int(cfg.get(section1, "DATE_COLUMN")) date_fmt = cfg.get(section1, "DATE_FORMAT") kml_dir = cfg.get(section1, "KML_DIR") mission_date = cfg.get(section1, "MISSION_START_DATE") organization = cfg.get(section1, "ORGANIZATION") vehicle_name = cfg.get(section1, "VEHICLE_NAME") kml_title = cfg.get(section1, "KML_DOC_TITLE") kml_lookat_lon = float(cfg.get(section1, "KML_LOOKAT_LON")) kml_lookat_lat = float(cfg.get(section1, "KML_LOOKAT_LAT")) kml_lookat_range = float(cfg.get(section1, "KML_LOOKAT_RANGE")) kml_cdata_title = cfg.get(section1, "KML_CDATA_TITLE") plot_url = cfg.get(section1, "PLOT_URL") plot_width = int(cfg.get(section1, "PLOT_WIDTH")) plot_height = int(cfg.get(section1, "PLOT_HEIGHT")) plot_temp = cfg.get(section1, "PLOT_TEMP") plot_oxyg = cfg.get(section1, "PLOT_OXYG") plot_sali = cfg.get(section1, "PLOT_SALI") plot_chlo = cfg.get(section1, "PLOT_CHLO") plot_cdom = cfg.get(section1, "PLOT_CDOM") icon_url = cfg.get(section1, "ICON_URL") icon_normal_scale = cfg.get(section1, "ICON_NORMAL_SCALE") icon_normal_color = cfg.get(section1, "ICON_NORMAL_COLOR") icon_normal_width = cfg.get(section1, "ICON_NORMAL_WIDTH") icon_highlight_url = cfg.get(section1, "ICON_HIGHLIGHT_URL") icon_highlight_scale = cfg.get(section1, "ICON_HIGHLIGHT_SCALE") icon_highlight_color = cfg.get(section1, "ICON_HIGHLIGHT_COLOR") icon_highlight_width = cfg.get(section1, "ICON_HIGHLIGHT_WIDTH") path_line_color = cfg.get(section1, "PATH_LINE_COLOR") path_line_width = int(cfg.get(section1, "PATH_LINE_WIDTH")) csvheader = cfg.get(section1, "CSV_HEADER") if csvheader == "YES": csvreader.next() else: pass for row in csvreader: coord.append((row[lon_f - 1], row[lat_f - 1], 0.0)) # -1 for python order timestamp = time.strptime(row[date_f - 1], date_fmt) kmltime = time.strftime("%Y-%m-%dT%H:%M:%SZ", timestamp) # KML requires specific time format timerange.append(kmltime) # time stamp # This constructs the KML document from the CSV file. kml = Kml(name="%s %s" % (organization, vehicle_name)) doc = kml.newdocument(name="%s" % kml_title, snippet=Snippet(timerange[0])) doc.lookat.gxtimespan.begin = timerange[0] doc.lookat.gxtimespan.end = timerange[-1] doc.lookat.longitude = kml_lookat_lon doc.lookat.latitude = kml_lookat_lat doc.lookat.range = kml_lookat_range # Create a folder ge_dir = doc.newfolder(name="Tracks") # Create a schema for extended data: heart rate, cadence and power schema = kml.newschema() # Create a new track in the folder trk = ge_dir.newgxtrack(name="%s %s" % (organization, vehicle_name)) desc1 = "<![CDATA[\n%s<br />\n<br />\n" % kml_cdata_title desc2 = "<a href='%s/glider.html' target='_blank'>Link to Plot</a><br />\n" % plot_url desc_temp = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_temp, plot_height, plot_width) desc_oxyg = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_oxyg, plot_height, plot_width) desc_sali = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_sali, plot_height, plot_width) desc_chlo = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_chlo, plot_height, plot_width) desc_cdom = "<img src='%s/%s' height='%d' width='%d' /><br />\n" % (plot_url, plot_cdom, plot_height, plot_width) desc3 = "]]>\n" trk.description = desc1 + desc2 + desc_temp + desc_oxyg + desc_sali + desc_chlo + desc_cdom + desc3 # Apply the above schema to this track trk.extendeddata.schemadata.schemaurl = schema.id # Add all information to the track trk.newwhen(timerange) # Each item in the give nlist will become a new <when> tag trk.newgxcoord(coord) # Ditto # Style trk.stylemap.normalstyle.iconstyle.icon.href = icon_url trk.stylemap.normalstyle.iconstyle.scale = icon_normal_scale trk.stylemap.normalstyle.linestyle.color = icon_normal_color trk.stylemap.normalstyle.linestyle.width = icon_normal_width trk.stylemap.highlightstyle.iconstyle.icon.href = icon_highlight_url trk.stylemap.highlightstyle.iconstyle.scale = icon_highlight_scale trk.stylemap.highlightstyle.linestyle.color = icon_highlight_color trk.stylemap.highlightstyle.linestyle.width = icon_highlight_width # Create a path line gpath = kml.newlinestring(name="%s %s" % (organization, vehicle_name)) gpath.description = trk.description gpath.timespan.begin = timerange[0] gpath.timespan.end = "" gpath.coords = coord gpath.style.linestyle.color = path_line_color gpath.style.linestyle.width = path_line_width # Check if KML Directory exists if not os.path.exists(kml_dir): os.makedirs(kml_dir) # Save the KML kml.save("%s/Glider_%s_%s_%s.kml" % (kml_dir, organization, vehicle_name, mission_date)) print("Glider_%s_%s_%s.kml created in '%s' folder" % (organization, vehicle_name, mission_date, kml_dir))
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) ) if len(tab) == KML_LINE_POINT_LIMIT: line = kml.newlinestring(name=str(firstPos.newTime), description="", coords=tab) tab = [] 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' firstPos = None if len(tab) > 0: line = kml.newlinestring(name=str(firstPos.newTime), description="", coords=tab)
def view(view_type): add_node_form = AddNode(request.form) add_link_form = AddLink(request.form) view_options_form = ViewOptionsForm(request.form) google_earth_form = GoogleEarthForm(request.form) scheduling_form = SchedulingForm(request.form) scheduling_form.scripts.choices = Script.choices() scheduling_form.workflows.choices = Workflow.choices() labels = {'node': 'name', 'link': 'name'} if 'script' in request.form: data = dict(request.form) selection = map(int, session['selection']) scripts = request.form.getlist('scripts') workflows = request.form.getlist('workflows') data['scripts'] = [get_obj(Script, name=name) for name in scripts] data['workflows'] = [ get_obj(Workflow, name=name) for name in workflows ] data['nodes'] = [get_obj(Node, id=id) for id in selection] data['user'] = current_user task = Task(**data) db.session.add(task) db.session.commit() return redirect(url_for('tasks_blueprint.task_management')) elif 'view_options' in request.form: # update labels labels = { 'node': request.form['node_label'], 'link': request.form['link_label'] } elif 'google earth' in request.form: kml_file = Kml() for node in Node.query.all(): point = kml_file.newpoint(name=node.name) point.coords = [(node.longitude, node.latitude)] point.style = styles[node.subtype] point.style.labelstyle.scale = request.form['label_size'] for link in Link.query.all(): line = kml_file.newlinestring(name=link.name) line.coords = [(link.source.longitude, link.source.latitude), (link.destination.longitude, link.destination.latitude)] line.style = styles[link.type] line.style.linestyle.width = request.form['line_width'] filepath = join(current_app.ge_path, request.form['name'] + '.kmz') kml_file.save(filepath) # for the sake of better performances, the view defaults to markercluster # if there are more than 2000 nodes view = 'leaflet' if len(Node.query.all()) < 2000 else 'markercluster' if 'view' in request.form: view = request.form['view'] # we clean the session's selected nodes session['selection'] = [] # name to id name_to_id = {node.name: id for id, node in enumerate(Node.query.all())} return render_template( '{}_view.html'.format(view_type), filters=Filter.query.all(), view=view, scheduling_form=scheduling_form, view_options_form=view_options_form, google_earth_form=google_earth_form, add_node_form=add_node_form, add_link_form=add_link_form, labels=labels, names=pretty_names, subtypes=node_subtypes, name_to_id=name_to_id, node_table={ obj: OrderedDict([(property, getattr(obj, property)) for property in type_to_public_properties[obj.type]]) for obj in Node.query.all() }, link_table={ obj: OrderedDict([(property, getattr(obj, property)) for property in type_to_public_properties[obj.type]]) for obj in Link.query.all() })
def generate_graph(input_file, output_file): carers, visits = load_solution(input_file) #write corresponding KLM file for display in Google Earth kml = Kml() #create palette of colors for carers and sorting carers visits colors = generate_colors(len(carers)) i = 0 for carer in carers: #setting style if not strtobool(carer.dropped): carer_style = Style() carer_style.iconstyle.color = colors[i] carer_style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/shapes/man.png' carer_style.linestyle.color = colors[i] carer_style.linestyle.width = 5 carer.set_style(carer_style) i = i + 1 # carers pins + info for carer in carers: if not strtobool(carer.dropped): carer.sort_visits() pnt = kml.newpoint(coords=[(float(carer.visits[0].lon), float(carer.visits[0].lat))]) pnt.extendeddata.newdata(name='sap_number', value=carer.sap_number, displayname="SAP number") pnt.extendeddata.newdata(name='work_relative', value=carer.work_relative, displayname="Relative working time") pnt.extendeddata.newdata(name='work_total_time', value=carer.work_total_time, displayname="Total working time") pnt.extendeddata.newdata(name='work_available_time', value=carer.work_available_time, displayname="Available working time") pnt.extendeddata.newdata(name='work_service_time', value=carer.work_service_time, displayname="Service working time") pnt.extendeddata.newdata(name='work_travel_time', value=carer.work_travel_time, displayname="Travelling time") pnt.extendeddata.newdata(name='work_idle_time', value=carer.work_idle_time, displayname="Idle time") pnt.extendeddata.newdata(name='work_visits_count', value=carer.work_visits_count, displayname="Number of visits") if len(carer.visits) > 0: pnt.style.iconstyle = carer.style.iconstyle pnt.timespan.begin = datetime.datetime.strptime( carer.visits[0].start_time, '%Y-%b-%d %H:%M:%S').isoformat() pnt.timespan.end = datetime.datetime.strptime( carer.get_endtime(), '%Y-%b-%d %H:%M:%S').isoformat() # visits pins + info for visit in visits: pnt = kml.newpoint(coords=[(float(visit.lon), float(visit.lat))]) pnt.extendeddata.newdata(name='user', value=visit.user, displayname="User ID") pnt.extendeddata.newdata(name='start_time', value=visit.start_time, displayname="Start time") pnt.extendeddata.newdata(name='duration', value=visit.duration, displayname="Duration") if visit.is_multiple_carers(): pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/paddle/wht-blank.png' else: pnt.style.iconstyle.icon.href = 'http://maps.google.com/mapfiles/kml/pushpin/wht-pushpin.png' if not strtobool(visit.dropped): pnt.extendeddata.newdata(name='assigned_carer', value=visit.assigned_carer, displayname="Assigned carer SAP") pnt.extendeddata.newdata(name='satisfaction', value=visit.satisfaction, displayname="User satisfaction") if not strtobool(visit.dropped): for carer in carers: if visit.assigned_carer == carer.sap_number: carer_style = carer.style end_time = carer.get_endtime() break if carer_style: pnt.style.iconstyle.color = carer_style.iconstyle.color pnt.timespan.begin = datetime.datetime.strptime( visit.start_time, '%Y-%b-%d %H:%M:%S').isoformat() pnt.timespan.end = datetime.datetime.strptime( end_time, '%Y-%b-%d %H:%M:%S').isoformat() else: #if viist is dropped pnt.style.iconstyle.color = Color.rgb(0, 0, 0) # adding edges for carer in carers: if not strtobool(carer.dropped): if len(carer.visits) > 1: for i in range(0, len(carer.visits) - 1): source = carer.visits[i] target = carer.visits[i + 1] linestring = kml.newlinestring() linestring.coords = [ (float(source.lon), float(source.lat), 0), (float(target.lon), float(target.lat), 0) ] linestring.style.linestyle = carer.style.linestyle linestring.timespan.begin = datetime.datetime.strptime( target.start_time, '%Y-%b-%d %H:%M:%S').isoformat() linestring.timespan.end = datetime.datetime.strptime( carer.get_endtime(), '%Y-%b-%d %H:%M:%S').isoformat() kml.save(output_file)
How to use simplekml. """ import os from simplekml import Kml kml = Kml( name="Usage", open=1 ) # open=1 just opens the document in the TOC (table of contents). Not a necessary step. # A simple Point kml.newpoint(name="Kirstenbosch", coords=[(18.432314, -33.988862)]) # A simple Linestring showing off HTML markup lin = kml.newlinestring(name="Pathway", description="A pathway in <b>Kirstenbosch</b>", coords=[(18.43312, -33.98924), (18.43224, -33.98914), (18.43144, -33.98911), (18.43095, -33.98904)]) # A simple Polygon with a hole in it. pol = kml.newpolygon(name="Atrium Garden", outerboundaryis=[(18.43348, -33.98985), (18.43387, -33.99004262216968), (18.43410, -33.98972), (18.43371, -33.98952), (18.43348, -33.98985)], innerboundaryis=[[(18.43360, -33.98982), (18.43386, -33.98995), (18.43401, -33.98974), (18.43376, -33.98962), (18.43360, -33.98982)]])
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")
from simplekml import Kml, Color kml = Kml(open=1) # generate geometries point = kml.newpoint(name="TestPoint", coords=[(-23.094721, 33.4838)]) linestring = kml.newlinestring(name="TestLinestring") linestring.coords = [(-23.1659603, 33.4754108), (-23.1631279, 33.4767710), (-23.1604671, 33.4769858), (-23.1554890, 33.4758403), (-23.1545448, 33.4731198), (-23.1518841, 33.4686807), (-23.1486225, 33.4667476), (-23.1433010, 33.4662464), (-23.1391811, 33.4666044), (-23.1354904, 33.4686807), (-23.1324005, 33.4715447), (-23.1305981, 33.4754824), (-23.1307697, 33.4795631), (-23.1289673, 33.4822835), (-23.1247616, 33.4828562), (-23.1208992, 33.4819255), (-23.1177235, 33.4796347), (-23.1159210, 33.4762699), (-23.1117153, 33.4736925), (-23.1081963, 33.4726186)] polygon1 = kml.newpolygon(name="TestPolygonOnlyOuter") polygon1.outerboundaryis = [ (-23.0895710, 33.4706855), (-23.0868244, 33.4729050), (-23.0818462, 33.4744085), (-23.0760098, 33.4738357), (-23.0727482, 33.4737641), (-23.0702591, 33.4745517), (-23.0689716, 33.4755540), (-23.0683708, 33.4769142), (-23.0689716, 33.4778449), (-23.0709457, 33.4772722), (-23.0737782, 33.4761267), (-23.0778122, 33.4772006), (-23.0790138, 33.4786324), (-23.0786705, 33.4804938), (-23.0774689, 33.4819255), (-23.0756664, 33.4823551), (-23.0742931, 33.4837868), (-23.0740356, 33.4856480), (-23.0724049, 33.4870797), (-23.0697441, 33.4884398), (-23.0687141, 33.4880103), (-23.0688000, 33.4871513),
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)