Beispiel #1
0
def create_placemark_element(lat, lon, row, col, val, icon_file, inps):
    """Create an KMZ Placemark element.
    Parameters: lat/lon   - float, latitude / longitude in degrees
                row/col   - int, row / column number
                val       - float, value
                icon_file - str, path of the icon file
                inps      - Namespace object
    Returns:    placemark - KMZ.Placemark() object
    """

    placemark = KML.Placemark(
        # style
        KML.Style(
            KML.IconStyle(
                    KML.color(get_hex_color(val, inps.colormap, inps.norm)),
                    KML.scale(0.5),
                    KML.Icon(KML.href(icon_file),
                ),
            ),
        ),

        # extended data
        KML.ExtendedData(
            KML.Data(
                KML.value(f"{lat:.6f}˚"),
                name="Latitude",
            ),
            KML.Data(
                KML.value(f"{lon:.6f}˚"),
                name="Longitude",
            ),
            KML.Data(
                KML.value(f"{row:.0f}"),
                name="Row",
            ),
            KML.Data(
                KML.value(f"{col:.0f}"),
                name="Column",
            ),
            KML.Data(
                KML.value(f"{val:.2f} {inps.disp_unit}"),
                name="Value",
            ),
        ),

        # point coord
        KML.Point(
            KML.coordinates(f"{lon},{lat}"),
        ),
    )

    return placemark
Beispiel #2
0
def photo2kml(files):
    tag_inds = [tag_dict[t] for t in meta_tags]
    metadata, inc = exiftool(files, tag_inds)
    # sorded by datetime
    metadata = sorted(metadata, key=lambda l: l[3])
    ndata = len(metadata)

    if not inc:
        sys.exit('Error: File not found.')
    elif not ndata:
        sys.exit('Error: GPSInfo not found in file.')

    kml_doc = KML.kml(
        KML.Document(
            KML.name(trip_name),
            KML.Style(
                KML.IconStyle(
                    KML.color(color_argb),  # only valid in Google Earth
                    KML.scale(1.),  # only valid in Google Earth
                    KML.Icon(KML.href(icon_url)),
                    KML.hotSpot(x='0.5',
                                y='0.0',
                                xunits="fraction",
                                yunits="fraction")),
                id='icon_style',
            )))

    # append location one by one
    for meta in metadata:

        msg = 'Photo location.'
        #msg += '\nTrip: %s' % trip_name
        #msg += '\nTime: %s' % meta[3]
        #msg += '\nModel: %s' % meta[4]
        #msg += '\nName: %s' % meta[0]
        kml_doc.Document.append(
            KML.Placemark(
                # use datetime as marker name
                KML.name(meta[3]),
                KML.styleUrl('#%s' % 'icon_style'),
                KML.description(msg),
                KML.Point(KML.coordinates('%f, %f' % (meta[1], meta[2]))),
                # ExtendedData only valid in Google Map
                KML.ExtendedData(
                    KML.Data(KML.value(trip_name), name='Trip'),
                    KML.Data(KML.value(meta[3]), name='Time'),
                    KML.Data(KML.value(meta[4]), name='Model'),
                    KML.Data(KML.value(meta[0].replace('./', '')),
                             name='Name'),
                )))
    return kml_doc, ndata
Beispiel #3
0
def extend(infos, expocode):
    extended = KML.ExtendedData(
        KML.Data(
            KML.value(expocode),
            name='expocode',
        ), *infos)
    return extended
Beispiel #4
0
def get_info(expocode):
    info = {}

    sesh = session()
    cruise = sesh.query(Cruise).filter(Cruise.ExpoCode == expocode).first()

    keymap = [
        ['line', 'Line'],
        ['country', 'Country'],
        ['date_start', 'Begin_Date'],
        ['date_end', 'EndDate'],
        ['ship', 'Ship_Name'],
        ['alias', 'Alias'],
        ['group', 'Group'],
        ['program', 'Program'],
        ['link', 'link'],
    ]
    for key, attr in keymap:
        info[key] = get_attribute(cruise, attr)

    cs = []

    chiefs = cruise.contacts_cruises

    for x in chiefs:
        first = x.contact.FirstName
        last = x.contact.LastName
        name = first + " " + last
        cs.append(name)

    clist = ", ".join(cs)
    info['chisci'] = clist
    sesh.close()
    infos = []
    for k, v in info.items():
        try:
            infos.append(KML.Data(
                KML.value(v),
                name=k,
            ))
        except ValueError:
            pass

    return info, cruise, infos
 def generateKMZs(self, dirs, outputDir):
     for index, directory in enumerate(dirs):
         geotaggedDir = os.path.join(directory, "Geotagged-Images")
         dirName = os.path.basename(directory)
         QgsMessageLog.logMessage(dirName, "dirs", 0)
         imgToGPS = self.constructImgMap(geotaggedDir, dirName)
         if imgToGPS is None:
             return
         root = KML.kml(
             KML.Document(
                 KML.name(dirName),
                 KML.Style(KML.IconStyle(
                     KML.Icon(
                         KML.href(
                             "http://maps.google.com/mapfiles/kml/pushpin/wht-pushpin.png"
                         )), KML.colorMode("normal"), KML.scale(0.6)),
                           id="scale")))
         for imgName in imgToGPS:
             lon, lat, alt = imgToGPS[imgName]
             if lat and lon and alt:
                 placemark = KML.Placemark(
                     KML.visibility(0),
                     KML.description("{}, {}m".format(imgName, alt)),
                     KML.styleUrl("#scale"),
                     KML.Point(
                         KML.coordinates("{}, {}, {}".format(lon, lat,
                                                             alt))),
                     KML.ExtendedData(
                         KML.Data(KML.value(imgName), name='imgName'),
                         KML.Data(KML.value(geotaggedDir), name='imgDir'),
                         KML.Data(KML.value(dirName), name='folderName'),
                         KML.Data(KML.value(lat), name='Latitude'),
                         KML.Data(KML.value(lon), name='Longitude'),
                         KML.Data(KML.value(alt), name='Altitude')))
                 root.Document.append(placemark)
             else:
                 reply = QMessageBox.question(
                     self.iface.mainWindow(), 'Continue?',
                     'Warning: {} in {} cannot be found. Still continue?'.
                     format(imgName,
                            dirName), QMessageBox.Yes, QMessageBox.No)
                 if (reply == QMessageBox.No):
                     return
         outputPath = os.path.join(outputDir, dirName + ".kmz")
         kml_str = '<?xml version="1.0" encoding="UTF-8"?>\n'
         kml_str += etree.tostring(root, pretty_print=True).decode('UTF-8')
         with ZipFile(outputPath, 'w') as zip:
             zip.writestr('doc.kml', kml_str)
