Пример #1
0
    def write_kml(self):
        """Write KML file."""
        make_dir_if_not_exist(self.output_dir)
        # shamefully dump as JSON then unmarshal into a dict -- sigh.
        peak_dict = json.loads(self.tablib_data.export('json'))

        k = kml.KML()
        ns = '{http://www.opengis.net/kml/2.2}'

        # Create a KML Document and add it to the KML root object
        d = kml.Document(ns,
                         self.filename,
                         self.filename,
                         'pinmap for {}'.format(self.filename))
        k.append(d)
        kmlFolder =\
            kml.Folder(ns,
                       self.filename,
                       self.filename,
                       'kml map of list points for {}'.format(self.filename))
        for peak in peak_dict:
            details = ''
            for key, val in sorted(peak.items()):
                details += '{}: {}\n'.format(key, val)
            p = kml.Placemark(ns, peak['Name'], peak['Name'], details)
            p.geometry = Point(peak['Longitude'], peak['Latitude'])
            kmlFolder.append(p)
        d.append(kmlFolder)
        with open('{}.kml'.format(self.output_file), 'w') as output_kml:
            output_kml.write(k.to_string(prettyprint=True))
Пример #2
0
def kml_netlink(uri: str) -> str:
    ns = '{http://www.opengis.net/kml/2.2}'
    k = kml.KML(ns)

    d = kml.Document(ns, name="explorer tiles netlink")
    k.append(d)

    class NetworkLink(kml.Document):
        __name__ = 'NetworkLink'

        def __init__(self, ns=None, name=None, href=None):
            super().__init__(ns=ns, name=name)
            self._href = href

        def etree_element(self):
            href = kml.etree.Element(ns + "href")
            href.text = self._href

            link = kml.etree.Element(ns + "Link")
            link.append(href)

            e = super().etree_element()
            e.append(link)

            return e

    n = NetworkLink(ns, name="explorer tiles", href=uri)
    d.append(n)

    return k.to_string(prettyprint=True)
Пример #3
0
def write_kml():
    print('=====')
    print('===== Building KML =====')
    k = kml.KML()
    # print(k)
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', 'doc name', 'doc description')
    k.append(d)

    p = kml.Placemark(ns, 'id', 'name', 'description')
    # p.geometry = Polygon([(0,0,0), (1,1,0), (1,0,1)])
    easting = 128.4
    northing = 36.4
    elevation = 0  # does Google Earth show points that are under terrain or buildings?

    # KML uses long, lat, alt for ordering coordinates (x, y, z)
    p.geometry = Point(easting, northing, elevation)
    d.append(p)

    # kml.Placemark

    print(k.to_string(prettyprint=True))

    with open(kml_path, 'w') as f:
        f.write(k.to_string())

    with open(kml_path, 'r') as f:
        print(f.read())
Пример #4
0
    def _get_output_kml(self):
        outputkml = kml.KML()
        for doc in self.Documents:
            id = doc.id
            name = doc.name
            desc = doc.description
            outdoc = kml.Document(ns, id, name, desc)
            outputkml.append(outdoc)

            if isinstance(list(doc.features())[0], Placemark):
                out_nsfolders = self._setPlacemark_for_KML(doc.features())
                for out_nsfolder in out_nsfolders:
                    outdoc.append(out_nsfolder)
            else:
                for folder in doc.features():
                    id = folder.id
                    name = folder.name
                    desc = folder.description
                    outfolder = kml.Folder(ns, id, name, desc)
                    out_nsfolders = self._setPlacemark_for_KML(
                        folder.features())
                    for out_nsfolder in out_nsfolders:
                        outfolder.append(out_nsfolder)
                    outdoc.append(outfolder)

        return outputkml
Пример #5
0
	def write_to_kml(self,filename):
		k = kml.KML()
		ns = '{http://www.opengis.net/kml/2.2}'
		d = kml.Document(ns=ns, name='SNOPT Stitched Trajectory')

		#styles
		s = styles.Style(id='yellowLineGreenPoly')
		ls = styles.LineStyle(color='7f00ff00',width=4)
		ps = styles.PolyStyle(color='7f00ff00')
		s.append_style(ls)
		s.append_style(ps)
		d.append_style(s)

		#placemark
		pm = kml.Placemark(name='Stitched Trajectory',description='Trajectory for EADDDAS',styleUrl='#yellowLineGreenPoly')
		geom = Geometry()
		coords = []
		for i,x in enumerate(self.east):
			coord = [0]*3
			coord[1] = self.ka.lat + self.north[i]/111111.0 #lat
			coord[0] = self.ka.lon + self.east[i]/(111111.0*cos(coord[1]*pi/180)) #lon
			coord[2] = self.ka.alt + self.up[i] #alt
			coords.append(tuple(coord))
		geom.geometry = LineString(coords)
		geom.extrude = True
		geom.tessellate = True
		geom.altitude_mode = 'absolute'
		pm.geometry = geom
		d.append(pm)
		k.append(d)
		kmlfile = open(filename,"w")
		kmlfile.write(k.to_string(prettyprint=True))
		kmlfile.close()	
