Esempio n. 1
0
def buildPlacemarkForSite(folder, siteData):
    ''' Build a placemark for a particular site.
        If the site is in PLUME_SOURCES, then show a wedge or circle depending on the wind speed.
        Otherwise show just a point.
        Render a popup or not based on json data.
    '''
    siteName = siteData['name']
    if siteName in SITE_POSITIONS:
        dotPlacemark = kml.Placemark(NAME_SPACE, siteName, siteName,
                                     getSiteDescription(siteData))
        dotPlacemark.styleUrl = '#' + getDotIconId(
            getDataValue('SO2.AQItext', siteData))
        dotPlacemark.geometry = buildPoint(SITE_POSITIONS[siteName], siteName)
        folder.append(dotPlacemark)

        if siteName == PLUME_SOURCE:
            plumeData = getPlumeSourceData()
            for crater in WEDGE_POSITIONS:
                craterPlacemark = kml.Placemark(
                    NAME_SPACE, makeKey(crater), crater,
                    getCraterDescription(plumeData))
                craterPlacemark.styleUrl = '#' + getPolyStyleId(
                    getDataValue('SO2.AQItext', plumeData))
                if CONDITIONS['LOW_WIND']:
                    craterPlacemark.geometry = buildCircle(
                        WEDGE_POSITIONS[crater], crater)
                else:
                    craterPlacemark.geometry = buildWedge(
                        WEDGE_POSITIONS[crater], CONDITIONS['WIND_DIRECTION'],
                        crater)
                folder.append(craterPlacemark)
    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)
Esempio n. 3
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)
Esempio n. 4
0
def slicePlacemarks(placemarks, state):
    """Slice the source placemark geometry and ingest it."""
    outputPlacemarks = []
    outputPolygons = []
    totalPolygons = 0
    ns = '{http://www.opengis.net/kml/2.2}'
    for placemark in placemarks:
        s = shape(placemark.geometry)

        if isinstance(s, shapely.geometry.polygon.Polygon):
            boundery = insertBoundery(s, state, True)
            outputPolygons.append(boundery)

        elif isinstance(s, shapely.geometry.multipolygon.MultiPolygon):
            subSs = list(s)
            for subS in subSs:
                boundery = insertBoundery(subS, state, True)
                outputPolygons.append(boundery)

        slices = fishnet(placemark.geometry, 0.01)
        totalPolygons += len(slices)

        for polygonSlice in slices:
            matchingId = str(uuid.uuid4())
            newPlacemark = kml.Placemark(ns, 'id', matchingId, 'description')
            newPlacemark.geometry = polygonSlice
            newPlacemark.styleUrl = "KMLStyler"
            if isinstance(newPlacemark.geometry,
                          shapely.geometry.polygon.Polygon):
                outputPlacemarks.append(newPlacemark)
                boundery = insertBoundery(newPlacemark.geometry, state, False)
                boundery.matchingId = matchingId
                outputPolygons.append(boundery)

            elif isinstance(newPlacemark.geometry,
                            shapely.geometry.multipolygon.MultiPolygon):
                subPolygons = list(newPlacemark.geometry)
                for subPolygon in subPolygons:
                    matchingId = str(uuid.uuid4())
                    newSubPlacemark = kml.Placemark(ns, 'id', matchingId,
                                                    'description')
                    newSubPlacemark.geometry = subPolygon
                    newSubPlacemark.styleUrl = "KMLStyler"
                    outputPlacemarks.append(newSubPlacemark)
                    boundery = insertBoundery(subPolygon, state, False)
                    boundery.matchingId = matchingId
                    outputPolygons.append(boundery)

    return outputPlacemarks, totalPolygons, outputPolygons
Esempio n. 5
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
Esempio n. 6
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())
Esempio n. 7
0
    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
Esempio n. 8
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()	
Esempio n. 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()
Esempio n. 10
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))
Esempio n. 11
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))
Esempio n. 12
0
def _flight_export_kml(
    flight: Flight,
    styleUrl: Optional[kml.StyleUrl] = None,
    color: Optional[str] = None,
    alpha: float = 0.5,
    **kwargs,
) -> kml.Placemark:
    if color is not None:
        # the style will be set only if the kml.export context is open
        styleUrl = toStyle(color)
    params = {
        "name": flight.callsign,
        "description": flight._info_html(),
        "styleUrl": styleUrl,
    }
    for key, value in kwargs.items():
        params[key] = value
    placemark = kml.Placemark(**params)
    placemark.visibility = 1
    # Convert to meters
    coords = np.stack(flight.coords)  # type: ignore
    coords[:, 2] *= 0.3048
    placemark.geometry = Geometry(
        geometry=LineString(coords),
        extrude=True,
        altitude_mode="relativeToGround",
    )
    return placemark