Beispiel #6
0
    def export_data(self, dataset):
        """
        Returns format representation for given dataset.
        """
        kml_doc = KML.Document(KML.name('PCA Locations'))

        for pca_data in dataset.dict:

            locations = GwPCALocation.objects.filter(pca__id=pca_data['ID'])

            for loc in locations:

                data_copy = pca_data.copy()
                data_copy['Locality'] = loc.locality.name
                data_copy['CAD_CODE'] = loc.locality.cad_code
                data_copy['CAS_CODE'] = loc.locality.cas_code
                data_copy['Gateway'] = loc.gateway.name
                data_copy['Location Name'] = loc.location.name

                data = KML.ExtendedData()
                for key, value in data_copy.items():
                    data.append(KML.Data(KML.value(value), name=key))

                point = KML.Placemark(
                    KML.name(data_copy['Number']),
                    data,
                    KML.Point(
                        KML.coordinates('{long},{lat}'.format(
                            lat=loc.location.point.y,
                            long=loc.location.point.x)), ),
                )

                kml_doc.append(point)

        return etree.tostring(etree.ElementTree(KML.kml(kml_doc)),
                              pretty_print=True)
Beispiel #7
0
def ConvertShapeToPlacemark(shape, geoid, aland, awater, kml):
  #if len(shape.parts) > 1:
  #  print '----------geoid=%s aland=%s awater=%s' % (geoid, aland, awater)
  if shape.shapeType != 5:
    raise Exception('Unexpected shape type [%d] in file' % shape.shapeType)

  pm = KML.Placemark(
    KML.name('%s' % geoid),
    KML.styleUrl('#ts'),
    KML.ExtendedData(
      KML.Data(
        KML.displayName('ALAND'),
        KML.value(aland),
        name='string'
      ),
      KML.Data(
        KML.displayName('AWATER'),
        KML.value(awater),
        name='string'
      )
    ),
    KML.MultiGeometry(
      KML.Polygon(
        KML.extrude(0),
        KML.altitudeMode('clampToGround')
      )
    )
  )

  # The parentPoly will be used to append rings, and a
  # new Polygon will be appended for multiple rings in
  # a geography.
  parentPoly = pm.MultiGeometry.Polygon

  #if len(shape.parts) > 1:
  #  print 'shape has %d parts' % len(shape.parts)
  for i in range(0, len(shape.parts)):
    lo = shape.parts[i]
    hi = len(shape.points)
    if i < len(shape.parts) - 1:
      hi = shape.parts[i + 1]
    #if len(shape.parts) > 1:
    #  print 'shape has points in [%d, %d) of %d' % (lo, hi, len(shape.points))
    if (shape.points[lo][0] != shape.points[hi-1][0] or
        shape.points[lo][1] != shape.points[hi-1][1]):
      raise Exception('Loop endpoints in [%d, %d) do not match' % (lo, hi))
    coords = []
    for j in reversed(range(lo, hi)):
      lng = shape.points[j][0]
      lat = shape.points[j][1]
      coords.append([lng, lat])

    latlngCoords = []
    for c in coords:
      latlngCoords.append('%f,%f,0' % (c[0], c[1]))
    coordinates = ' '.join(latlngCoords)

    # Note: need LinearRing to compute ccw. Need Polygon to compute contains().
    spoly = SPolygon(coords)
    if i == 0:
      parentSpoly = spoly
    ring = polygon.LinearRing(coords)

    # Some sanity checks to make sure all rings are closed, non-empty,
    # and valid.
    if not ring.is_ring:
      raise Exception('Badly formatted non-ring : %s' % geoid)
    if ring.is_empty:
      raise Exception('Empty geometry found: %s' % geoid)
    if not ring.is_valid:
      raise Exception('Invalid ring: %s' % geoid)

    if not ring.is_ccw:
      # This ring is an internal (enclave) ring.
      rring = copy.deepcopy(ring)
      rring.coords = list(rring.coords)[::-1]
      # Shapely contains does not handle point-overlaps. This
      # means that enclaves which touch the containing ring
      # are not handled correctly. To cure this, we check two
      # points.
      if not (parentSpoly.contains(SPoint(rring.coords[0])) or
              parentSpoly.contains(SPoint(rring.coords[1]))):
        print 'Out-of-order enclave'
        # print 'ring %s does not contain %s' % (parentSpoly, ring)
        # print ring
        # print rring
        # Note: if this triggers, we will need to store the polys
        # to figure out which one is the enclosing one. Hopefully
        # the census files will not exhibit this, although it is
        # legal strictly according to the shapefule spec.
        raise Exception('Out-of-order enclave')
        coordinates = coordinates + ' 0,0,0'
        parentPoly.append(KML.innerBoundaryIs(
          KML.LinearRing(
            KML.coordinates(coordinates)
          )
        ))
      else:
        # Find the containing poly...
        parentPoly.append(KML.innerBoundaryIs(
         KML.LinearRing(
            KML.coordinates(coordinates)
          )
        ))
    else:
      if i > 0:
        # Set the new parent polygon ring.
        parentSpoly = spoly
        parentPoly = KML.Polygon(
          KML.extrude(0),
          KML.altitudeMode('clampToGround'))
        pm.MultiGeometry.append(parentPoly)
      parentPoly.append(KML.outerBoundaryIs(
        KML.LinearRing(
          KML.coordinates(coordinates)
        )
      ))

  return pm