Пример #6
0
def create_kml_for_placemark(placemark):
    # Create the root KML object
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    data = placemark.extended_data.elements[0].data
    datadict = {}
    for kv in data:
        datadict[kv['name']] = kv['value']

    insee_dep = datadict['insee_dep']
    nom_dep = datadict['nom_dep']

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns, nom_dep, nom_dep, nom_dep)
    k.append(d)

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    d.append(placemark)

    if len(insee_dep) < 2:
        insee_dep = '0' + insee_dep
    filepath = os.path.join(GEN_ZONES, '{}-{}.kml'.format(insee_dep, nom_dep))
    with open(filepath, 'w', encoding='utf-8') as myfile:
        myfile.write(k.to_string(prettyprint=True))
    return insee_dep, filepath
Пример #7
0
def tiles_to_kml(tiles, filename, name):
    # Create the root KML object
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    s = styles.Style(id="s", styles=[styles.LineStyle(color="ff0000ff", width=1)])

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns, name=name, styles=[s])
    k.append(d)

    # Create a KML Folder and add it to the Document
    f = kml.Folder(ns, name=name)
    d.append(f)

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    for tile_id in tiles:
        tile = Tile(tile_id)
        p = kml.Placemark(ns, tile_id, styleUrl="#s")
        p.geometry = tile.line_string_lon_lat
        f.append(p)

    print(k.to_string(prettyprint=True))
    with open(filename, 'w') as hf:
        hf.write(k.to_string(prettyprint=True))
    return True
Пример #8
0
def search_target_kml(request, format=None):
    """
    A view that returns a kml file for targets given a bounding box
    """
    queryset = Target.objects.all()

    bounding_box = request.query_params['bounding_box']

    if bounding_box == '':
        bounding_box = None

    if bounding_box is not None:
        queryset = queryset.filter(coordinates__coveredby=bounding_box)

    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', 'GHGSat Document', 'Display GHGSat targets')
    k.append(d)
    f = kml.Folder(ns, 'folder1', 'Targets', 'Targets features')
    d.append(f)

    for target in queryset:
        p = kml.Placemark(ns, str(target.id), str(target.name), 'description')
        p.geometry = Point(target.coordinates.x,
                           target.coordinates.y, target.elevation)
        f.append(p)

    return Response(k.to_string(prettyprint=True))
Пример #9
0
def getKmlFromGeom(geom):
    # Create the root KML object
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns)
    k.append(d)

    # Create a KML Folder and add it to the Document
    f = kml.Folder(ns)
    d.append(f)

    # Create a KML Folder and nest it in the first Folder
    nf = kml.Folder(ns)
    f.append(nf)

    # Create a second KML Folder within the Document
    f2 = kml.Folder(ns)
    d.append(f2)

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    p = kml.Placemark(ns)
    p.geometry = geom
    f2.append(p)

    return k.to_string()
Пример #10
0
    def form_valid(self, form):
        k = kml.KML()
        ns = '{http://www.opengis.net/kml/2.2}'
        d = kml.Document(ns, 'docid', 'San Francisco Observations',
                         'KML Document')
        f = kml.Folder(ns, 'fid', 'San Francisco Observations Root Folder',
                       'Contains place marks for specimens and observations.')
        k.append(d)
        d.append(f)
        os = Occurrence.objects.all()
        for o in os:
            if (o.geom):
                p = kml.Placemark(ns, 'id', 'name', 'description')
                #coord = utm.to_latlon(o.geom.coords[0], o.geom.coords[1], 37, 'P')
                pnt = Point(o.geom.coords[0], o.geom.coords[1])
                p.name = o.__str__()
                d = "<![CDATA[<table>"
                openrow = "<tr><td>"
                middlerow = "</td><td style='font-weight:bold'>"
                closerow = "</td></tr>"

                d += openrow
                d += ''.join(("Basis of Record", middlerow))
                d += ''.join(
                    filter(None, (o.basis_of_record, closerow, openrow)))
                d += ''.join(("Time", middlerow))
                d += ''.join(
                    filter(None, (str(o.field_number), closerow, openrow)))
                d += ''.join(("Item Type", middlerow))
                d += ''.join(filter(None, (o.item_type, closerow, openrow)))
                d += ''.join(("Collector", middlerow))
                d += ''.join(filter(None, (o.collector, closerow, openrow)))
                d += ''.join(("Collection Method", middlerow))
                d += ''.join(
                    filter(None, (o.collecting_method, closerow, openrow)))
                d += ''.join(("Count", middlerow))
                d += ''.join(
                    filter(None, (str(o.individual_count), closerow, openrow)))
                d += ''.join(("Bar Code", middlerow))
                d += ''.join(filter(None, (str(o.barcode), closerow, openrow)))
                d += ''.join(("Scientific Name", middlerow))
                d += ''.join(
                    filter(None, (o.item_scientific_name, closerow, openrow)))
                d += ''.join(("Description", middlerow))
                d += ''.join(
                    filter(None, (o.item_description, closerow, openrow)))
                d += ''.join(("Remarks", middlerow))
                d += ''.join(filter(None, (o.remarks, closerow, openrow)))
                d += ''.join(("In Situ", middlerow))
                d += ''.join(filter(None, (str(o.in_situ), closerow)))
                d += "</table>"
                p.description = d
                p.geometry = pnt
                f.append(p)
        r = k.to_string(prettyprint=True)
        response = HttpResponse(r, mimetype='text/plain')
        response[
            'Content-Disposition'] = 'attachment; filename="san_francisco.kml"'
        return response
