Exemple #1
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()
    def _setPlacemark_for_KML(self, upstream_feature):
        output_df = self.outputdf
        out_nsfolders = []
        for placemark in upstream_feature:
            id = placemark.id
            name = placemark.name
            desc = placemark.description
            # creating nested folder
            out_nsfolder = kml.Folder(ns, id, name, desc)
            # creating placemarks (points and LineString)
            Lines = self.info_df[self.info_df['Trace'].str.contains(
                name)]['Outputs'].to_list()
            line_names = self.info_df[self.info_df['Trace'].str.contains(
                name)]['Trace'].to_list()
            outplacemarks = gen_placemark_from_Line(Lines, ns, line_names)
            for pm in outplacemarks:
                out_nsfolder.append(pm)

            out_points_folder = kml.Folder(ns, id, name='Poteaux')
            if not self.offset:
                for Line in Lines:
                    for point in Line:
                        id = str(Line.index(point))
                        point_name = output_df[output_df['Name'].str.contains(
                            placemark.name)]['Number'].to_list()
                        name = point_name[Line.index(point)]
                        desc = 'Electric Pole'
                        outpoint = kml.Placemark(ns, id, name, desc)
                        outpoint.geometry = Point(point)
                        out_points_folder.append(outpoint)
                out_nsfolder.append(out_points_folder)
            out_nsfolders.append(out_nsfolder)

        return out_nsfolders
    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)
Exemple #4
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 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))
Exemple #6
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
Exemple #7
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))
    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
Exemple #9
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
Exemple #10
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())
Exemple #11
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()
Exemple #12
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)
    def get_coord_folder(self, coord):
        folder = self.coord_cache.get(coord)
        if folder:
            return folder

        folder = fkml.Folder(ns=self.NS, name=coord, id='f-{}'.format(coord))

        folder.extended_data = fkml.SchemaData(
            ns=self.NS,
            schema_url=self.schema_set['coordinate_metadata'],
            data=[{
                'name': 'coord',
                'value': coord
            }])

        visible_marker = fkml.Placemark(ns=self.NS,
                                        name=coord,
                                        id='pl-{}'.format(coord))

        # Dummy data required by QGIS to display all columns
        dummy_data = [
            {
                'name': 'uuid',
                'value': None
            },
            {
                'name': 'wrs2_path_row',
                'value': None
            },
            {
                'name': 'netcdf_slice',
                'value': None
            },
        ]

        for band in self.bands:
            dummy_data.append({'name': 'band_{}'.format(band), 'value': None})

        visible_marker.extended_data = fkml.SchemaData(
            ns=self.NS,
            schema_url=self.schema_set['placemark_metadata'],
            data=dummy_data)

        visible_marker.geometry = Geometry(
            ns=self.NS,
            geometry=Polygon(
                get_grid_perimeter(*[int(i) for i in coord.split('_')])))

        visible_marker.description = ''
        folder.append(visible_marker)

        self.coord_container.append(folder)
        self.coord_cache[coord] = folder

        return folder
Exemple #14
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))
Exemple #15
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
Exemple #16
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))
def nestedKMLSearch(kmlFolder):
    gps = dict()
    
    if type(kmlFolder) == type(list()):
        for i in range(len(kmlFolder)):
            gps = nestedKMLSearch(kmlFolder[i])
    elif type(kmlFolder) == type(kml.Folder()):
        f = list(kmlFolder.features())
        if type(f[0]) == type(kml.Folder()):
            gps = nestedKMLSearch(f[0])
        else:
            if type(f[0]) == type(kml.Placemark()):
                for i in range(len(f)):
                    gps[f[i].name] = []
                    if "_geometry" in f[i].__dict__.keys():
                        if "geometry" in f[i].__dict__["_geometry"].__dict__.keys():
                            gps[f[i].name] = np.array(f[i].__dict__["_geometry"].__dict__["geometry"])
    else:
        # kmlFolder is a placemark
        gps[kmlFolder.name] = []
        if "_geometry" in kmlFolder.__dict__.keys():
            if "geometry" in kmlFolder.__dict__["_geometry"].__dict__.keys():
                gps[kmlFolder.name] = np.array(kmlFolder.__dict__["_geometry"].__dict__["geometry"])
    return gps
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)
Exemple #19
0
def _airspace_export_kml(
    sector: Airspace,
    styleUrl: Optional[kml.StyleUrl] = None,
    color: Optional[str] = None,
    alpha: float = 0.5,
) -> kml.Placemark:
    if color is not None:
        # the style will be set only if the kml.export context is open
        styleUrl = toStyle(color)
    folder = kml.Folder(name=sector.name, description=sector.type)
    for extr_p in sector:
        for elt in sector.decompose(extr_p):
            placemark = kml.Placemark(styleUrl=styleUrl)
            placemark.geometry = kml.Geometry(geometry=elt,
                                              altitude_mode="relativeToGround")
            folder.append(placemark)
    return folder
    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)