Beispiel #8
0
def makeExtendedDataElements(datadict):
    '''Converts a dictionary to ExtendedData/Data elements'''
    edata = KML.ExtendedData()
    for key, value in datadict.items():
        edata.append(KML.Data(KML.value(value), name=key + "_"))
    return edata
Beispiel #9
0
    def createPlacemarkForSelection(self, cmp, uuid, center, fld):
        
        #geomtryLinks =  cmp.getAttribute("Geometry").getLinks()
        
        #for link in geomtryLinks:
        #    link.
        l = cmp.getAttribute("l_bounding").getDouble()
        b = cmp.getAttribute("b_bounding").getDouble()
        h = cmp.getAttribute("h_bounding").getDouble()
        alpha = cmp.getAttribute("alpha_bounding").getDouble()
 
        nodes = []
        nodes.append(Node(l/2, -b/2, h))
        nodes.append(Node(l/2, b/2, h))
        nodes.append(Node(-l/2, b/2, h))
        nodes.append(Node(-l/2, -b/2, h))
        nodes.append(Node(l/2, -b/2, h))
        
        nodes = self.rotatePolygon(nodes, alpha)
        nodes = self.translatePolygon(nodes, center)
        
        nodes_transformed = []
        exdata = KML.ExtendedData()
        attributes = cmp.getAllAttributes()
        for k in attributes:
            attr = attributes[k]
            #print attr.getType()
            if attr.getType() == Attribute.DOUBLE:
                #print str(k) + " " + str(attr.getDouble())
                d = KML.Data(
                         KML.name(k),
                         KML.value(attr.getDouble()),
                    )
                exdata.append(d)
                    
        
        for n in nodes:
            nodes_transformed.append(self.transformCoorindate(n))
        coordinates =  ''
        for n in nodes_transformed:
            coordinates+="{0},{1},{2}".format(n.getX(), n.getY(), n.getZ())+"\n"
    
        
        y = int(cmp.getAttribute("built_year").getDouble())
        if y < 1:
                y = 1900
        m = 1
        d = 1
        pm = KML.Placemark(
                           KML.name(uuid+"_Data"),
                           exdata,
                           KML.styleUrl("#transRedPoly"),
                           KML.TimeStamp(
                               KML.when((date(y,m,d)).strftime('%Y-%m-%dT%H:%MZ')),
                            ),
                           KML.Polygon(
                                       KML.extrude(1),
                                       KML.altitudeMode("relativeToGround"),
                                       KML.outerBoundaryIs(
                                                            KML.LinearRing(

                                                                            KML.coordinates(coordinates),
                                                                           ),
                                                            ),
                                        ),
                               
                            )
        fld.append(pm)