Пример #11
0
    def handle(self, *args, **options):
        """Slice and import the KML file."""
        # Open the input file and get its features.

        startTime = datetime.now()

        print("Starting at:", startTime)

        with open(options['input'], 'rt') as kmlFile:
            doc = kmlFile.read()

        fileName, fileExtension = os.path.splitext(options['input'])

        k = kml.KML()
        k.from_string(doc.replace("xsd:", "").encode('UTF-8'))
        features = list(k.features())
        features1 = list(features[0].features())
        inputStyles = list(features[0].styles())
        placemarks = list(features1[0].features())

        # Prepare the output file.
        ns = '{http://www.opengis.net/kml/2.2}'
        output = kml.KML()
        d = kml.Document(ns, 'docid', 'doc name', 'doc description')
        d._styles = inputStyles
        output.append(d)
        f = kml.Folder(ns, 'fid', 'f name', 'f description')
        d.append(f)
        nf = kml.Folder(ns, 'nested-fid', 'nested f name',
                        'nested f description')
        f.append(nf)

        # remove old entries of the state:
        toDelete = Boundery.objects.filter(state=fileName)
        toDelete.delete()

        # Parallelize the processing.
        pool = Pool(processes=8)
        print("Processing ", len(placemarks), " Placemarks in the file.")
        chunks = [placemarks[i::10] for i in range(10)]
        result = pool.map(partial(slicePlacemarks, state=fileName), chunks)

        # summarize the results.
        for pm in result:
            for pl in pm[0]:
                print(pl)
                nf.append(pl)

            Boundery.objects.bulk_create(pm[2])

        # dump the results into the output file.
        print("%s.%s" % (fileName, fileExtension))
        text_file = open("%s_sliced%s" % (fileName, fileExtension), "w")
        outputString = output.to_string()
        text_file.write(outputString)
        text_file.close()

        # print the totals.
        print("Done within:", datetime.now() - startTime)
    def handle(self, *args, **options):
        """Extract the results and write them into a KML files."""
        startTime = datetime.now()

        boundaries = Boundery.objects.filter(isMain=False, processed=True)

        k = kml.KML()
        ns = "{http://www.opengis.net/kml/2.2}"
        d = kml.Document(ns, 'docid', "Results %s" % (startTime),
                         'doc description')
        k.append(d)
        f = kml.Folder(ns, 'fid', 'all objects', 'main folder')
        d.append(f)

        style = kml.Style(ns=ns, id="KMLStyler")

        polyStyle = styles.PolyStyle(id="polystyle", color="7fe1ca9e")

        style.append_style(polyStyle)

        k._features[0]._styles.append(style)

        print(list(k.features()))

        for boundary in boundaries:

            boundaryFolder = kml.Folder(
                ns, 'fid', boundary.matchingId,
                "Found features: %s" % (boundary.address_set.count()))

            boundaryPolygon = kml.Placemark(
                ns, boundary.matchingId, boundary.matchingId,
                "Found features: %s" % (boundary.address_set.count()))

            boundaryPolygon.geometry = Polygon(list(
                boundary.polygon.coords[0]))
            boundaryPolygon.styleUrl = "KMLStyler"
            boundaryFolder.append(boundaryPolygon)

            if (options['addresses']):
                for address in boundary.address_set.all():
                    p = kml.Placemark(
                        ns, str(address.id), address.formattedAddress,
                        "confidence: %s" % (str(address.confidence)))
                    p.geometry = Point(address.point.coords)
                    p.styleUrl = "KMLStyler"
                    p.visibility = 0
                    boundaryFolder.append(p)

            f.append(boundaryFolder)

        text_file = open("./processed.kml", "w")
        outputString = k.to_string()
        text_file.write(outputString)
        text_file.close()

        print("Exporting:", boundaries.count())

        print("Done within:", datetime.now() - startTime)
