def extract_kml(self): kml = fastkml.kml.KML() ns = '{http://www.opengis.net/kml/2.2}' doc = fastkml.kml.Document( ns, 'nrd-cluster-%s' % (datetime.datetime.now().strftime('%Y-%m-%d'),), 'NRC Clusters %s' % (datetime.datetime.now().strftime('%Y-%m-%d'),), 'Cluster analysis of all recent NRC reports in the gulf of mexico that indicate a release of materials into the environment.') kml.append(doc) self.cur.execute("truncate table appomatic_nrccluster_nrcreport") self.cur.execute("truncate table appomatic_nrccluster_cluster") self.cur.execute(""" insert into appomatic_nrccluster_nrcreport( geocode_source, reportnum, incident_datetime, incidenttype, lat, lng, location) select geocode_source, reportnum, incident_datetime, incidenttype, lat, lng, ST_MakePoint(lng, lat) from "NrcReleaseIncidents" where region='gulf' and extract(day from NOW()-incident_datetime) <= 366 and geocode_source = 'Explicit'; """) for timeperiod in (None, 12*30, 6*30, 3*30): self.extract_clusters(timeperiod, doc) self.extract_reports(doc) return kml.to_string(prettyprint=True)
def main(): args = get_args() T = TracksAnalysis(*args.paths) V = WaypointVoronoi.from_tracks(T) if args.kml: kml = V.to_kml(alpha=args.alpha) if args.output: if args.gzip: output_kmz(kml, args.output) else: output_kml(kml, args.output) else: print(kml.to_string())
def extract_kml(name, cur, query, size, radius, periods, **kw): kml = fastkml.kml.KML() docname = name if periods: docname += ' ' + ', '.join("%s:%s" % (timeperiod[0].strftime("%Y-%m-%d"), timeperiod[1].strftime("%Y-%m-%d")) for timeperiod in periods) doc = fastkml.kml.Document(KMLNS, django.template.defaultfilters.slugify(docname), docname, '') kml.append(doc) for timeperiod in periods: extract_clusters_kml(cur, query, size, radius, timeperiod, doc, **kw) extract_reports_kml(cur, query, periods, doc) return kml.to_string(prettyprint=True)
def extract_kml(self): kml = fastkml.kml.KML() ns = '{http://www.opengis.net/kml/2.2}' doc = fastkml.kml.Document(ns, 'regions', 'Regions', 'Region names and codes used by SkyTruth') kml.append(doc) self.cur.execute(""" select distinct src from region """) srcs = [row[0] for row in self.cur] for src in srcs: folder = fastkml.kml.Folder('{http://www.opengis.net/kml/2.2}', src, src) doc.append(folder) self.cur.execute(""" select src, name, code, ST_AsText(the_geom) as the_geom from region where src = %(src)s """, {'src': src}) for row in dictreader(self.cur): keys = row.keys() keys.sort() placemark = fastkml.kml.Placemark('{http://www.opengis.net/kml/2.2}', "%(code)s" % row, "%(name)s" % row, "%(name)s (%(code)s, from %(src)s)" % row) placemark.geometry = shapely.wkt.loads(str(row['the_geom'])) folder.append(placemark) return kml.to_string(prettyprint=True)
def feed(request, format): filter = {} limit = 50 if 'l' in request.GET or 'BBOX' in request.GET: if 'l' in request.GET: lat1, lng1, lat2, lng2 = [float(x) for x in request.GET['l'].split(',')] elif 'BBOX' in request.GET: lng1, lat1, lng2, lat2 = [float(x) for x in request.GET['BBOX'].split(',')] filter['the_geom__contained'] = shapely.geometry.box(min(lng1, lng2), min(lat1, lat2), max(lng1, lng2), max(lat1, lat2)) if 'dates' in request.GET: if ',' in request.GET['dates']: start, end = request.GET['dates'].split(',') start = datetime.datetime.strptime(start, '%Y-%m-%d') end = datetime.datetime.strptime(end, '%Y-%m-%d') filter['incident_datetime__gte'] = start filter['incident_datetime__lte'] = end else: start = datetime.datetime.strptime(request.GET['dates'], '%Y-%m-%d') filter['incident_datetime__gte'] = start if 'd' in request.GET: filter['incident_datetime__gte'] = datetime.datetime.now() - datetime.timedelta(int(request.GET['d'])) if 'tag' in request.GET: filter['tags__array_contains'] = request.GET['tag'].split(',') if 'n' in request.GET: limit = int(request.GET['n']) entries = appomatic_feedserver.models.Feedentry.objects.filter(**filter).order_by('published')[:limit] if format == 'kml': kml = fastkml.kml.KML() ns = '{http://www.opengis.net/kml/2.2}' doc = fastkml.kml.Document(ns, 'docid', 'doc name', 'doc description') kml.append(doc) for entry in entries: placemark = fastkml.kml.Placemark(ns, "entry-%s" % entry.id, entry.title, entry.content) placemark.geometry = shapely.wkt.loads(entry.the_geom.wkt) # Bah, GeoDjango does not support the geo interface :( doc.append(placemark) result = kml.to_string(prettyprint=True).encode('utf-8') elif format == 'geojson': features = [] for entry in entries: geometry = fcdjangoutils.jsonview.from_json( geojson.dumps( shapely.wkt.loads( entry.the_geom.wkt))) feature = {"type": "Feature", "geometry": geometry, "properties": {'id': entry.id, 'title': entry.title, 'link': entry.link, 'summary': entry.summary, 'content': entry.content, 'source': entry.source.name, 'kml_url': entry.kml_url, 'incident_datetime': entry.incident_datetime.strftime('%Y-%m-%d %H:%M:%S'), 'published': entry.published.strftime('%Y-%m-%d %H:%M:%S'), 'regions': [{'src': region.src, 'name': region.name, 'code': region.code} for region in appomatic_mapdata.models.Region.objects.filter(id__in = entry.regions)], 'tags': entry.tags, 'source_item_id': entry.source_item_id }} features.append(feature) result = fcdjangoutils.jsonview.to_json( {"type": "FeatureCollection", "features": features}) elif format == 'csv': f = StringIO.StringIO() writer = csv.writer(f) writer.writerow(['id', 'lat', 'lng', 'title', 'link', 'summary', 'content', 'source', 'kml_url', 'incident_datetime', 'published', 'regions', 'tags', 'source_item_id']) for entry in entries: writer.writerow([entry.id, entry.lat, entry.lng, entry.title, entry.link, entry.summary, entry.content, entry.source.name, entry.kml_url, entry.incident_datetime.strftime('%Y-%m-%d %H:%M:%S'), entry.published.strftime('%Y-%m-%d %H:%M:%S'), ','.join(region.code for region in appomatic_mapdata.models.Region.objects.filter(id__in = entry.regions)), ','.join(entry.tags), entry.source_item_id ]) result = f.getvalue() elif format == 'atom': result = django.template.loader.get_template( 'appomatic_feedserver/feed.atom' ).render( django.template.RequestContext( request, {"entries": entries, "now": datetime.datetime.now(), "id": uuid.uuid4().urn})) else: # elif format == 'txt': format = 'txt' result = '\n'.join("%(title)s @ %(lat)sN %(lng)sE, %(incident_datetime)s (%(tags)s)" % DictWrapper(entry) for entry in entries) contentTypes = {'kml': 'application/kml', 'atom': 'application/atom+xml', 'geojson': 'application/json', 'csv': 'text/csv', 'txt': 'text/plain'} response = django.http.HttpResponse(result, content_type=contentTypes[format]) response['Content-Disposition'] = 'attachment; filename="feed.%s"' % (format,) return response
def output_kmz(kml, path): with zipfile.ZipFile(path, 'w') as wzf: wzf.writestr('doc.kml',kml.to_string())
def output_kml(kml, path): with open(path, 'wt') as wfp: wfp.write(kml.to_string())