当前位置: 首页>>代码示例>>Python>>正文


Python KML_ElementMaker.open方法代码示例

本文整理汇总了Python中pykml.factory.KML_ElementMaker.open方法的典型用法代码示例。如果您正苦于以下问题:Python KML_ElementMaker.open方法的具体用法?Python KML_ElementMaker.open怎么用?Python KML_ElementMaker.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pykml.factory.KML_ElementMaker的用法示例。


在下文中一共展示了KML_ElementMaker.open方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _docSkel

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def _docSkel(name):
    name = re.sub('[^a-zA-Z0-9\n\.]', ' ', name.split('.')[0]).title()
    doc = KML.kml(
        KML.Document(
            KML.name(name),
            KML.open('1'),
            KML.visibility('1'),
            # uncomment the following if you want to hide the children
            #            KML.Style(
            #                KML.ListStyle(
            #                    KML.listItemType('checkHideChildren')
            #                ),
            #                id='check-hide-children',
            #                ),
            #            KML.styleUrl('#check-hide-children'),
        )
    )
    return doc
开发者ID:johnnycakes79,项目名称:pyops,代码行数:20,代码来源:maps.py

示例2: placeMaker

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def placeMaker(attr):
    '''Uses pyKML to produce a placemark for an image
    
The use of pyKML isn't actually necessary,
you could do just as well appending the placemarks from the NASA
KML files into a single document, but the intention was to
give an example usage of pyKML.'''
    try:
        placemark = K.Placemark(
                        K.open(0),
                        K.name(attr['MRF']),
                        K.styleUrl("#sm_style"),
                        K.Point(
                            K.altitudeMode('relativeToGround'),
                            K.coordinates(",".join([attr["Longitude"],attr["Latitude"],attr["Elevation"]]))
                        ),
                        K.LookAt(
                            K.tilt(attr["Tilt"]),
                            K.longitude(attr["Longitude"]),
                            K.latitude(attr["Latitude"]),
                            K.range(40000)
                        ),
                        K.TimeStamp(K.when(time.strftime("%Y-%m-%dT%H:%M:%SZ",time.strptime(attr["YYYYMMDD"]+attr["HHMMSS"],"%Y%m%d %H%M%S")))),
                        K.ExtendedData(
                            K.Data( K.value(attr["MRF"]), name="MRF"),
                            K.Data( K.value(attr["IMG"]), name="IMG"),
                            K.Data( K.value(attr["Features"]), name="features"),
                            K.Data( K.value(attr["YYYYMMDD"]), name="YYYYMMDD"),
                            K.Data( K.value(attr["HHMMSS"]), name="HHMMSS"),
                            K.Data( K.value(attr["Camera Tilt"]), name="Camera_Tilt"),
                            K.Data( K.value(attr["Camera Lens"]), name="Camera_Lens"),
                            K.Data( K.value(attr["Camera"]), name="Camera"),
                            K.Data( K.value(attr["Sun Azimuth"]), name="Sun_Azimuth"),
                            K.Data( K.value(attr["Sun Elevation"]), name="Sun_Elevation"),
                            K.Data( K.value(attr["Spacecraft Altitude"]), name="Spacecraft_Altitude"),
                            K.Data( K.value(attr["DB Entry"]), name="DB_Entry"),
                        )

                        
                    )
    except :
        return None
    return placemark
开发者ID:rsawtell,项目名称:AstroKML,代码行数:45,代码来源:AstroKML.py

示例3: generate_cbar_element

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def generate_cbar_element(inps):

    out_name_base = plot.auto_figure_title(inps.ts_file, inps_dict=vars(inps))
    cbar_png_file = '{}_cbar.png'.format(out_name_base)

    cbar_png_file = plot_colorbar(out_file=cbar_png_file, vmin=inps.vlim[0], vmax=inps.vlim[1], cmap=inps.colormap)
    cbar_overlay = KML.ScreenOverlay(
        KML.name('Colorbar'),
        KML.Icon(
            KML.href("{}".format(cbar_png_file)),
            KML.viewBoundScale(0.75)
        ),
        KML.overlayXY(x="0", y="0", xunits="fraction", yunits="fraction"),
        KML.screenXY(x="0", y="0", xunits="fraction", yunits="fraction"),
        KML.size(x="0", y="250", xunits="pixel", yunits="pixel"),
        KML.rotation(0),
        KML.visibility(1),
        KML.open(0)
    )
    print('add colorbar.')
    return cbar_overlay, cbar_png_file