Пример #13
0
    def get_kml(self):
        '''
        Render the Site as KML
        '''
        k = kml.KML()
        ns = '{http://www.opengis.net/kml/2.2}'
        ls = LineStyle(color="ffffff00", width=0.5)
        s1 = Style(id="thin_border", styles=[ls])
        d = kml.Document(ns,
                         self.site.name,
                         self.site.name,
                         "Site plan for %s" % (self.site.name),
                         styles=[s1])
        k.append(d)
        # nf = kml.Folder(ns, 'B1', 'building 1', 'Building one')
        # d.append(nf)

        # render the site reference mark as a KML Placemark
        p = kml.Placemark(ns, 'ref_mark', self.site.name,
                          'Reference survey mark')
        p.geometry = self.site.ref_mark
        d.append(p)

        # compute the UTM coords of the Site reference point

        crs = get_epsg(self.site.ref_mark)
        site_UTM = get_UTM_from_long_lat(self.site.ref_mark)
        project_UTM_to_WGS84 = partial(pyproj.transform, pyproj.Proj(init=crs),
                                       pyproj.Proj(init='epsg:4326'))

        folder = kml.Folder(ns, 'Structures', 'Structures',
                            'Structures on the site')
        d.append(folder)

        # render each Structure

        for s in self.site.structures:
            name = s.name
            # work with the outline of the structure
            outline = s.geometry.buffer(0)
            # move outline into UTM coordinates for the site
            outline = translate(outline, xoff=site_UTM.x, yoff=site_UTM.y)
            # and transform to WGS84
            outline = transform(project_UTM_to_WGS84, outline)

            # place the outline in Structures folder
            p = kml.Placemark(ns,
                              name,
                              name,
                              s.description,
                              styleUrl="#thin_border")
            p.geometry = outline
            folder.append(p)

        # return the KML

        return k.to_string(prettyprint=True)
Пример #14
0
def colorizedGlyph(data, folderPath, docname, nbins, limits, cmap_type):
	# data: a numpy matrix with [latitude, longitude, height, f] in each row. Where f is the variable asociated with the color.
	# folderPath: a string with the folder path
	# nbins: number of beans of the color map
	# limits: a list [min, max] which are the limits of our color scale.
	# cmap_type: a string with the name of the colormap. Read matplotlib.cm reference for further information.
	
	 
	colormap = cm.get_cmap(cmap_type, nbins)
	
	
	# Create the root KML object
	k = kml.KML()
	ns = '{http://www.opengis.net/kml/2.2}'

	# Create a KML Document and add it to the KML root object
	docid=''
	docdescription='This file was generated automaticaly with fastKML to colorize the aeroglyph.'
	kdoc = kml.Document(ns, docid, docname, docdescription)
	k.append(kdoc)
	
	# Create a KML Folder and add it to the Document
	folder1 = kml.Folder(ns, '', 'aeroglyph', '')
	kdoc.append(folder1)
	
	
	puntoPrev=[]
	idPunto=0
	for punto in data:
		if(idPunto!=0):
			u=(punto[3]-limits[0])/(limits[1]-limits[0])
			uprev=(puntoPrev[3]-limits[0])/(limits[1]-limits[0])
			u=(u+uprev)/2
			
			rgbcolor=colormap(u)
			
			hexcolor=colors.to_hex(rgbcolor, keep_alpha=True)
			hexcolor=hexcolor[-2:]+hexcolor[1:7]
			

			# Create a Placemark with a LineString geometry and add it to the Document
			estilolinea = styles.LineStyle(ns, color=hexcolor, width=4)
			estilo = styles.Style(styles=[estilolinea])
			p = kml.Placemark(ns, str(idPunto), styles=[estilo])
			p.geometry =  LineString([puntoPrev[0:3], punto[0:3]])
			# _geometry attribute is supposed not to be accessed directly
			# we have to look for a better solution using fastkml functions.
			p._geometry.altitude_mode='absolute'
			folder1.append(p)
			
		puntoPrev=punto
		idPunto+=1
	
	# write kml buffer to our file.
	fileHandle= open(folderPath+docname+'.kml',"w+")
	fileHandle.write(k.to_string(prettyprint=True))
	fileHandle.close()
Пример #15
0
def export(filename: str):
    global current_document
    kml_tree = kml.KML()
    current_document = kml.Document()
    yield current_document
    kml_tree.append(current_document)
    with open(filename, "w", encoding="utf8") as kml_file:
        kml_file.write(kml_tree.to_string(prettyprint=True))
    _stylemap.clear()
    current_document = None