Beispiel #10
0
    datum = str(date.date(int(yyyy[i]), int(mm[i]), int(dd[i])))
    ev_time = str(date.time(int(hr[i]), int(mn[i]), int(ss[i])))
    eventid = event_id[i]
    Mw = data['mw'][i]
    CD = data['CD'][i]
    Mo = data['mo'][i]

    kmlobj.Document.append(
        KML.Placemark(
            KML.name(
                '%s' % str(eventid)
            ),  #uncomment this to add a name to the placemark (will always appear in GoogleEarth)
            KML.
            ExtendedData(  #I add information about the earthquake, it appears in a table ('info' : value)
                KML.Data(
                    KML.value('%s' % datum),  #add value of the specific info
                    name='date'  #name of'info' you add.
                ),
                KML.Data(
                    KML.value('%s' %
                              ev_time),  #add value of the specific info 
                    name='time'  #name of 'info' you add.
                ),
                KML.Data(KML.value('%s' % eventid), name='event_id'),
                KML.Data(KML.value('%s' % Mw), name='Mw'),
                KML.Data(KML.value('%s' % CD), name='CD'),
                KML.Data(KML.value('%s' % Mo), name='Mo'),
            ),  #more data can be added, following the same structure 
            KML.styleUrl(
                '#beach_ball_%s' % eventid
            ),  #get the correct beachball in the directory as marker
            KML.Point(KML.coordinates(longitude[i], ',', latitude[i]), ),
Beispiel #11
0
    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",
                ),
                KML.Style(
                    KML.LineStyle(
                        KML.color('ff00ff00'),
                        KML.width('4'),
                    ),
                    KML.PolyStyle(KML.color('400000ff'), ),
                    KML.BalloonStyle(
                        KML.text((
                            '<script type="text/javascript" src="http://dygraphs.com/dygraph-combined.js">'
                            '</script>'
                            '<div id="graphdiv"></div>'
                            '<script type="text/javascript">'
                            'g = new Dygraph('
                            'document.getElementById("graphdiv"),'
                            '$[csv_data],'
                            '{{'
                            'ylabel: \'{param} [{units}]\','
                            'legend: \'always\''
                            '}}'
                            ');'
                            '</script>').format(
                                param=meta.variable.name,
                                units=meta.variable.units,
                            ))),
                    id="style-highlight",
                ),
                #Time Folders will be appended here
            ), )
        try:
            s = db.Session()

            # create a folder to hold the geometries
            geom_fld = KML.Folder(KML.name('Geometries'), )

            for geom in s.query(db.Geometry).all():

                coord_list = geom.as_kml_coords()
                multigeom_args = [
                    KML.Polygon(
                        KML.tessellate('1'),
                        KML.outerBoundaryIs(
                            KML.LinearRing(KML.coordinates(coords.text), ), ),
                    ) for coords in coord_list
                ]

                # TODO: sort values by time to speed loading
                values = [
                    '{0},{1}'.format(
                        datetime.strftime(val.time, "%Y-%m-%d %H:%M:%S"),
                        val.value) for val in geom.values
                ]
                pm = KML.Placemark(
                    KML.name('Geometry'),
                    KML.ExtendedData(
                        KML.Data(
                            KML.value('"Date,{param}\\n{data}"'.format(
                                param=meta.variable.name,
                                data='\\n'.join(values))),
                            name="csv_data",
                        ), ),
                    KML.description(''),
                    KML.styleUrl('#smap'),
                    KML.MultiGeometry(*multigeom_args),
                )
                geom_fld.append(pm)
            doc.Document.append(geom_fld)


#            for time in s.query(db.Time).all():
#                # create a folder for the time
#                timefld = KML.Folder(
##                    KML.Style(
##                      KML.ListStyle(
##                        KML.listItemType('checkHideChildren'),
##                        KML.bgColor('00ffffff'),
##                        KML.maxSnippetLines('2'),
##                      ),
##                    ),
#                    KML.name(time.as_xml_date()),
#                    # placemarks will be appended here
#                )
#                for val in time.values:
#                    poly_desc = (
#                        '<table border="1">'
#                          '<tbody>'
#                            '<tr><th>Variable</th><td>{variable}</td></tr>'
#                            '<tr><th>Date/Time (UTC)</th><td>{time}</td></tr>'
#                            '<tr><th>Value</th><td>{value:.{digits}f} {units}</td></tr>'
#                          '</tbody>'
#                        '</table>'
#                    ).format(
#                        variable=meta.variable.name,
#                        time=val.time_ref.as_xml_date(),
#                        value=val.value,
#                        digits=3,
#                        units=meta.variable.units,
#                    )
#
#                    coords = val.geometry.as_kml_coords()
#                    timefld.append(
#                      KML.Placemark(
#                        KML.name('Geometry'),
#                        KML.description(poly_desc),
#                        KML.styleUrl('#smap'),
#                        KML.Polygon(
#                          KML.tessellate('1'),
#                          KML.outerBoundaryIs(
#                            KML.LinearRing(
#                              KML.coordinates(coords),
#                            ),
#                          ),
#                        ),
#                      )
#                    )
#                doc.Document.append(timefld)
#            pass
        finally:
            s.close()

        # return the pretty print string
        output = etree.tostring(doc, pretty_print=True)
        # Unescape newline characters
        #return(output.replace('&amp;#10;','\\n'))
        return (output)
