Пример #1
0
def extractLocations(locations_kml, trees_locations):
    """Function to convert the trees locations expressed trough palcemarks on google Earth
       to UTM and to store the converted locations on a csv file
    """
    # extracting the .doc file from which generate the structure
    doc = file(locations_kml).read()
    k = kml.KML()
    k.from_string(doc)

    # Create the KML object to store the parsed result
    k = kml.KML()

    # Read in the KML string
    k.from_string(doc)

    # getting al the palcemarks in the kml
    features = list(list(k.features())[0].features())

    # iterate over placemarks and save longitude and latitude on a csv file
    with open(trees_locations, 'w') as points_locations:
        fieldnames = ['id', 'easting', 'northing']
        writer = csv.DictWriter(points_locations, fieldnames=fieldnames)
        writer.writeheader()
        for placemark in features:
            latitude = placemark.geometry.y
            longitude = placemark.geometry.x
            utm_coordinates = utm.from_latlon(latitude, longitude)
            name = placemark.name
            writer.writerow({
                'id': str(name),
                'easting': str(utm_coordinates[0]),
                'northing': str(utm_coordinates[1])
            })
Пример #2
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)
Пример #3
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
Пример #4
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))
Пример #5
0
    def get_kml_file(self):
        """
        read the form and fetch the kml or kmz file
        :return: return a kml.KML() object
        """
        # TODO parse the kml file more smartly to locate the first placemark and work from there.
        import_file = self.get_import_file()
        #kml_file_upload_name = kml_file_upload.name  # get the file name
        # kml_file_name = kml_file_upload_name[:kml_file_upload_name.rfind('.')]  # get the file name no extension
        kml_file_extension = self.get_import_file_extension(
        )  # get the file extension

        kml_file_path = os.path.join(settings.MEDIA_ROOT)

        kml_file = kml.KML()
        if kml_file_extension == "kmz":
            kmz_file = self.get_kmz_file()
            kml_document = kmz_file.open('doc.kml', 'r').read()
        else:
            # read() loads entire file as one string
            kml_document = open(kml_file_path + "/" + import_file.name,
                                'r').read()

        kml_file.from_string(
            kml_document
        )  # pass contents of kml string to kml document instance for parsing
        return kml_file
Пример #6
0
    def get(self, request, mapshareID, filters=None, format=None):
        urlSuffix = mapshareID
        if filters:
            urlSuffix += f'?{filters}'
        response = requests.get('https://share.garmin.com/Feed/Share/' +
                                urlSuffix)

        try:
            # Read KML from response
            k = kml.KML()
            k.from_string(response.content)

            features = list(k.features())
            placemarks = self.parse_features(features)
            content = {
                'is_valid': True,
                'MapshareID': mapshareID,
                'API_status': response.status_code,
                'placemarks': placemarks if placemarks else None,
            }
            return Response(content)

        except:
            errors = {
                'is_valid': False,
                'Error': 'Unable to read KML data.',
                'API_status': response.status_code,
                'Reponse status': response.reason,
                'Content': response.content,
            }
            return Response(errors)
def load_shape_info(shapefile):
    # This script converts .kml, .shp and .txt files to the right format. If multiple shapes are available the script
    # will select the first one.

    if shapefile.endswith('.shp'):
        with collection(shapefile, "r") as inputshape:
            for shape in inputshape:
                # only first shape
                dat = shape['geometry']['coordinates']

                st = '('
                for p in dat[0]:
                    st = st + str(p[0]) + ' ' + str(p[1]) + ','
                st = st[:-1] + ')'

                break
    elif shapefile.endswith('.kml'):
        doc = file(shapefile).read()
        k = kml.KML()
        k.from_string(doc)
        shape = list(list(
            k.features())[0].features())[0].geometry.exterior.coords[:]
        st = '('
        for p in shape:
            st = st + str(p[0]) + ' ' + str(p[1]) + ','
        st = st[:-1] + ')'
    else:
        print 'format not recognized! Pleas creat either a .kml or .shp file.'
        return []

    return st