Пример #16
0
def write_kml(messages, output_filename):
    """ Sort messages on timestamp, convert to KML and write to disk """
    # Sort since when saving to a file on the watch, they may be out of order
    messages.sort(key=lambda x: x.epoch)

    # Create KML file
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'watch-loc-data', 'Watch location data')
    k.append(d)
    f = kml.Folder(ns, 'all-data', 'All location data')
    d.append(f)
    s = [
        kml.Style(ns, 'styles', [
            styles.LineStyle(ns, 'linestyle', 'FF0000FF', width=2),
            styles.PolyStyle(ns, 'polystyle', '00FFFFFF'),
        ])
    ]

    i = 0
    pt_prev = None
    ts_prev = None

    for msg in messages:
        if msg.message_type == SensorData.MESSAGE_TYPE_LOCATION:
            # Skip if invalid lat/lon/alt value
            if msg.longitude == 0.0 and msg.latitude == 0.0 and msg.horiz_acc == 0.0:
                continue
            if msg.altitude == 0.0 and msg.vert_acc == 0.0:
                continue

            ts = datetime.fromtimestamp(msg.epoch)
            pt = (msg.longitude, msg.latitude, msg.altitude)

            # We're drawing lines between points, so skip the first point
            if i != 0:
                p = kml.Placemark(ns,
                                  'point-' + str(i),
                                  'point-' + str(i),
                                  styles=s)
                p.geometry = geometry.Geometry(ns,
                                               'geometry-' + str(i),
                                               geometry.Polygon(
                                                   [pt_prev, pt, pt, pt_prev]),
                                               altitude_mode='absolute')
                p.begin = ts_prev
                p.end = ts
                f.append(p)

            i += 1
            pt_prev = pt
            ts_prev = ts

    with open(output_filename, "w") as f:
        f.write(k.to_string(prettyprint=True))
Пример #17
0
def document(name='', description='', shapes=[]):
    k = kml.KML()

    d = kml.Document(VERSION, 'root', 'Boxes', '')
    k.append(d)

    f = kml.Folder(VERSION, 'content', name, description)
    d.append(f)

    for shape in shapes:
        f.append(shape)
    return k
Пример #18
0
def main():
    # read all the EXIF data from the target folder (or webserver?)
    # generate a KML with points
    # date-time of photo
    # any other EXIF data
    # make a KMZ that includes the photos (or URL to show the photo in Google Earth)

    # 2 approaches:
    #       1. Batch process everything in phases, doing one action to all the objects
    #       2. Process each item individually through the phases. DevOps = small batch size
    # Going with option 2.

    # initialize the KML document
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', 'doc name',
                     'doc description')  # TODO update fields
    k.append(d)

    files = []
    for (dirpath, dirnames, filesnames) in walk(target):
        path_filenames = []
        for file in filesnames:
            path_filenames.append(dirpath + file)
        files.extend(path_filenames)
        break  # call to walk only the top directory

    for file in files:
        # print(file)
        # read EXIF
        # with open(file) as f:  # exifread takes filenames
        # tags = exifread.process_file(file)  # exifgps can open files also

        # convert EXIF coordinate format to KML coordinate format
        imagegps = exifgps.read(file)
        # print(imagegps)
        imagegps.process_exif()
        if imagegps._has_gps:
            print(file, imagegps._decimal_degrees)

            northing, easting = imagegps._decimal_degrees  # order is latitude, longitude
            elevation = 0

            # construct the KML tag and add it
            # TODO set the relative altitude mode...
            p = kml.Placemark(ns, file, file, file)
            # KML uses long, lat, alt for ordering coordinates (x, y, z)
            p.geometry = Point(easting, northing, elevation)
            d.append(p)
    # finish the KML
    print(k.to_string(prettyprint=True))
    with open(kml_path, 'w') as f:
        f.write(k.to_string())
Пример #19
0
def generate_kml(meshviewer):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns)
    k.append(d)

    for n in meshviewer['nodes']:
        if 'location' not in n:
            continue

        if 'latitude' not in n['location']:
            continue

        if 'longitude' not in n['location']:
            continue

        if 'hostname' not in n:
            continue

        if 'node_id' not in n:
            continue

        if 'is_online' not in n:
            continue

        extended = kml.ExtendedData()

        p = kml.Placemark(ns, n['node_id'], n['hostname'])
        p.geometry = Point(n['location']['longitude'],
                           n['location']['latitude'])
        d.append(p)

        extended = []

        if n['is_online']:
            status = "online"
        else:
            status = "offline"

        extended.append(
            kml.Data(value=status, name='status', display_name='Status'))

        url = 'https://vogtland.freifunk.net/map/#!/map/' + n['node_id']
        extended.append(kml.Data(value=url, name='url', display_name='URL'))

        p.extended_data = kml.ExtendedData(elements=extended)

    return k