开发者ID:hfattahi,项目名称:PySAR,代码行数:23,代码来源:save_kmz_timeseries.py

示例4: get_kml_for_queryset

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def get_kml_for_queryset(queryset, filename=_('Geographical objects')):
    """
    :param queryset: GeoObject queryset
    :return: KML file from GeoObject queryset
    """
    kml = KML.kml(KML.Document(KML.open(1)))

    geo_objects = queryset.values_list('color', 'title', 'lat', 'lon', 'geometry', 'short_description')
    colors = set(items[0] for items in sorted(geo_objects))
    colors_dict = {color: convert_color_hex_to_kml(color) for color in colors}

    for line_color, polygon_color in colors_dict.values():
        kml.Document.append(KML.Style(
            KML.PolyStyle(KML.color(polygon_color)),
            KML.LineStyle(KML.color(line_color), KML.width(2)),
            id=line_color,
        ))
        print(line_color, polygon_color)

    for (color, title, lat, lon, polygon, short_description) in geo_objects:
            style_id = colors_dict[color][0]
            fld = KML.Folder(
                KML.name(title),
                KML.Placemark(
                    KML.name(title),
                    KML.styleUrl('#' + style_id),
                    KML.description(short_description),
                    KML.Point(KML.coordinates("{},{},0".format(lon, lat)))
                )
            )

            if polygon:
                polygon = parser.fromstring(polygon.kml)
                fld.append(KML.Placemark(KML.name(title), KML.styleUrl('#' + style_id),
                                         KML.description(short_description), polygon))

            kml.Document.append(fld)

    kml_str = '<?xml version="1.0" encoding="UTF-8"?>\n' + etree.tostring(kml, pretty_print=True).decode()
    return get_file_response(kml_str, filename)
开发者ID:,项目名称:,代码行数:42,代码来源:

示例5: _convert_

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
    def _convert_(self,request):
        from pykml.factory import KML_ElementMaker as KML
        from lxml import etree
        
        ## create the database
        if self.use_stat:
            raise(NotImplementedError)
        else:
            db = self.sub.to_db(wkt=True,to_disk=True)
        
        meta = request.ocg
        if request.environ['SERVER_PORT']=='80':
            portstr = ''
        else:
            portstr = ':{port}'.format(port=request.environ['SERVER_PORT'])
        
        url='{protocol}://{server}{port}{path}'.format(
            protocol='http',
            port=portstr,
            server=request.environ['SERVER_NAME'],
            path=request.environ['PATH_INFO'],
        )
        description = (
            '<table border="1">'
              '<tbody>'
                '<tr><th>Archive</th><td>{archive}</td></tr>'
                '<tr><th>Emissions Scenario</th><td>{scenario}</td></tr>'
                '<tr><th>Climate Model</th><td>{model}</td></tr>'
                '<tr><th>Run</th><td>{run}</td></tr>'
                '<tr><th>Output Variable</th><td>{variable}</td></tr>'
                '<tr><th>Units</th><td>{units}</td></tr>'
                '<tr><th>Start Time</th><td>{start}</td></tr>'
                '<tr><th>End Time</th><td>{end}</td></tr>'
                '<tr>'
                  '<th>Request URL</th>'
                  '<td><a href="{url}">{url}</a></td>'
                '</tr>'
                '<tr>'
                  '<th>Other Available Formats</th>'
                  '<td>'
                    '<a href="{url}">KML</a> - Keyhole Markup Language<br/>'
                    '<a href="{url_kmz}">KMZ</a> - Keyhole Markup Language (zipped)<br/>'
                    '<a href="{url_shz}">Shapefile</a> - ESRI Shapefile<br/>'
                    '<a href="{url_csv}">CSV</a> - Comma Separated Values (text file)<br/>'
                    '<a href="{url_json}">JSON</a> - Javascript Object Notation'
                  '</td>'
                '</tr>'
              '</tbody>'
            '</table>'
        ).format(
            archive=meta.archive.name,
            scenario=meta.scenario,
            model=meta.climate_model,
            run=meta.run,
            variable=meta.variable,
            units=meta.variable.units,
            simout=meta.simulation_output.netcdf_variable,
            start=meta.temporal[0],
            end=meta.temporal[-1],
            operation=meta.operation,
            url=url,
            url_kmz=url.replace('.kml', '.kmz'),
            url_shz=url.replace('.kml', '.shz'),
            url_csv=url.replace('.kml', '.csv'),
            url_json=url.replace('.kml', '.geojson'),
        )
        ##### TODO: build linked urls on the fly
        #from piston.emitters import Emitter
        #Emitter.EMITTERS.keys()
        #['xml', 'sqlite', 'nc', 'shz', 'kml', 'kcsv', 'django', 'json', 'html', 'meta', 'lshz', 'csv', 'pickle', 'kmz']

        doc = KML.kml(
          KML.Document(
            KML.name('Climate Simulation Output'),
            KML.open(1),
            KML.description(description),
            KML.snippet(
                '<i>Click for metadata!</i>',
                maxLines="2",
            ),
            KML.StyleMap(
              KML.Pair(
                KML.key('normal'),
                KML.styleUrl('#style-normal'),
              ),
              KML.Pair(
                KML.key('highlight'),
                KML.styleUrl('#style-highlight'),
              ),
              id="smap",
            ),
            KML.Style(
              KML.LineStyle(
                KML.color('ff0000ff'),
                KML.width('2'),
              ),
              KML.PolyStyle(
                KML.color('400000ff'),
              ),
              id="style-normal",
#.........这里部分代码省略.........
开发者ID:LeadsPlus,项目名称:OpenClimateGIS,代码行数:103,代码来源:kml.py

示例6: gmaps

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def gmaps(input, configFile):
    """
       Check and deal with command line agruments.
    """

    if NOKMLLIB:
        print("\nOoops! 'gmaps' needs KML_ElementMaker from pykml.factory")
        print("       Try: pip install pykml\n")
    else:
        # # Check input arguments
        # if len(sys.argv) < 2 or len(sys.argv) > 3:
        #     # ... show usage hint...
        #     _gmapsusage(sys.argv[0])
        #     # ... exit!
        #     raise SystemExit(1)

        # input = sys.argv[1]
        # if sys.argv[2]:
        #     configFile = sys.argv[2]
        # else:
        #     configFile = False

        # create containers
        experiments = {}
        filters = {}
        currents = {}
        styles = []

        # Open input file for reading.
        infile = open(input, 'r')

        # Scan through the file line-by-line.
        # TODO: look into moving this for loop into a function
        for line in infile.readlines():
            if line.startswith('Trail'):
                break

            # TODO: Replace the crude pattern matching below with RegEx...
            if line.startswith('Experiment:'):
                expr = line.split(': ')[1].strip()
                if expr not in experiments:
                    experiments[expr] = KML.Folder(KML.name(expr.replace('_',
                                                                         ' ')),
                                                   KML.open('1'),
                                                   id='expr_{}'.format(expr))
                currents['experiment'] = expr

            if line.startswith('Swath:'):
                fltr = line.split(': ')[1].strip()
                if fltr not in filters:
                    filters[fltr] = KML.Folder(KML.name(fltr.replace('_', ' ')),
                                               KML.open('0'),
                                               KML.visibility('1'),
                                               KML.Style(KML.ListStyle(KML.listItemType('checkHideChildren')), id='check-hide-children'),
                                               KML.styleUrl('#check-hide-children'),
                                               id='fltr_{}'.format(fltr))
                    experiments[currents['experiment']].append(filters[fltr])
                currents['filter'] = fltr

            if line.startswith('Orbit:'):
                orbit = line.split()[1].strip()
                currents['orbit'] = orbit

            if line.startswith('Pericenter time (UTC):'):
                peric_time = line.split(': ')[1].strip()
                currents['pericenter time'] = peric_time

            if line.startswith('First image time (UTC):'):
                first_image_t = line.split(': ')[1].strip()
                currents['first image time'] = first_image_t

            if line.startswith('First image time (from pericenter):'):
                first_image_t_frm_peric = line.split(': ')[1].strip()
                currents['first image time from pericenter'] = first_image_t_frm_peric

            if line.startswith('Last image time (UTC):'):
                last_image_t = line.split(': ')[1].strip()
                currents['last image time'] = last_image_t

            if line.startswith('Last image time (from pericenter):'):
                last_image_t_frm_peric = line.split(': ')[1].strip()
                currents['last image time from pericenter'] = last_image_t_frm_peric

            # build an 'image' placemark element
            if line.startswith(' '):
                image = _buildSwath(line, currents)
                filters[currents['filter']].append(image)

        infile.close()

        # the styles for the different swaths
        colors = {}

        # if the MAPPS ini has been provided get colours from it.
        if configFile:
            inifile = open(configFile, 'r')
            for line in inifile.readlines():
                if '\swathColorName=' in line:
                    cHTML = line.rsplit("=#", 1)[1].strip()
                    cKML = '{}{}{}'.format(cHTML[4:6], cHTML[2:4], cHTML[0:2])
#.........这里部分代码省略.........
开发者ID:johnnycakes79,项目名称:pyops,代码行数:103,代码来源:maps.py

示例7: makeKmlDoc

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
    def makeKmlDoc(self):
        """
        """
        self.cdatatext = {}
        args = self.config['arguments']
        
        trackfolder = imagefolder = None
        self.colourIndex = 0
        
        if ('update' in self.config['arguments'] and 
            self.config['arguments']['update']):
            
            with open(args['out'], 'r') as f:
                doc = KML.parse(f)
            # Find a folder that contains a Name with the text "tracks"
            trackfolder = doc.find('./Folder/[Name="tracks"]/..')
            # Find a folder that contains a Name with the text "tracks"
            imagefolder = doc.find('./Folder/[Name="images"]/..')

            if trackfolder:
                self.colourIndex = \
                    ((len(trackfolder.findall(KML.PlaceMark)) - 1) % 
                      self.colourSetLen)
        else:
            # create a new KML structure from scratch
            doc = KML.Document(
                      KML.description('Tracks and image placemarks'),
                      KML.visibility('1'),
                      KML.open('1'),
                      KML.name("Tracks and Images")
                  )
    
            # Append a style for pictures using the camera icon
            doc.append(
                KML.Style(
                    KML.IconStyle(
                        KML.scale(1.0),
                        KML.Icon(
                            KML.href(
                                'http://maps.google.com/mapfiles/kml/'\
                                'shapes/camera.png'),
                        ),
                        id="picture_style"
                    ),
                    id='picture'
                )
            )
    
            # Append styles for lines in different colours
            colourSet = [['7fff0000', 6, 'ffff0000', 8],
                         ['7f00ff00', 6, 'ff00ff00', 8],
                         ['7f0000ff', 6, 'ff0000ff', 8],
                         ['7fffff00', 6, 'ffffff00', 8],
                         ['7fff00ff', 6, 'ffff00ff', 8],
                         ['7f00ffff', 6, 'ff00ffff', 8]]
            self.colourSetLen = len(colourSet)
            
            for colourIndex in range(len(colourSet)):
                normal, narrow, highlight, wide = colourSet[colourIndex]
                colourID = 'colour' + str(colourIndex)
                self.colourStyle(doc, 
                                 colourID, 
                                 normal, 
                                 narrow,
                                 highlight,
                                 wide)
            
            trackfolder = KML.Folder(
                              KML.Name('tracks')
                              )
            doc.append(trackfolder)
            
            imagefolder = KML.Folder(
                              KML.Name('images')
                              )
            doc.append(imagefolder)

        return (doc, trackfolder, imagefolder)
开发者ID:redmanr,项目名称:jpggps2kml,代码行数:80,代码来源:jpggps2kml.py

示例8: main

# 需要导入模块: from pykml.factory import KML_ElementMaker [as 别名]
# 或者: from pykml.factory.KML_ElementMaker import open [as 别名]
def main():
# ###############################################################################

    usage = "usage: %prog [options] <gpxfile>\n\n"
    usage += "where:\n"
    usage += "  <gpxfile>\tgpx formatted file"

    parser = optparse.OptionParser(usage=usage)
    parser.add_option("-p", "--points", dest="points", action="store_true", help="specify if points output is desired", default=False)
    parser.add_option("-f", "--flyover", dest="flyover", action="store_true", help="specify if flyover output is desired", default=False)
    parser.add_option("-c", "--color", dest="color", help="track color if not flyover", default='641400FF')
    parser.add_option("-o", "--output", dest="output", help="output file", default=None)
    (options, args) = parser.parse_args()

    # see http://www.zonums.com/gmaps/kml_color/
    colors = {'pink':'64781EF0', 'blue':'64F01E14'}
    
    gpxfile = args.pop(0)
    if options.output == None:
        outfile = os.path.basename(gpxfile) + '.kml'
    else:
        outfile = options.output

    # get input
    _GPX = open(gpxfile,'r')
    gpx = gpxpy.parse(_GPX)

    # create a KML file skeleton
    stylename = "sn_shaded_dot"
    color = colors[options.color]
    sty = KML.Style(
        KML.IconStyle(
            KML.scale(1.2),
            KML.Icon(
                KML.href("http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png")
                ),
            KML.color(colors[options.color]),
            ),
        id=stylename,
        )
    iconstylename = '#sn_shaded_dot'

    doc = KML.Document(
        KML.Name('generated from {0}'.format(gpxfile)),
        KML.open(1),
        )
    doc.append(sty)

    '''
    <TimeStamp>
      <when>1997-07-16T07:30:15Z</when>
    </TimeStamp>
    '''
    # loop through gpx tracks, creating kml placemarks
    times = []
    coords = []
    dists = []
    points = []
    lastpoint = None
    for track in gpx.tracks:
        for segment in track.segments:
            for point in segment.points:
                if not lastpoint:
                    lastpoint = point
                plon = point.longitude
                plat = point.latitude
                pelev = point.elevation
                points.append(point)
                thisdist = gpxpy.geo.distance(lastpoint.latitude, lastpoint.longitude, lastpoint.elevation, plat, plon, pelev)
                lastpoint = point
                dists.append(thisdist)
                ptime = t.dt2asc(point.time)
                times.append(ptime)
                coords.append('{lon},{lat},{alt}'.format(lon = plon,lat = plat,alt = 0))
    
    if options.flyover:
        plm = KML.Placemark()
        doc.append(plm)
        track = GX.track()
        plm.append(track)
        
        for when in times:
            track.append(KML.when(when))
        for coord in coords:
            track.append(KML.coordinates(coord))
            
        '''
        doc.append(KML.Placemark(
            KML.LookAt(
                KML.longitude(plon),
                KML.latitude(plat),
                KML.tilt(45),
                KML.heading(0),  # make this behind the guy
                KML.altitudeMode("relativeToGround"),
                KML.range(50),
                ),
            KML.Point(
                KML.altitudeMode("relativeToGround"),
                ,
                ,
#.........这里部分代码省略.........
开发者ID:MikeTYang,项目名称:running,代码行数:103,代码来源:gpx2kml.py


注:本文中的pykml.factory.KML_ElementMaker.open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。