Пример #8
0
def import_kml_polygon(filename):
    '''import a single .kml polygon created in Google Earth. Should work in simple cases.......'''
    
    kml_file = filename # Name of the kml file
    
    # Load the file as a string, skipping the first line because for some reason fastkml cannot deal with that...
    with open(kml_file, 'rt', encoding="utf-8") as myfile:
        doc=myfile.readlines()[1:]
        myfile.close()
    doc = ''.join(doc) # gets it as a string
    
    # Using the very opaque fastkml module to parse out the features. I wonder if the length of features is 2 if it's a 2-segment line..?
    k = kml.KML()
    k.from_string(doc)
    features = list(k.features())
    
    # Extract the first feature and a LineString object corresponding to it!
    f1 = list(features[0].features())
    t = f1[0].geometry

    A = np.array(t.exterior.coords)
    Polylon = A[:,0]
    Polylat = A[:,1]
    
    return Polylon, Polylat
Пример #9
0
def nexrad_loc(radsite):
    # read nexrad data
    with open('Weather_Radar_Stations.kml', 'rt', encoding="utf-8") as myfile:
        doc = myfile.read()

    # parse kml file
    k = kml.KML()
    k.from_string(bytes(doc, encoding='utf8'))
    features = list(k.features())
    f2 = list(features[0].features())
    f3 = list(f2[0].features())
    site_name = []
    site_lon = []
    site_lat = []

    for fsub in f3:
        site_name.append(fsub.extended_data.elements[0].data[1]['value'])
        lon, lat = fsub.geometry.xy
        site_lon.append(lon[0])
        site_lat.append(lat[0])

    # get data at radar site
    radind = site_name.index(radsite)
    radlon = site_lon[radind]
    radlat = site_lat[radind]
    return radlon, radlat
Пример #10
0
def readKMLFile(path):
    k = None
    with open(path, 'rb') as kmlFile:
        doc = kmlFile.read()
        k = kml.KML()
        k.from_string(doc)
    return k
Пример #11
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
Пример #12
0
def download_kml(map_id, file_name):
	lanes_map_file = f'/tmp/{file_name}.kml'
	if not os.path.exists(lanes_map_file):
		print(f'downloading map http://www.google.com/maps/d/kml?mid={map_id}&forcekml=1')
		os.system(f'wget "http://www.google.com/maps/d/kml?mid={map_id}&forcekml=1" -O "{lanes_map_file}"')

	k = kml.KML()
	# open & encoding - для декодирования файлов при открытии, потому что в системе по умолчанию может стоять кодировка ascii
	with open(lanes_map_file, encoding='utf-8') as f:
		# а плагин сам ещё раскодирует utf-8, поэтому закодировать обратно
		k.from_string(f.read().encode('utf-8'))

	data = []
	for f in list(k.features())[0].features():
		lanes = None
		if f.name == 'односторонние сущ.' or f.name == 'Существующие. Односторонние':
			lanes = 1
		elif f.name == 'двусторонние сущ.' or f.name == 'Существующие':
			lanes = 2
		if lanes:
			for f2 in f.features():
				data.append({'lanes': lanes, 'geometry': f2.geometry})

	gdf = gpd.GeoDataFrame(data, crs=WGS)
	gdf['length'] = gdf['geometry'].to_crs(SIB).length  # в проекции альберса сибирь метры -- это реальные метры, в пределах бСССР, вне этого прямоугольника координат начинаются сильные нелинейные искажения.
	return gdf
Пример #13
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())
Пример #14
0
def convert(infilename, outfilename=None):
    def convert_polygons(feature):
        if getattr(feature, 'geometry', None):
            if isinstance(feature.geometry, Polygon):
                feature.geometry = orient(feature.geometry, 1.0)
            elif isinstance(feature.geometry,  MultiPolygon):
                polys = []
                for p in feature.geometry.geoms:
                    polys.append(orient(p, 1.0))
                mp = MultiPolygon(polys)
                feature.geometry = mp
        if getattr(feature, 'features', None):
            for f in feature.features():
                convert_polygons(f)
    # main #
    (fname, ext) = os.path.splitext(infilename)
    srcfile = open(infilename, 'r')
    src = kml.KML()
    src.from_string(srcfile.read())
    for feature in src.features():
        convert_polygons(feature)
    xml = '<?xml version="1.0" encoding="UTF-8"?>' + src.to_string()
    if outfilename == None:
        outfilename = fname + '-new.kml'
    out = open(outfilename, 'w')
    out.write(xml)
    out.close()