Пример #20
0
def getCurrentStateKml(serverUrl, rest=True):
    ''' Create the overall KML for the current state of the air quality.
    If we can't get fresh data, return None
    serverUrl = the url of the server providing this KML, so we can have the network link and the icons.
    '''

    # Try to get data
    global CURRENT_DATA
    CURRENT_DATA = getData()

    global SERVER_URL
    SERVER_URL = serverUrl

    # Create the root KML object
    topKml = kml.KML()

    if rest:
        global ICON_PATH
        ICON_PATH = '/static/rest/basaltApp/icons/hvnp_air_quality'

    # Create a KML Document and add it to the KML root object
    document = kml.Document(
        NAME_SPACE,
        'hvnp_caq_doc',
        "Hawai'i Volcanoes National Park",
        "Approximate direction of the volcanic gas plumes (wedges) from Halema'uma'u and Pu'u 'O'o. Colored circles show the current air quality conditions for sulfur dioxide and particulate matter at each monitoring site.",
        styles=buildStyles())

    topKml.append(document)
    if not CURRENT_DATA:
        document.description = "NO DATA; Cannot reach server"
        return document.to_string(prettyprint=True)

    # Read and interpret the current conditions
    getConditions()

    # Build a top level KML folder
    topFolder = kml.Folder(NAME_SPACE, 'hvnp_caq_doc', 'Current Air Quality',
                           getConditionsString())

    # Build placemarks for all the found sites
    buildSites(topFolder)

    # Put the document together
    document.append(topFolder)

    # Return the KML as a string.
    return document.to_string(prettyprint=True)
Пример #21
0
def generate_kml(fname, poi_df):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    styid = 'style1'
    # colors in KML: aabbggrr, aa=00 is fully transparent
    sty = styles.Style(id=styid,
                       styles=[styles.LineStyle(color='9f0000ff',
                                                width=2)])  # transparent red
    doc = kml.Document(ns, '1', 'POIs', 'POIs visualization', styles=[sty])
    k.append(doc)

    # Placemark for POIs
    for ix in poi_df.index:
        name = poi_df.loc[ix, 'poiName']
        cat = poi_df.loc[ix, 'poiTheme']
        lat = poi_df.loc[ix, 'poiLat']
        lon = poi_df.loc[ix, 'poiLon']
        url = poi_df.loc[ix, 'poiURL']
        ext_data = kml.ExtendedData(
            ns,
            elements=[
                kml.Data(
                    name='video',
                    value=
                    "![CDATA[<iframe name='Framename' width='480' height='360' src='%s' frameborder='0'></iframe><br><br>]]"
                    % (url))
            ])

        desc = ''.join([
            'POI Name: ', name, '<br/>Category: ', cat,
            '<br/>Coordinates: (%f, %f)' % (lat, lon), '<br/>URL: ', url
        ])
        pm = kml.Placemark(ns,
                           str(ix),
                           name,
                           desc,
                           styleUrl='#' + styid,
                           extended_data=ext_data)
        pm.geometry = Point(lon, lat)
        doc.append(pm)

    # save to file
    kmlstr = k.to_string(prettyprint=True)
    with open(fname, 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write(kmlstr)
Пример #22
0
def make_kml(polys, filename):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', 'doc name', 'doc description')
    f = kml.Folder(ns, 'fid', 'f name', 'f description')
    k.append(d)
    d.append(f)
    nf = kml.Folder(ns, 'nested-fid', 'nested f name', 'nested f description')
    f.append(nf)
    f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
    d.append(f2)
    for poly in polys:
        p = kml.Placemark(ns, 'id', 'name', 'description')
        p.geometry = poly
        f2.append(p)
    # print k.to_string(prettyprint=True)
    with open(filename, 'wb') as f:
        f.write(k.to_string())
    def configure_document_root(self):
        root_document = fkml.Document(ns=self.NS, id='root-doc')
        self.register_schemas(root_document)

        self.kml_root = fkml.KML(ns=self.NS)
        self.kml_root.append(root_document)

        self.coord_container = fkml.Folder(ns=self.NS,
                                           id='coordinates',
                                           name='coordinates')

        self.coord_container.extended_data = fkml.SchemaData(
            ns=self.NS,
            schema_url=self.schema_set['document_metadata'],
            data=[{
                'name': 'gen_date',
                'value': NOW.strftime(self.TS_OUTPUT_FMT)
            }, {
                'name': 'spatial_reference',
                'value': self.projection
            }])

        root_document.append(self.coord_container)
Пример #24
0
    def setup_gradient_and_t(self, steps):
        red = Color("blue")
        colors = list(red.range_to(Color("green"), steps))
        styles = []
        for idx, value in enumerate(colors):
            # DEBUG: print (f'VALUE: {value.hex_l}')
            style_id = "style-"
            idx_inc = idx + 1
            style_id += str(idx_inc)
            lineStyle = LineStyle(
            )  #self.name_space,f'line-{idx_inc}',Color("white").hex_l)
            polyStyle = PolyStyle(self.name_space, f'poly-{idx_inc}',
                                  value.hex_l.replace('#', '#88'))
            this_style = kml.Style(self.name_space, style_id,
                                   (polyStyle, lineStyle))
            styles.append(this_style)

        self.cell_document = kml.Document(self.name_space, 'mgrs-doc', 'Cells',
                                          'MGRS cells matching query', styles)
        # try and limit returns
        # self.threshold = steps - 1 if steps > 1 else 1
        self.threshold = 0
        return styles
Пример #25
0
def kml_file_from_polygons(polygons, kml_file):
    if not isinstance(polygons, Iterable):
        polygons = [polygons]
    # Create the root KML object
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns, 'docid', 'Zone unexplored tiles',
                     'Zone unexplored tiles')
    k.append(d)

    # Create a KML Folder and add it to the Document
    f = kml.Folder(ns)
    d.append(f)

    # Create a KML Folder and nest it in the first Folder
    nf = kml.Folder(ns)
    f.append(nf)

    # Create a second KML Folder within the Document
    f2 = kml.Folder(ns)
    d.append(f2)

    # ls = styles.LineStyle(ns, color='red', width=3)
    # s1 = styles.Style(styles=[ls])

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    for polygon in polygons:
        # p = kml.Placemark(ns, styles=[s1])
        p = kml.Placemark(ns)
        p.geometry = polygon
        f2.append(p)

    with open(kml_file, 'w') as myfile:
        myfile.write(k.to_string(prettyprint=True))