Esempio n. 13
0
def gen_placemark_from_Line(coords, ns, names):
    """
    create a placemark object for kml
    :param coords: list of the base line and optionaly the offsets lines
    :type coords: list of coordinates
    :param ns: ns of kml version
    :type ns: str
    :param name: list of line names
    :type name: list of str
    :return: list of placemark object
    :rtype: list of placemark
    """
    outplacemarks = []
    name_l = [name for name in names if 'offset_l' in name]
    name_r = [name for name in names if 'offset_r' in name]
    name_b = [
        name for name in names
        if 'offset_r' not in name and 'offset_l' not in name
    ]
    coords_l = [
        coords[names.index(name)] for name in names if 'offset_l' in name
    ]
    coords_r = [
        coords[names.index(name)] for name in names if 'offset_r' in name
    ]
    dim = len(coords_r)
    coords_b = [
        coords[names.index(name)] for name in names
        if 'offset_r' not in name and 'offset_l' not in name
    ]
    colors = color_range_gen(dim + 1)
    for i in range(dim):
        ls = styles.LineStyle(ns=ns, id=None, color=colors[i + 1], width=1.5)
        s1 = styles.Style(styles=[ls])
        outplacemark_l = kml.Placemark(ns, None, name_l[i], None, styles=[s1])
        outplacemark_r = kml.Placemark(ns, None, name_r[i], None, styles=[s1])
        outplacemark_l.geometry = LineString(coords_l[i])
        outplacemark_r.geometry = LineString(coords_r[i])
        outplacemarks.append(outplacemark_l)
        outplacemarks.append(outplacemark_r)
    ls = styles.LineStyle(ns=ns, id=None, color=colors[0], width=3)
    s1 = styles.Style(styles=[ls])
    outplacemark = kml.Placemark(ns, None, name_b[0], None, styles=[s1])
    outplacemark.geometry = LineString(coords_b[0])
    outplacemarks.append(outplacemark)

    return outplacemarks
Esempio n. 14
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
Esempio n. 15
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()
    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
Esempio n. 17
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))
Esempio n. 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())
Esempio n. 19
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)
Esempio n. 20
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
Esempio n. 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)
Esempio n. 22
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
Esempio n. 23
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())
Esempio n. 24
0
    def main(self):
        with open(sys.argv[1], 'r') if len(sys.argv) > 1 else sys.stdin as f:
            # read the whole contents and put it in memory
            lines = f.readlines()
            f.close()

        for line in lines:
            if self.current_line > 2:
                # TODO: establish YUV axis if undef.
                components = line.strip().split()
                if self.gradient_values is None:
                    self.gradient_values = self.setup_gradient_and_t(
                        int(components[1]))
                    # styles.append(kml.Style(self.name_space, styleid, this_style)

                if int(components[1]) > self.threshold:

                    style = self.gradient_values[int(components[1]) - 1]

                    # southwest corner
                    sw_lat_lon = self.mgrs.toLatLon(str.encode(components[0]))
                    ne_lat_lon = self.offset_corner(sw_lat_lon)

                    pm_ident = 'mgrs-'
                    pm_ident += str(self.current_line)
                    style_identifier = "#style-"
                    style_identifier += components[1]
                    # print (f'{components[0]}: lat: {lat_lon[0]:.5f} lon: {lat_lon[1]:.5f} value: {components[1]} {northing} {easting}')
                    p = kml.Placemark(self.name_space, pm_ident, components[0],
                                      ''.join(components), None,
                                      style_identifier)
                    p.geometry = Geometry(
                        self.name_space, '',
                        Polygon([(sw_lat_lon[1], sw_lat_lon[0], 170),
                                 (ne_lat_lon[1], sw_lat_lon[0], 170),
                                 (ne_lat_lon[1], ne_lat_lon[0], 170),
                                 (sw_lat_lon[1], ne_lat_lon[0], 170)]), True,
                        True, 'relativeToGround')
                    self.cell_document.append(p)
                # process line
            self.current_line += 1

        self.output_kml.append(self.cell_document)
        print(self.output_kml.to_string(prettyprint=True))
Esempio n. 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))
    def write(self, record_set):
        coord_folder = self.get_coord_folder(record_set.get('coordinate_set'))
        coord_mark = fkml.Placemark(
            ns=self.NS,
            name=record_set.get('observation_date')[0].strftime(
                self.TS_OUTPUT_FMT))
        coord_mark.begin, coord_mark.end = record_set.get('observation_date')
        coord_mark.visibility = 0

        coord_mark.geometry = Geometry(
            ns=self.NS,
            geometry=Polygon(
                *convert_grid_coords(record_set.get('polygon_point_bounds'))))

        coord_data = [{
            'name': 'uuid',
            'value': record_set.get('uuid')
        }, {
            'name': 'wrs2_path_row',
            'value': record_set.get('wrs2_path_row')
        }, {
            'name': 'netcdf_slice',
            'value': record_set.get('netcdf_slice')
        }]

        for band in self.bands:
            coord_data.append({
                'name': 'band_{}'.format(band),
                'value': record_set.get('band_{}'.format(band))
            })

        coord_mark.extended_data = fkml.SchemaData(
            ns=self.NS,
            schema_url=self.schema_set['placemark_metadata'],
            data=coord_data)
        coord_folder.append(coord_mark)
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
Esempio n. 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()
Esempio n. 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)