def lecture_picardie(repertoire_picardie, departements_picardie):
    """
    :param repertoire_picardie:
    :param departements_picardie:
    :return: orgues_picardie: liste [[departement, commune, edifice, x_gps, y_gps],...]
    """
    orgues_picardie = list()
    # Parcours des fichiers KML.
    for departement_picardie in departements_picardie:
        with open(repertoire_picardie + departement_picardie + '.kml',encoding='utf-8') as f_kml:
            doc = f_kml.read()
            k = kml.KML()
            k.from_string(doc)
            features = list(k.features())
            for f in features[0].features():
                for placemark in f.features():
                    name = placemark.name.rstrip('\n')
                    # Si l'édifice est présent :
                    if ' - ' in name:
                        commune, edifice = name.split(' - ')
                    # Si l'édifice est absent :
                    else:
                        commune, edifice = name, None
                    orgues_picardie.append([departement_picardie,
                                            commune,
                                            edifice,
                                            str(placemark.geometry.x),
                                            str(placemark.geometry.y)])
    return orgues_picardie
Пример #16
0
def import_kml_line(filename):
    '''import a single .kml line created in Google Earth. Note that this will probably import only the first segment of 'multi segment' lines. Which is fine......'''
    
    kml_file = filename # Name of the kml file
    
    # Load the file as a string, skipping the first line because for some reason fastkml cannot deal with that...
    with open(kml_file, 'rt', encoding="utf-8") as myfile:
        doc=myfile.readlines()[1:]
        myfile.close()
    doc = ''.join(doc) # gets it as a string
    
    # Using the very opaque fastkml module to parse out the features. I wonder if the length of features is 2 if it's a 2-segment line..?
    k = kml.KML()
    k.from_string(doc)
    features = list(k.features())
    
    # Extract the first feature and a LineString object corresponding to it!
    f1 = list(features[0].features())
    t = f1[0].geometry
    
    # Get the coordinates of the line's nodes.
    xy = t.xy
    x0 = xy[0][0]
    x1 = xy[0][1]
    y0 = xy[1][0]
    y1 = xy[1][1]
    
    return x0,x1,y0,y1
Пример #17
0
 def _createPostcodeDictionaryFromKML(self):
     """ Reads in kml file converts data to dictionary on postcode.
     Then we can look up quickly later.
     
     KML maps found at.
     https://www.doogal.co.uk/KmlDataFeeds.php
     """ 
     # read it using fastkml
     if not os.path.exists(self.postcode_file):
         raise ValueError("Expected KML file %s does not exist" % self.postcode_file)
     with open(self.postcode_file, 'rt', encoding="utf-8") as myfile:
         doc=myfile.read()
     kmlInst = kml.KML()
     kmlInst.from_string(doc)
 
     
     # Get top layer features
     featuresLayer1 = list(kmlInst.features())
     # Get next layer - individual postcodes layer
     featuresLayer2 = list(featuresLayer1[0].features())
     # Should be 18948 unique Edinburgh postcodes
     
     
     if len(featuresLayer2)!=18948:
         raise ValueError("Expected 18948 postcode entries, but number found is %s" % 
                          len(featuresLayer2))
     
     # process into dictionary: dict(postcode,Tuple(longitude,latitude)
     # Only include active ones in dictionary
     self.postcodeLocationDict=dict([(feature.name.strip(),feature.geometry) 
         for feature in featuresLayer2 if feature.styleUrl=='#active']) 
     
     if len(self.postcodeLocationDict)!=13214:
         raise ValueError("Expected 13214 active postcode entries, but number found is %s" % 
                          len(self.postcodeLocationDict))
Пример #18
0
    def _get_document(self):
        doc = open("pracas.kml", "r").read().encode('utf-8')

        self._document = kml.KML()

        self._document.from_string(doc)
        return self._document
Пример #19
0
 def records(self):
     with open(self.shapefile, 'r') as kml_file:
         kml_data = self.sanatize(kml_file.read())
         obj = kml.KML()
         obj.from_string(kml_data)
         for result in self.data_generator(obj):
             yield result
Пример #20
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()	
Пример #21
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
Пример #22
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()
Пример #23
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)
Пример #24
0
def kmlToGeoJsonDict(kmlfile=None, data=None, encoding=None):
    """ Convert a KML file to a GeoJSON dict """
    import xml.dom.minidom as md
    from fastkml import kml
    import kml2geojson

    k = kml.KML()

    with open(kmlfile) as thefile:
        kmlf = thefile.read()

    # Handle encoding
    if not encoding:
        try:
            import re
            match = re.search('encoding=".+"', kmlf).group()
            encoding = match.split('=')[1][1:-1]
        except:
            encoding = 'utf-8'

    kmlf = kmlf.encode(encoding)
    k.from_string(kmlf)
    kmlStr = k.to_string()

    # force encoding
    kmlStr = kmlStr.encode(encoding, errors="ignore").decode()
    root = md.parseString(kmlStr)
    layers = kml2geojson.build_feature_collection(root)
    return layers