Пример #26
0
def kml_tiles(geometry, max_sq_geometry=None, individual: bool = False) -> str:
    ns = '{http://www.opengis.net/kml/2.2}'
    k = kml.KML(ns)

    style_normal = kml_styles.Style(id='normal',
                                    styles=[
                                        kml_styles.LineStyle(color="400000ff",
                                                             width=1),
                                        kml_styles.PolyStyle(
                                            color="300000ff",
                                            outline=(1 if individual else 0)),
                                    ])
    style_max_sq = kml_styles.Style(id='max_sq',
                                    styles=[
                                        kml_styles.LineStyle(color="40ff0000",
                                                             width=1),
                                        kml_styles.PolyStyle(
                                            color="30ff0000",
                                            outline=(1 if individual else 0)),
                                    ])

    d = kml.Document(ns,
                     name="explorer tiles",
                     styles=[style_normal, style_max_sq])
    k.append(d)

    p = kml.Placemark(ns, styleUrl="#normal")
    p.geometry = geometry
    d.append(p)

    if max_sq_geometry:
        p = kml.Placemark(ns, styleUrl="#max_sq")
        p.geometry = max_sq_geometry
        d.append(p)

    return k.to_string(prettyprint=True)
def create_kml_for_placemark(placemark):
    # Create the root KML object
    kml_doc = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'

    data = placemark.extended_data.elements[0].data
    datadict = {}
    for kv in data:
        datadict[kv['name']] = kv['value']

    nom_province = datadict['nom_province']

    # Create a KML Document and add it to the KML root object
    d = kml.Document(ns, nom_province, nom_province, nom_province)
    kml_doc.append(d)

    # Create a Placemark with a simple polygon geometry and add it to the
    # second folder of the Document
    d.append(placemark)

    filepath = os.path.join(GEN_ZONES, 'BE-{}.kml'.format(nom_province))
    with open(filepath, 'w', encoding='utf-8') as kml_handle:
        kml_handle.write(kml_doc.to_string(prettyprint=True))
    return nom_province, filepath
Пример #28
0
    def convert_to_kml(self):
        output_filename = self.flight_name + ".kml"

        k = kml.KML()
        ns = '{http://www.opengis.net/kml/2.2}'

        d = kml.Document(ns)
        k.append(d)
        f = kml.Folder(ns)
        d.append(f)

        i = 0
        for row in self.geotags_list:
            row_num = [float(tag) for tag in row]
            row_num[0], row_num[1] = row_num[1], row_num[0]

            p = kml.Placemark(ns, str(i))
            p.geometry = Point(row_num)
            f.append(p)
            i += 1

        kml_file = open(output_filename, "w")
        kml_file.write(k.to_string(prettyprint=True))
        kml_file.close()