Beispiel #12
0
def create_ev_sta_kml(input_dics, events):
    """
    create event/station/ray in KML format readable by Google-Earth
    :param input_dics:
    :param events:
    :return:
    """
    try:
        from pykml.factory import KML_ElementMaker as KML
        from lxml import etree
    except:
        sys.exit('[ERROR] pykml should be installed first!')

    if not os.path.isdir('kml_dir'):
        os.mkdir('kml_dir')
    else:
        print('[INFO] kml_dir already exists!')

    # create a document element with multiple label style
    kmlobj = KML.kml(KML.Document())
    counter = 0
    for ei in range(len(events)):
        print(events[ei]['event_id'])
        counter += 1

        ev_date = '%04i/%02i/%02i-%02i:%02i:%02i' \
                  % (events[ei]['datetime'].year,
                     events[ei]['datetime'].month,
                     events[ei]['datetime'].day,
                     events[ei]['datetime'].hour,
                     events[ei]['datetime'].minute,
                     events[ei]['datetime'].second
                     )

        if input_dics['plot_focal']:
            try:
                focmecs = [float(events[ei]['focal_mechanism'][0]),
                           float(events[ei]['focal_mechanism'][1]),
                           float(events[ei]['focal_mechanism'][2]),
                           float(events[ei]['focal_mechanism'][3]),
                           float(events[ei]['focal_mechanism'][4]),
                           float(events[ei]['focal_mechanism'][5])]
            except:
                print("WARNING: 'focal_mechanism' does not exist!")
                focmecs = [1, 1, 1, 0, 0, 0]
        else:
            focmecs = [1, 1, 1, 0, 0, 0]

        if 0 <= events[ei]['depth'] < 70:
            event_color = 'red'
        elif 70 <= events[ei]['depth'] < 300:
            event_color = 'green'
        else:
            event_color = 'blue'

        try:
            Beachball(focmecs,
                      outfile=os.path.join(
                          'kml_dir', events[ei]['event_id'] + '.png'),
                      facecolor=event_color,
                      edgecolor=event_color)
        except Exception as error:
            print(error)
            print(focmecs)
            continue
        plt.close()
        plt.clf()

        if input_dics['plot_ev'] or input_dics['plot_ray']:
            kmlobj.Document.append(
                KML.Style(
                    KML.IconStyle(
                        KML.Icon(KML.href(os.path.join(
                            events[ei]['event_id'] + '.png')),
                        ),
                        KML.scale(events[ei]['magnitude']/2.),
                        KML.heading(0.0),
                    ),
                    id='beach_ball_%i' % counter
                ),
            )

            kmlobj.Document.append(
                KML.Placemark(
                    KML.name(events[ei]['event_id']),
                    KML.ExtendedData(
                        KML.Data(
                            KML.value('%s' % events[ei]['event_id']),
                            name='event_id'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['magnitude']),
                            name='magnitude'
                        ),
                        KML.Data(
                            KML.value('%s' % ev_date),
                            name='datetime'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['depth']),
                            name='depth'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['latitude']),
                            name='latitude'
                        ),
                        KML.Data(
                            KML.value('%s' % events[ei]['longitude']),
                            name='longitude'
                        ),
                    ),
                    KML.styleUrl('#beach_ball_%i' % counter),
                    # KML.Point(KML.coordinates(events[ei]['longitude'], ',',
                    #                           events[ei]['latitude'], ',',
                    #                           700000 -
                    #                           abs(events[ei]['depth']*1000)),
                    #           KML.altitudeMode('absolute')
                    #           ),
                    KML.Point(KML.coordinates(events[ei]['longitude'], ',',
                                              events[ei]['latitude'], ',',
                                              0.),
                              KML.altitudeMode('absolute')
                              ),
                ),
            )

        if input_dics['plot_sta'] or input_dics['plot_ray']:
            target_path = locate(input_dics['datapath'],
                                 events[ei]['event_id'])
            if len(target_path) < 1:
                continue
            if len(target_path) > 1:
                print("[LOCAL] more than one path was found for the event:")
                print(target_path)
                print("[INFO] use the first one:")
                target_path = target_path[0]
                print(target_path)
            else:
                print("[LOCAL] Path:")
                target_path = target_path[0]
                print(target_path)

            update_sta_ev_file(target_path, events[ei])
            sta_ev_arr = np.loadtxt(os.path.join(target_path,
                                                 'info', 'station_event'),
                                    delimiter=',', dtype=bytes, ndmin=2).astype(np.str)
            sta_ev_arr = sta_ev_arr.astype(np.object)
            del_index = []
            for sti in range(len(sta_ev_arr)):

                if not plot_filter_station(input_dics, sta_ev_arr[sti]):
                    del_index.append(sti)

                dist, azi, bazi = gps2DistAzimuth(events[ei]['latitude'],
                                                  events[ei]['longitude'],
                                                  float(sta_ev_arr[sti, 4]),
                                                  float(sta_ev_arr[sti, 5]))

                epi_dist = dist/111.194/1000.
                if input_dics['min_azi'] or input_dics['max_azi'] or \
                        input_dics['min_epi'] or input_dics['max_epi']:
                    if input_dics['min_epi']:
                        if epi_dist < input_dics['min_epi']:
                            del_index.append(sti)
                    if input_dics['max_epi']:
                        if epi_dist > input_dics['max_epi']:
                            del_index.append(sti)
                    if input_dics['min_azi']:
                        if azi < input_dics['min_azi']:
                            del_index.append(sti)
                    if input_dics['max_azi']:
                        if azi > input_dics['max_azi']:
                            del_index.append(sti)

            del_index = list(set(del_index))
            del_index.sort(reverse=True)
            for di in del_index:
                sta_ev_arr = np.delete(sta_ev_arr, (di), axis=0)

            kmlobj.Document.append(
                KML.Style(
                    KML.IconStyle(
                        KML.scale(2.5),
                        KML.heading(0.0),
                    ),
                    id='station'
                ),
            )
            kmlobj.Document.append(
                KML.Style(
                    KML.LineStyle(
                        KML.width(1.0),
                        # KML.color('ff33ccff'),
                        KML.color('2333ccff'),
                    ),
                    id='great_circle_distance'
                ),
            )
            for sti in sta_ev_arr:
                dist, azi, bazi = gps2DistAzimuth(events[ei]['latitude'],
                                                  events[ei]['longitude'],
                                                  float(sti[4]),
                                                  float(sti[5]))
                epi_dist = dist/111.194/1000.
                sta_id = '%s.%s.%s.%s' % (sti[0], sti[1], sti[2], sti[3])
                kmlobj.Document.append(
                    KML.Placemark(
                        KML.name(sta_id),
                        KML.ExtendedData(
                            KML.Data(
                                KML.value('%s' % sta_id),
                                name='StationID'
                            ),
                            KML.Data(
                                KML.value('%s' % epi_dist),
                                name='Distance'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[6]),
                                name='Elevation'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[7]),
                                name='Depth'
                            ),
                            KML.Data(
                                KML.value('%s' % bazi),
                                name='Back-Azimuth'
                            ),
                            KML.Data(
                                KML.value('%s' % azi),
                                name='Azimuth'
                            ),
                            KML.Data(
                                KML.value('%s' % events[ei]['event_id']),
                                name='EventID'
                            ),
                            KML.Data(
                                KML.value('%s' % sti[8]),
                                name='Source'
                            ),
                        ),
                        KML.styleUrl('station'),
                        KML.Point(KML.coordinates(
                            float(sti[5]), ',', float(sti[4]))
                        ),
                    ),
                )
                if input_dics['plot_ray']:
                    kmlobj.Document.append(
                        KML.Placemark(
                            KML.name(sta_id),
                            KML.ExtendedData(
                                KML.Data(
                                    KML.value('%s' % sta_id),
                                    name='StationID'
                                ),
                            ),
                            KML.styleUrl('great_circle_distance'),
                            KML.LineString(KML.coordinates(
                                '%s,%s,0\n'
                                '%s,%s,0' % (float(sti[5]),
                                             float(sti[4]),
                                             events[ei]['longitude'],
                                             events[ei]['latitude'])),
                                KML.tessellate(1)),
                        ),
                    )
    kml_outfile = file(os.path.join(
        'kml_dir',
        'kml_output.kml'), 'w')
    kml_outfile.write(etree.tostring(kmlobj, pretty_print=True))
    sys.exit('[INFO] KML file is stored in ./kml_dir!')