Exemple #21
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()
Exemple #22
0
# Import the library
from fastkml import kml
from shapely.geometry import Point, LineString, Polygon

# 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', 'doc name', 'doc description')
k.append(d)

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

# Create a KML Folder and nest it in the first Folder
nf = kml.Folder(ns, 'nested-fid', 'nested f name', 'nested f description')
f.append(nf)

# Create a second KML Folder within the Document
f2 = kml.Folder(ns, 'id2', 'name2', 'description2')
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, 'id', 'name', 'description')
p.geometry = Polygon([(0, 0, 0), (1, 1, 0), (1, 0, 1)])
f2.append(p)

# Print out the KML Object as a string
Exemple #23
0
def main(argv):
    # Get command line options
    try:
        opts, args = getopt.getopt(argv, "hf:o:a:",
                                   ["filepath=", "long-start=", "lat-start="])
    except getopt.GetoptError:
        print 'create-haworth-cemetery-f-kml.py -f <filepath> -o <long start> -a <lat start>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'create-haworth-cemetery-f-kml.py -f <filepath> -o <long start> -a <lat start>'
            sys.exit()
        elif opt in ("-f", "--filepath"):
            filepath = arg
        elif opt in ("-o", "--long-start"):
            long_start = float(arg)
        elif opt in ("-a", "--lat-start"):
            lat_start = float(arg)

    map_origin = Point(long_start, lat_start)

    # Read in all the graves as objects and stick them in a grid.
    graveyard = [[None for i in range(GRAVEYARD_MAX_SIZE)]
                 for j in range(GRAVEYARD_MAX_SIZE)]
    with open(filepath) as csvfile:
        reader = csv.DictReader(csvfile)
        for r in reader:
            if r['column']:
                row = int(r['row'])
                column = int(r['column'])
                graveyard[row][column] = Grave(r['section'], r['grave_id'],
                                               row, column, r['inscription'])
    # Create the root KML object.
    k = kml.KML()

    # Create the KML Document styles to use.
    doc_styles = []
    a = []
    a.append(styles.LineStyle(NS, None, 'ffbdbdbd'))
    a.append(styles.PolyStyle(NS, None, '4dbdbdbd'))
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-normal', a))
    a[0] = styles.LineStyle(NS, None, 'ffbdbdbd', None, 2)
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-highlight', a))
    doc_styles.append(
        kml.StyleMap(NS, "poly-BDBDBD-1-77",
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-normal'),
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-highlight')))

    # Create the KML Document, and add it to the KML root object.
    d = kml.Document(NS, None, NAME, DESCRIPTION.format(SECTION), doc_styles)
    k.append(d)

    # Create a KML Folder for the section and add it to the Document.
    f = kml.Folder(NS, None, "Section {}".format(SECTION))
    k.append(f)

    # Process the graveyard grid, creating a Placemark with a polygon for each grave.
    for i in range(GRAVEYARD_MAX_SIZE):
        for j in range(GRAVEYARD_MAX_SIZE):
            if graveyard[i][j]:
                g = graveyard[i][j]
                name = '{}-{}'.format(g.section, g.grave_id)
                p = kml.Placemark(NS, None, name.lower(), g.inscription, None,
                                  '#poly-BDBDBD-1-77')
                lon = long_start + (i * (LONG_2FEET * 3))
                lat = lat_start + (j * (LAT_2FEET * 2))
                p.geometry = Polygon([
                    (lon, lat, 0), (lon + LONG_3FEET + LONG_2FEET, lat, 0),
                    (lon + LONG_3FEET + LONG_2FEET, lat + LAT_3FEET, 0),
                    (lon, lat + LAT_3FEET, 0), (lon, lat, 0)
                ])
                p.geometry = shapely.affinity.rotate(p.geometry,
                                                     ADJUSTMENT_ANGLE,
                                                     map_origin)
                f.append(p)

    # Print out the KML Object as a string.
    print k.to_string(prettyprint=True)
Exemple #24
0
busroutes = sorted(glob.glob('tfl_bus_routes/*.json'))

for busroute in busroutes:

    with open(busroute) as f:
        route = json.load(f)

    print('Processing %s %s... ' % (route['lineId'], route['direction']),
          end="",
          flush=True)

    l = ast.literal_eval(route['lineStrings'][0])

    line = LineString(l[0])

    k = kml.KML()
    d = kml.Document(ns, 'Tfl Bus route', route['lineId'],
                     "%s %s" % (route['lineId'], route['direction']))
    k.append(d)
    f = kml.Folder(ns, 'fid', 'bus route', '')
    d.append(f)
    p = kml.Placemark(ns, 'id', 'route', '')
    p.geometry = line
    k.append(p)

    with open(
            DESTDIR + '/' +
            busroute.replace('tfl_bus_routes/', '').replace('json', 'kml'),
            'w') as w:
        w.write(k.to_string(prettyprint=True))
Exemple #25
0
#f.append(nf)
recorded_data_description="\
100 m segment cuts with statistics.\n\
Click any point on the track to display mm/m value of a 100 m\n\
segment measured before the point. Value represents average\n\
rectified speed in the shock absorber over 100 m segment\n\
and divided by standard speed of 80 km/h. Value comes from the\n\
numeric model that calculates response at standard speed,\n\
removing dependency on actual speed at which measurement has been done.\n\
\n\
Color codes:\n\
<font color=\"red\">%.1f</font>, <font color=\"orange\">%.1f</font>, <font color=\"green\">%.1f</font>, <font color=\"cyan\">%.1f</font>, \
<font color=\"blue\">%.1f</font>, <font color=\"violet\">%.1f</font>, <font color=\"magenta\">0.0</font>\n\
" % (red_iri, 2.0/2.5*red_iri, 1.5/2.5*red_iri, 1.0/2.5*red_iri,
0.5/2.5*red_iri, 0.3/2.5*red_iri)
f2 = kml.Folder(ns, id='folderid', name='Recorded data', description=recorded_data_description)
d.append(f2)
t = kml.TimeStamp()

arrow_icon_href="http://maps.google.com/mapfiles/kml/shapes/arrow.png"

# buffer to read wav
b=bytearray(12)
mvb=memoryview(b)

# matrix is already calculated for sampling_length = 0.05 m
# for different sampling_lenghth, calculate new matrix:
if sampling_length != 0.05:
  st_pr(DX=sampling_length)
#print(ST)
#print(PR)
Exemple #26
0
    ]

    polygons.append(polygon)
    prev_point = cur_point

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

polystyle = fastkml.styles.PolyStyle(ns=ns, color='ccccccaa', outline=0)
linestyle = fastkml.styles.LineStyle(ns=ns, color='ff0000ff', width=10)
styles = fastkml.styles.Style(ns=ns,
                              id='TheStyle',
                              styles=[polystyle, linestyle])
d = kml.Document(ns, 'docid', 'doc name', 'doc description', styles=[styles])
k.append(d)
f = kml.Folder(ns, 'fid', 'f name', 'f description')
d.append(f)

for polygon in polygons:
    p = kml.Placemark(ns, 'id', 'name', 'description', styleUrl='#TheStyle')
    p.geometry = fastkml.geometry.Geometry(
        ns=ns,
        geometry=Polygon(polygon),
        altitude_mode='relativeToGround',
    )
    f.append(p)

p = kml.Placemark(ns, styleUrl='#TheStyle')
p.geometry = fastkml.geometry.Geometry(ns=ns,
                                       geometry=LineString(points),
                                       altitude_mode='relativeToGround')
def main(argv):
    # Get command line options
    try:
        opts, args = getopt.getopt(argv, "ho:a:",
                                   ["long-start=", "lat-start="])
    except getopt.GetoptError:
        print 'test-rotation-kml.py -o <long start> -a <lat start>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'test-rotation-kml.py -o <long start> -a <lat start>'
            sys.exit()
        elif opt in ("-o", "--long-start"):
            long_start = float(arg)
        elif opt in ("-a", "--lat-start"):
            lat_start = float(arg)

    map_origin = Point(long_start, lat_start)

    k = kml.KML()

    # Create the KML Document styles to use.
    doc_styles = []
    a = []
    a.append(styles.LineStyle(NS, None, 'ffbdbdbd'))
    a.append(styles.PolyStyle(NS, None, '4dbdbdbd'))
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-normal', a))
    a[0] = styles.LineStyle(NS, None, 'ffbdbdbd', None, 2)
    doc_styles.append(kml.Style(NS, 'poly-BDBDBD-1-77-highlight', a))
    doc_styles.append(
        kml.StyleMap(NS, "poly-BDBDBD-1-77",
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-normal'),
                     kml.StyleUrl(NS, None, '#poly-BDBDBD-1-77-highlight')))

    # Create the KML Document, and add it to the KML root object.
    d = kml.Document(NS, None, NAME, DESCRIPTION.format(SECTION), doc_styles)
    k.append(d)

    # Create a KML Folder for the section and add it to the Document.
    f = kml.Folder(NS, None, "Section {}".format(SECTION))
    k.append(f)

    # Process a spiral of markers in a counter-clockwise direction
    lon = long_start + (OBJECT_START_ROW * (LONG_2FEET * 3))
    lat = lat_start + (OBJECT_START_COL * (LAT_2FEET * 2))
    adjustment_angle = 0.00
    while adjustment_angle < 360:
        name = 'Degrees: {}'.format(adjustment_angle)
        p = kml.Placemark(NS, None, name, "Test Rotation", None,
                          '#poly-BDBDBD-1-77')
        p.geometry = Polygon([(lon, lat, 0),
                              (lon + LONG_3FEET + LONG_2FEET, lat, 0),
                              (lon + LONG_3FEET + LONG_2FEET, lat + LAT_3FEET,
                               0), (lon, lat + LAT_3FEET, 0), (lon, lat, 0)])
        p.geometry = shapely.affinity.rotate(p.geometry, adjustment_angle,
                                             map_origin)
        f.append(p)
        adjustment_angle += ADJUSTMENT_ANGLE_INCR

    # Print out the KML Object as a string.
    print k.to_string(prettyprint=True)
Exemple #28
0
db.start()
while db.init:
    time.sleep(0.1)

data = db.Get("SELECT Id,Lat,Lon,Time from Gps WHERE Time >= '%s' ORDER BY id"%date)
# print(data)

# Create the root KML object
root = kml.KML()
ns = '{http://www.opengis.net/kml/2.2}'

# Create a KML Document and add it to the KML root object
doc = kml.Document(ns, '1', 'test document', 'test gps data extraction')
root.append(doc)
# Create a KML Folder and nest it in the first Folder
f = kml.Folder(ns, 'nested-fid', 'nested f name', 'nested f description')
doc.append(f)

lon1 = data[0][2]
lat1 = data[0][1]
p           = kml.Placemark(ns, "0","%s"%data[0][3], 'description')
p.geometry  = Point(lon1,lat1)
f.append(p)

for d in data:
    lon2 = d[2]
    lat2 = d[1]
    print(dist((lon1,lat1),(lon2,lat2)).kilometers)
    if dist((lon1,lat1),(lon2,lat2)).kilometers>10: 
        p           = kml.Placemark(ns, "%s"%d[0],"%s"%d[3], 'description')
        p.geometry  = Point(lon2,lat2)
Exemple #29
0
# Get all of the cities and towns in the database. As some datasets
# (like fire_hydrants) are large, and at some zoom levels obscure
# details, these are put into a sub-folder in the KML file.
places = post.getPlaces(8)
# Get the bigger counties in the database.
counties = post.getPlaces(6)

parks = post.getProtected()

#
# Hiking Trails
#
if dd.get('trails') is True:
    logging.info("Downloading trails for %s" % title)
    trailfolder = kml.Folder(ns, 0, 'Hiking Trails')
    # cache the trails we find in the area, so when we use
    # the county polygon, we don't create a duplicate LineString.
    cache = dict()
    areas = list()
    areas = parks
    areas += counties
    if len(areas) > 0:
        kmldoc.append(trailfolder)
        for place in areas:
            if place['name'] is None:
                continue
            tmp = place['wkb_geometry'][0]
            trails = post.getTrails(tmp)
            logging.debug("FIXME trails: %d: %s" %
                          (len(trails), place['name']))
Exemple #30
0
def write_kml_tiles(out_filepath,
                    tiles,
                    land_mask_filepath,
                    doc_name="doc name",
                    doc_desc="doc description"):
    k = kml.KML()
    ns = '{http://www.opengis.net/kml/2.2}'
    d = kml.Document(ns, 'docid', doc_name, doc_desc)
    k.append(d)
    p_style = styles.PolyStyle(ns, 'id', fill=0)
    l_style = styles.LineStyle(ns, 'id', color="FF0000FF")
    sty = kml.Style(ns, 'id', styles=[p_style, l_style])

    # read SHP land mask
    driver = ogr.GetDriverByName("ESRI Shapefile")
    ds_mask = driver.Open(land_mask_filepath, update=False)
    layer_mask = ds_mask.GetLayer()

    for tile_counter in range(0, tiles.shape[2]):
        points = tiles[:, :, tile_counter]
        points = np.concatenate((points, np.array([points[0, :]])), axis=0)
        polygon_points = []
        for point in points:
            polygon_points.append((float(point[0]), float(point[1])))
        f = kml.Folder(ns, 'fid', 'f name', 'f description')
        d.append(f)
        # define geometry
        geom = geometry.Geometry()
        geom.geometry = Polygon(polygon_points)

        # create and add metadata
        polygon = ogr.CreateGeometryFromWkt(geom.geometry.wkt)
        coversland = False
        for feat_mask in layer_mask:
            if polygon.Intersects(feat_mask.geometry()):
                coversland = True
                break
        layer_mask.ResetReading()
        ll_lon = int(np.min(points[:, 0]))
        ll_lat = int(np.min(points[:, 1]))
        extent = int(np.max(points[:, 0]) - np.min(points[:, 0]))
        tilename = "{:03d}_{:03d}".format(
            int(np.min(points[:, 0])) + 180,
            int(np.min(points[:, 1])) + 90)
        schema_data = kml.SchemaData(
            ns,
            schema_url="#" +
            os.path.splitext(os.path.basename(out_filepath))[0])
        schema_data.append_data(name="GRID", value="LatLon Grid")
        schema_data.append_data(name="VERSION", value="V1")
        schema_data.append_data(name="ZONE", value="Globe")
        schema_data.append_data(name="SHORTNAME", value="LLG GL")
        schema_data.append_data(name="TILE", value=tilename)
        schema_data.append_data(name="EXTENT", value=str(extent))
        schema_data.append_data(name="LLLON", value=str(ll_lon))
        schema_data.append_data(name="LLLAT", value=str(ll_lat))
        schema_data.append_data(name="COVERSLAND", value=str(int(coversland)))
        # create placemark
        p = kml.Placemark(ns,
                          'id',
                          extended_data=kml.ExtendedData(
                              ns, elements=[schema_data]))
        p.geometry = geom
        p.append_style(sty)
        f.append(p)

    with open(out_filepath, 'w') as filehandle:
        filehandle.write(k.to_string(prettyprint=True))