Пример #29
0
def convert(infilename, outfilename='doc.kml', namecolumn=0):
    sf = shapefile.Reader(infilename)
    k = kml.KML()
    doc = kml.Document(name=infilename)
    k.append(doc)
    for sr in sf.shapeRecords():
        if sr.shape.points:
            pm = kml.Placemark(name=unicode(sr.record[namecolumn]),
                               description="test")
            if not hasattr(sr.shape, '__geo_interface__'):
                import ipdb
                ipdb.set_trace()

            pm.geometry = pygeoif.as_shape(sr.shape)
            doc.append(pm)
            if sr.shape.__geo_interface__ != pygeoif.as_shape(
                    sr.shape).__geo_interface__:
                #import ipdb; ipdb.set_trace()
                print sr.record
                print len(sr.shape.__geo_interface__['coordinates']), len(
                    pygeoif.as_shape(
                        sr.shape).__geo_interface__['coordinates'])
                print sr.shape.__geo_interface__['type'], pygeoif.as_shape(
                    sr.shape).__geo_interface__['type']
                #for i in range(0,len(sr.shape.__geo_interface__['coordinates'])):
                #    print sr.shape.__geo_interface__['coordinates'][i] == pygeoif.as_shape(sr.shape).__geo_interface__['coordinates'][i]

    xml = '<?xml version="1.0" encoding="UTF-8"?>' + k.to_string()
    #try:
    #    xml = xml.decode('utf-8', 'ignore')
    #except:
    #    pass
    #xml =  xml.encode('utf-8')
    out = open(outfilename, 'w')
    out.write(xml)
    out.close()
def gen_kml(fname, traj_data, traj_stats, traj_id_list, traj_name_list=None):
    """Generate KML file"""
    assert (len(traj_id_list) > 0)
    if traj_name_list:
        assert (len(traj_id_list) == len(traj_name_list))

    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    stid = 'style1'
    # colors in KML: aabbggrr, aa=00 is fully transparent
    # developers.google.com/kml/documentation/kmlreference?hl=en#colorstyle
    st = styles.Style(id=stid,
                      styles=[styles.LineStyle(color='2f0000ff',
                                               width=3)])  # transparent red
    doc = kml.Document(ns,
                       '001',
                       'Trajectories',
                       'Trajectory visualization',
                       styles=[st])
    k.append(doc)

    stats = traj_stats[traj_stats['Trajectory_ID'].isin(traj_id_list)]
    assert (stats.shape[0] == len(traj_id_list))

    pm_traj = []
    pm_photo = []

    for i in range(len(stats.index)):
        ri = stats.index[i]
        traj_id = stats.ix[ri]['Trajectory_ID']
        photos = traj_data[traj_data['Trajectory_ID'] == traj_id]
        lngs = [lng for lng in photos['Longitude'].tolist()]
        lats = [lat for lat in photos['Latitude'].tolist()]
        name = 'Trajectory_' + str(traj_id)
        if traj_name_list: name += '_' + traj_name_list[i]
        desc = 'User_ID: '              + str(stats.ix[ri]['User_ID']) + \
               '<br/>Start_Time: '      + str(stats.ix[ri]['Start_Time']) + \
               '<br/>Travel_Distance: ' + str(round(stats.ix[ri]['Travel_Distance(km)'], 2)) + ' km' + \
               '<br/>Total_Time: '      + str(round(stats.ix[ri]['Total_Time(min)'], 2)) + ' min' + \
               '<br/>Average_Speed: '   + str(round(stats.ix[ri]['Average_Speed(km/h)'], 2)) + ' km/h' + \
               '<br/>#Photos: '         + str(stats.ix[ri]['#Photo']) + \
               '<br/>Photos: '          + str(photos['Photo_ID'].tolist())
        pm = kml.Placemark(ns, str(traj_id), name, desc, styleUrl='#' + stid)
        pm.geometry = LineString([(lngs[j], lats[j])
                                  for j in range(len(lngs))])
        pm_traj.append(pm)

        for rj in photos.index:
            name = 'Photo_' + str(photos.ix[rj]['Photo_ID'])
            desc = 'Trajectory_ID: '  + str(traj_id) + \
                   '<br/>Photo_ID: '  + str(photos.ix[rj]['Photo_ID']) + \
                   '<br/>User_ID: '   + str(photos.ix[rj]['User_ID']) + \
                   '<br/>Timestamp: ' + str(photos.ix[rj]['Timestamp']) + \
                   '<br/>Coordinates: (' + str(photos.ix[rj]['Longitude']) + ', ' + str(photos.ix[rj]['Latitude']) + ')' + \
                   '<br/>Accuracy: '  + str(photos.ix[rj]['Accuracy']) + \
                   '<br/>URL: '       + str(photos.ix[rj]['URL'])
            pm = kml.Placemark(ns, str(photos.ix[rj]['Photo_ID']), name, desc)
            pm.geometry = Point(photos.ix[rj]['Longitude'],
                                photos.ix[rj]['Latitude'])
            pm_photo.append(pm)

    for pm in pm_traj:
        doc.append(pm)
    for pm in pm_photo:
        doc.append(pm)

    kmlstr = k.to_string(prettyprint=True)
    with open(fname, 'w') as f:
        f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        f.write(kmlstr)