Beispiel #13
0
    # group POIs by folder based on output log file name
    group_name = f_name_base[:-len(output_log_suffix)]
    kml_poi_folder = KML.Folder(KML.name(group_name))
    kml_poi_doc.append(kml_poi_folder)
    lines = open(f_path).readlines()
    for line in lines:
        lat, lon, time, frame, found, uid, pixelx, pixely = line.split(" ")
        lat = dms2dec(lat)
        lon = dms2dec(lon)
        coord = lon + "," + lat
        # create POI
        pml = KML.Placemark(KML.name(uid),KML.Point(KML.coordinates(coord)))
        # add all data as extended data
        ext = KML.ExtendedData()
        pml.append(ext)
        ext.append(KML.Data(KML.value(uid), name="uid"))
        ext.append(KML.Data(KML.value(time), name="time"))
        ext.append(KML.Data(KML.value(frame), name="frame"))
        ext.append(KML.Data(KML.value(pixelx), name="pixelX"))
        ext.append(KML.Data(KML.value(pixely), name="pixelY"))
        kml_poi_folder.append(pml)
        # find image by id and optionally put it in kmz
        img_name = image_prefix + uid + image_ext
        img_path = os.path.join(work_dir, img_name)	#added 4/23
        if (os.path.exists(img_path)):
            pml.append(KML.description("<img src='" + img_name + "' width='400' />"))
            if (create_images_kmz):
               zipf.write(img_path, img_name)

