def _kml_shp_2_bb(self, filename): # from kml and shape file to a bounding box. We will always use a bounding box to create the final product. if filename.endswith('.shp'): with collection(filename, "r") as inputshape: shapes = [shape for shape in inputshape] # only first shape dat = shapes[0]['geometry']['coordinates'] lon = [l[0] for l in dat[0]] lat = [l[1] for l in dat[0]] latlim = [min(lat), max(lat)] lonlim = [min(lon), max(lon)] elif filename.endswith('.kml'): doc = file(filename).read() k = fastkml.KML() k.from_string(doc) dat = list(list(k.features())[0].features())[0].geometry[0].exterior.coords[:] lon = [l[0] for l in dat[0]] lat = [l[1] for l in dat[0]] latlim = [min(lat), max(lat)] lonlim = [min(lon), max(lon)] else: print 'format not recognized! Pleas creat either a .kml or .shp file.' return [] return latlim, lonlim
def convert_gsientries_to_kml(entries: List[GSIEntry]) -> fastkml.KML: # # Boilerplate for creating a new KML doc. kml = fastkml.KML() d = fastkml.Document() kml.append(d) s = fastkml.Style(id=style_id) d.append_style(s) s.append_style(fastkml.LineStyle(color="Af00ffff", width=6)) s.append_style(fastkml.PolyStyle(color="7f00ff00")) p = fastkml.Placemark() d.append(p) p.styleUrl = "#" + style_id g = fastkml.geometry.Geometry( extrude=True, tessellate=True, altitude_mode="relativeToGround", ) g.geometry = fastkml.geometry.LineString([ (entry.longitude, entry.latitude, entry.speed) for entry in entries ]) p.geometry = g return kml
def __init__(self) -> None: self.kml = K.KML() self.doc = K.Document( ns=KmlMaker.NS, id='docid', name=f'foursquare-{datetime.now().strftime("%Y%m%d")}', description='Foursquare lists', ) self.color2style: Dict[str, str] = {} self.kml.append(self.doc)
def load_geo_images_list(kml_path='.'): import fastkml, shapely def process_KML_feature(e): global geo_images if hasattr(e, 'features'): for f in e.features(): process_KML_feature(f) return if not hasattr(e, 'geometry'): return if not isinstance( e.geometry, shapely.geometry.point.Point) or not is_valid_image_id(e.name): return if not hasattr(e, 'description'): return if not e.description: return fields = e.description.split() if len(fields) < 1: return center_azimuth_deg = float(fields[0].partition('deg')[0]) owner_uid = 0 sharing_mode = None if len(fields) >= 2: owner_uid = int(fields[1]) if len(fields) >= 3: sharing_mode = fields[2] geo_images[e.name] = tuple(e.geometry.coords[0][:2]) + ( center_azimuth_deg, owner_uid, sharing_mode) k = fastkml.KML() k.from_string(open(kml_path + '/images.kml', 'r').read().encode('utf-8')) process_KML_feature(k)
def kml_poly_to_geom(kml_poly): """ Convert KML polygon in AVIRIS kml_poly field to a shapely Geometry """ # Not all KML polygons are correct (missing LinearRing tag); grab coords directly kmldom = minidom.parseString( '<?xml version="1.0" encoding="UTF-8"?>' + '<kml xmlns="http://www.opengis.net/kml/2.2"><Document><Placemark>' + kml_poly + "</Placemark></Document></kml>") coords = kmldom.getElementsByTagName( "outerBoundaryIs")[0].getElementsByTagName("coordinates")[0] kml = fastkml.KML() kml.from_string( '<?xml version="1.0" ?>' + '<kml xmlns="http://www.opengis.net/kml/2.2">' + "<Document><Placemark><Polygon><outerBoundaryIs><LinearRing>" + coords.toxml() + "</LinearRing></outerBoundaryIs></Polygon></Placemark></Document></kml>" ) return next(next(kml.features()).features()).geometry
def load_streets_kml(self): with open('{}/streets.kml'.format(self.streets_dir)) as data_file: self.kml = fastkml.KML() self.kml.from_string(data_file.read()) features = list(self.kml.features()) self.itemsGen = list(features)[0].features()
good_dZ[0:-1]=np.abs(np.diff(D.elevation))<0.25 good_dZ=np.convolve(good_dZ.astype(float), np.ones(3), mode='same')==3 xx=np.unique(np.round(D.longitude/.001)+1j*np.round(D.latitude/.001)) D1=pc.data().from_dict({'latitude': np.imag(xx)/1000, 'longitude':np.real(xx)/1000-360}) D_filt=D[good_dZ] D_nonscat=D_filt[D_filt.K0==0] D_scat=D_filt[D_filt.K0>0] geoms={} for file in ['Airstrip_outer.kml', 'Grassy_1.kml', 'Grassy_2.kml' ]: with open(file,'rb') as ff: doc=ff.read() K=fastkml.KML() K.from_string(doc) geoms[file.replace('.kml','')] =K._features[0]._features[0].geometry inside = [geo.Point(item[0], item[1]).within(geoms['Airstrip_outer']) for item in zip(D_filt.longitude, D_filt.latitude)] plt.figure(1); plt.clf() plt.plot(D_nonscat.x, D_nonscat.y,'k.', markersize=2, zorder=0) ii=np.argsort(D_scat.K0) plt.scatter(D_scat.x[ii], D_scat.y[ii], 2, c=np.log10(D_scat.K0[ii]), vmin=-4.5, vmax=-3, zorder=1); hb=plt.colorbar() hb.set_label('log $r_{eff}$, m')
from psycopg2.extras import execute_values import fastkml as fk import shapely.wkt from shapely.geometry.point import Point import sys if len(sys.argv) < 3: print("Usage: python load_takeout.py <userid> <Location History.json>") sys.exit(1) userid, location_file = sys.argv[1], sys.argv[2] print(f"Loading {location_file} data for userid {userid}") conn = psycopg2.connect("dbname=covid19 user=covid19 port=5434\ password=covid19databasepassword host=localhost") k = fk.KML() k.from_string(open(location_file).read()) doc = list(k.features())[0] values = [] cur = conn.cursor() for point in doc.features(): if type(point.geometry) != shapely.geometry.point.Point: continue start = point.begin.strftime('%Y-%m-%dT%H:%M:%S') end = point.end.strftime('%Y-%m-%dT%H:%M:%S') print(point.address, '|', point.name, '|', point.begin.strftime('%Y-%m-%dT%H:%M:%S'), point.end.strftime('%Y-%m-%dT%H:%M:%S'), point.geometry) geopoint = Point(point.geometry.x, point.geometry.y) geo = shapely.wkt.dumps(geopoint) geopoint = f"SRID=4326;{geo}"