Пример #25
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))
Пример #26
0
    def __init__(self, selected_type):
        config_file = 'geonames_config.toml'
        with open(config_file) as config_file:
            self.config = toml.loads(config_file.read())

        filename = os.path.dirname(os.path.abspath(__file__)) +\
                   '/../' + self.config[selected_type]['filename']
        # filename =  os.path.dirname(os.path.abspath(__file__)) +\
        #            '/../prior_examples/geo_names.kml'

        k = kml.KML()
        with open(filename, 'r') as f:
            k.from_string(bytes(bytearray(f.read(), encoding='utf-8')))

        docu = list(k.features())[0]
        polygons = {}
        for p in list(docu.features()):
            print(p.name)
            print(p.geometry)
            polygons[p.name] = p.geometry

        self.polygons = polygons
        # self.geo_names = {0: 'cont_europe', 1: 'sahara', 2: 'arabian_peninsula',
        #                   3: 'far_east_deserts', 4: 'persia', 5: 'india'}
        self.geo_names = {
            int(k): v
            for k, v in self.config[selected_type]['geo_names'].items()
        }
        assert set(polygons.keys()) == set(self.geo_names.values()), \
            ('not all keys in polygon are matched', polygons.keys(), self.geo_names.values())
        print('loaded the named_geography')
        print('available geo names ', self.geo_names)
Пример #27
0
 def parse_kml(self): 
     with open(self.configs["kml_location"], 'r') as f:
         k = kml.KML()
         k.from_string(f.read())
         self.kml_features = self.unroll_features(k)
         log.INFO("Successfully loaded kml from "+self.configs["kml_location"],self.identity )
         self.send(self.parent,"TASK_COMPLETE")
Пример #28
0
    def load_file(self):
        """
        Loads multiple KML Files simultaneously and constructs the
        corresponding patches.
        """
        for entry in self.dict_files.values(
        ):  # removes all patches from map, but not from dict_files
            if entry[
                    "patch"] is not None:  # since newly initialized files will have patch:None
                entry["patch"].remove()

        for index in range(self.listWidget.count()):
            if hasattr(self.listWidget.item(index), "checkState") and (
                    self.listWidget.item(index).checkState()
                    == QtCore.Qt.Checked):
                _dirname, _name = os.path.split(
                    self.listWidget.item(index).text())
                _fs = fs.open_fs(_dirname)
                try:
                    with _fs.open(_name, 'r') as kmlf:
                        self.kml = kml.KML()  # creates fastkml object
                        self.kml.from_string(kmlf.read().encode('utf-8'))
                        if self.listWidget.item(index).text(
                        ) in self.dict_files:  # just a precautionary check
                            if self.dict_files[self.listWidget.item(
                                    index).text(
                                    )]["patch"] is not None:  # added before
                                patch = KMLPatch(
                                    self.view.map, self.kml,
                                    self.set_color(
                                        self.listWidget.item(index).text()),
                                    self.set_linewidth(
                                        self.listWidget.item(index).text()))
                            else:  # if new file is being added
                                patch = KMLPatch(
                                    self.view.map, self.kml,
                                    self.dict_files[self.listWidget.item(
                                        index).text()]["color"],
                                    self.dict_files[self.listWidget.item(
                                        index).text()]["linewidth"])
                            self.dict_files[self.listWidget.item(
                                index).text()]["patch"] = patch

                except (IOError, TypeError, et.XMLSyntaxError,
                        et.XMLSchemaError, et.XMLSchemaParseError,
                        et.XMLSchemaValidateError
                        ) as ex:  # catches KML Syntax Errors
                    logging.error("KML Overlay - %s: %s", type(ex), ex)
                    self.labelStatusBar.setText(
                        str(self.listWidget.item(index).text()) +
                        " is either an invalid KML File or has an error.")
                    del self.dict_files[self.listWidget.item(
                        index).text()]  # del the checked files from dictionary
                    self.listWidget.takeItem(
                        index)  # remove file item from ListWidget
                    QtWidgets.QMessageBox.critical(
                        self, self.tr("KML Overlay"),
                        self.tr(f"ERROR:\n{type(ex)}\n{ex}"))
        logging.debug(self.dict_files)
    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)
Пример #30
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