f_out_poi_kml = open(poi_kml_output_file_name, "w")
f_out_poi_kml.write(etree.tostring(kml_poi, pretty_print=True))
Beispiel #14
0
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"),
                ,
                ,
                )
            ))
        '''
        
    elif options.points:
        #for coord in coords:
        #    ls.append(KML.coordinates(coord))
        lasttime = t.asc2epoch(times[0])
        totdist = 0
        for i in range(len(times)):
            thistime = t.asc2epoch(times[i])
            dur = thistime - lasttime
            lasttime = thistime
            totdist += dists[i]
            ex = KML.ExtendedData(
                KML.Data(KML.displayName('time'),KML.value(times[i])),
                KML.Data(KML.displayName('duration'),KML.value(dur)),
                KML.Data(KML.displayName('totdistance'),KML.value(int(round(totdist)))),
                )
            plm = KML.Placemark(
                #KML.name(times[i]),
                KML.name(''),
                KML.styleUrl(iconstylename),
                )
            plm.append(ex)
            plm.append(KML.Point(
                KML.altitudeMode('clampToGround'),
                KML.coordinates(coords[i])))
            doc.append(plm)
    
    else:
        if options.color:
            doc.append(
                KML.Style(
                    KML.LineStyle(
                    KML.color(colors[options.color]),
                    KML.width(5),
                    ),
                id=options.color))
            stylename = '#{0}'.format(options.color)
        
        '''
        <LineString id="ID">
          <!-- specific to LineString -->
          <gx:altitudeOffset>0</gx:altitudeOffset>  <!-- double -->
          <extrude>0</extrude>                      <!-- boolean -->
          <tessellate>0</tessellate>                <!-- boolean -->
          <altitudeMode>clampToGround</altitudeMode> 
              <!-- kml:altitudeModeEnum: clampToGround, relativeToGround, or absolute -->
              <!-- or, substitute gx:altitudeMode: clampToSeaFloor, relativeToSeaFloor -->
          <gx:drawOrder>0</gx:drawOrder>            <!-- integer --> 
          <coordinates>...</coordinates>            <!-- lon,lat[,alt] -->
        </LineString>
        '''
        plm = KML.Placemark(
            KML.name('runtrack'),
            )
        if options.color:
            plm.append(KML.styleUrl(stylename))
        doc.append(plm)
        ls = KML.LineString(
            KML.altitudeMode('clampToGround'),
#            KML.extrude(1),
#            KML.tessellate(1),
            )
        plm.append(ls)
        #for coord in coords:
        #    ls.append(KML.coordinates(coord))
        kcoords = ''
        for coord in coords:
            kcoords += coord + ' \n'
        ls.append(KML.coordinates(kcoords))
        
    _GPX.close()

    kml = KML.kml(doc)
    
    docstr = etree.tostring(kml, pretty_print=True)
    OUT = open(outfile,'w')
    OUT.write(docstr)
    OUT.close()
Beispiel #15
0
    def getkml(self):
        avgalt = sum([i.Altitude
                      for i in self.waypoints]) / float(len(self.waypoints))
        minlat = min([i.Latitude for i in self.waypoints])
        minlon = min([i.Longitude for i in self.waypoints])
        maxlon = max([i.Longitude for i in self.waypoints])
        maxlat = max([
            i.Latitude + (i.Altitude - avgalt) /
            (60.0 * 1852.0 * math.cos(math.radians(-20)))
            for i in self.waypoints
        ])
        if abs(maxlon - minlon) > abs(maxlat - minlat):
            rang = abs(maxlon - minlon) * 60.0 * 1852.0 / (
                2.0 * math.sin(math.radians(self.hfov) / 2.0)) * 1.2
        else:
            rang = abs(maxlat - minlat) * 60.0 * 1852.0 / (
                2.0 * math.sin(math.radians(self.hfov) / 2.0)) * 16.0 / 9.0
        txtwaypoints = ' '.join([
            '%f,%f,%f' % (i.Longitude, i.Latitude, i.Altitude)
            for i in self.waypoints
        ])
        txtsmoothed = ' '.join([
            '%f,%f,%f' % (i.Longitude, i.Latitude, i.Altitude)
            for i in self.smoothed
        ])

        wfolder = KML.Folder(
            KML.name('WayPoint Markers'),
            KML.visibility(1),
        )
        pfolder = KML.Folder(
            KML.name('POI Markers'),
            KML.visibility(1),
        )
        vfolder = KML.Folder(
            KML.name('WayPoint Views'),
            KML.visibility(0),
        )
        playlist = GX.Playlist()

        #TODO: CDATA
        virtmission = KML.kml(
            KML.Document(
                KML.name(self.mission),
                KML.LookAt(
                    KML.latitude((minlat + maxlat) / 2.0),
                    KML.longitude((minlon + maxlon) / 2.0),
                    KML.altitude(avgalt),
                    KML.heading(0),
                    KML.tilt(70),
                    KML.range(rang),
                    KML.altitudeMode("absolute"),
                    GX.horizFov(self.hfov),
                ),
                GX.Tour(
                    KML.name('Virtual Mission'),
                    playlist,
                ),
                KML.Style(
                    KML.LineStyle(
                        KML.color('FF00FFFF'),
                        KML.width(2),
                    ),
                    KML.PolyStyle(KML.color('4C00FFFF'), ),
                    id='wpstyle',
                ),
                KML.Style(
                    KML.LineStyle(
                        KML.color('FFFF00FF'),
                        KML.width(2),
                    ),
                    KML.PolyStyle(KML.color('4CFF00FF'), ),
                    id='smoothstyle',
                ),
                KML.Style(
                    KML.IconStyle(
                        KML.Icon(
                            KML.href(
                                'http://maps.google.com/mapfiles/kml/paddle/wht-blank.png'
                            ), ), ),
                    KML.BalloonStyle(
                        KML.text(
                            '\n<h3>WayPoint $[Waypoint]</h3>\n<table border="0" width="200">\n<tr><td>Altitude (msl) <td>$[Altitude_Abs] m\n<tr><td>Altitude (rtg) <td>$[Altitude_Gnd] m\n<tr><td>Heading<td>$[Heading] degrees\n<tr><td>Gimbal Tilt<td> $[Gimbal] degrees\n</tr></table>\n'
                        ),
                        KML.bgColor('ffffffbb'),
                    ),
                    id='wpmarkers',
                ),
                KML.Style(
                    KML.IconStyle(
                        KML.Icon(
                            KML.href(
                                'http://maps.google.com/mapfiles/kml/paddle/red-stars.png'
                            ), ), ),
                    KML.BalloonStyle(
                        KML.text(
                            '\n<h3>POI $[POI]</h3>\n <table border="0" width="200">\n <tr><td>Altitude (msl) <td>$[Altitude_Abs] m\n <tr><td>Altitude (rtg) <td>$[Altitude_Gnd] m\n </tr></table>\n'
                        ),
                        KML.bgColor('ffffffbb'),
                    ),
                    id='poimarkers',
                ),
                KML.Folder(
                    KML.name('Diagnostics'),
                    KML.Placemark(
                        KML.name('WayPoint Path'),
                        KML.visibility(0),
                        KML.styleUrl('#wpstyle'),
                        KML.LineString(
                            KML.extrude(1),
                            KML.tessellate(1),
                            KML.altitudeMode('absolute'),
                            KML.coordinates(txtwaypoints),
                        ),
                    ),
                    wfolder,
                    pfolder,
                    vfolder,
                    KML.Placemark(
                        KML.name('Smooth Flight Path'),
                        KML.visibility(1),
                        KML.styleUrl('#smoothstyle'),
                        KML.LineString(
                            KML.extrude(1),
                            KML.tessellate(1),
                            KML.altitudeMode('absolute'),
                            KML.coordinates(txtsmoothed),
                        ),
                    ),
                ),
            ))

        for wp in self.smoothed:
            playlist.append(
                GX.FlyTo(
                    GX.duration(wp.LegTime),
                    GX.flyToMode('smooth'),
                    KML.Camera(
                        KML.latitude(wp.Latitude),
                        KML.longitude(wp.Longitude),
                        KML.altitude(wp.Altitude),
                        KML.heading(wp.Heading),
                        KML.tilt(wp.GimbalTilt),
                        KML.roll(0),
                        KML.altitudeMode("absolute"),
                        GX.horizFov(self.hfov),
                    ),
                ), )
            playlist.append(GX.Wait(GX.duration(0), ), )

        for wp in self.waypoints:
            wfolder.append(
                KML.Placemark(
                    KML.name('WP%02d' % (wp.Num)),
                    KML.visibility(1),
                    KML.styleUrl('#wpmarkers'),
                    KML.ExtendedData(
                        KML.Data(KML.value(wp.Num), name='Waypoint'),
                        KML.Data(KML.value(round(wp.Altitude, 0)),
                                 name='Altitude_Abs'),
                        KML.Data(KML.value(round(wp.Altitude - wp.GroundAlt,
                                                 0)),
                                 name='Altitude_Gnd'),
                        KML.Data(KML.value(round(wp.Heading, 0)),
                                 name='Heading'),
                        KML.Data(KML.value(round(wp.GimbalTilt - 90.0, 0)),
                                 name='Gimbal'),
                    ),
                    KML.Point(
                        KML.altitudeMode("absolute"),
                        KML.extrude(1),
                        KML.coordinates(
                            '%f,%f,%f' %
                            (wp.Longitude, wp.Latitude, wp.Altitude)),
                    ),
                ), )

        for poi in self.pois:
            num = self.pois.index(poi) + 1
            pfolder.append(
                KML.Placemark(
                    KML.name('POI%02d' % num),
                    KML.visibility(1),
                    KML.styleUrl('#poimarkers'),
                    KML.ExtendedData(
                        KML.Data(KML.value(num), name='POI'),
                        KML.Data(KML.value(round(poi.Altitude, 0)),
                                 name='Altitude_Abs'),
                        KML.Data(KML.value(
                            round(poi.Altitude - poi.GroundAlt, 0)),
                                 name='Altitude_Gnd'),
                    ),
                    KML.Point(
                        KML.altitudeMode("absolute"),
                        KML.extrude(1),
                        KML.coordinates(
                            '%f,%f,%f' %
                            (poi.Longitude, poi.Latitude, poi.Altitude)),
                    ),
                ), )

        for wp in self.smoothed:
            if wp.Num is None:
                continue
            vfolder.append(
                KML.Document(
                    KML.name('WP%03d' % (wp.Num)),
                    KML.visibility(0),
                    KML.Camera(
                        KML.latitude(wp.Latitude),
                        KML.longitude(wp.Longitude),
                        KML.altitude(wp.Altitude),
                        KML.heading(wp.Heading),
                        KML.tilt(wp.GimbalTilt),
                        KML.roll(0),
                        KML.altitudeMode("absolute"),
                        GX.horizFov(self.hfov),
                    ),
                ), )

        return etree.tostring(virtmission, pretty_print=True)