示例#1
0
    def rotation_around_placemark(self, data, params, kml_doc):
        if type(data) is list:
            print("list")
            longitude = data[0]
            latitude = data[1]
        else:
            longitude = data.longitude
            latitude = data.latitude

        # spin around the data
        for aspect in range(0, 360, 10):
            kml_doc.Document[gxns + "Tour"].Playlist.append(
                GX.FlyTo(
                GX.duration(params[0]),
                    GX.flyToMode("smooth"),
                    KML.LookAt(
                        KML.longitude(float(longitude)),
                        KML.latitude(float(latitude)),
                        KML.altitude(params[1]),
                        KML.heading(aspect),
                        KML.tilt(params[2]),
                        KML.range(params[3]),
                        KML.altitudeMode("relativeToGround"),
                    )
                )
            )

        kml_doc.Document[gxns + "Tour"].Playlist.append(GX.Wait(GX.duration(1.0)))

        return kml_doc
示例#2
0
def create_tour_doc(tour_doc, row, imageInterval):
    camHeight  = row['Z']
    longitude, latitude = myProj(row['X'], row['Y'], inverse = True)
    azimuth = row['azimuth']
    zenith = row['zenith']
    
    intervalNo = row['intervalNo']
    corrChunk = imageInterval[int(intervalNo)]
    # define a variable for the Google Extensions namespace URL string
    gxns = '{' + nsmap['gx'] + '}'
    #fly to the subChunk with the given subChunk parameters
    tour_doc.Document[gxns+"Tour"].Playlist.append(
        GX.FlyTo(
            GX.flyToMode("bounce"),
            KML.LookAt(
                KML.longitude(longitude),#change  chunk[] to subChunk from csv
                KML.latitude(latitude),#change  chunk[] to subChunk from csv
                KML.altitude(camHeight),#change  chunk[] to subChunk from csv
                KML.heading(azimuth),#change chunk[] to subChunk from csv
                KML.tilt(zenith),#change  chunk[] to subChunk from csv
                KML.range(corrChunk['range0']),#change all chunk[] to subChunk from csv
                KML.altitudeMode(corrChunk['altitudeMode']),
    						GX.horizFov(horizFov)
            )
        )
    )
    tour_doc.Document[gxns+"Tour"].Playlist.append(GX.Wait(GX.duration(corrChunk['lookAtDuration'])))
示例#3
0
 def kml_addPathPoint(self, pos, dt):
     #pos[0] : latitude
     #pos[1] : longitude
     #pos[2] : altitude
     #pos[3] : roll
     #pos[4] : pitch
     #pos[5] : yaw
     if (pos == None):
         return
     #rospy.logerr(pos)
     
     self.tour_doc.Document[self.gxns+"Tour"].Playlist.append(
         GX.FlyTo(
             GX.duration(dt),
             GX.flyToMode("smooth"),
             #KML.Camera(
             KML.LookAt(
                 KML.latitude(pos[0]),
                 KML.longitude(pos[1]),
                 KML.altitude(pos[2]),
                 KML.heading(pos[5]),
                 #KML.tilt(pos[4] + 90.0),
                 #KML.roll(pos[3]),
                 KML.tilt(pos[4] + 75.0),
                 KML.range(20.0),
                 KML.altitudeMode("absolute"),
             ),
         ),
     )
     
     auxStr = ' {lon},{lat},{alt}\n'.format(lon=pos[1], lat=pos[0], alt=pos[2])
     #rospy.logerr(auxStr)
     self.execCoordListStr = self.execCoordListStr + auxStr
示例#4
0
def build_test_kml():
    """build a simple KML file with a simple LineString, for testing purposes"""

    from pykml.factory import KML_ElementMaker as KML
    from pykml.factory import GX_ElementMaker as GX
    from lxml import etree
    from django.http import HttpResponse

    kml = KML.kml(
        KML.Placemark(
            KML.name("build_test_kml output"),
            KML.LookAt(
                KML.longitude(146.806),
                KML.latitude(12.219),
                KML.heading(-60),
                KML.tilt(70),
                KML.range(6300),
                GX.altitudeMode("relativeToSeaFloor"),
            ),
            KML.LineString(
                KML.extrude(1),
                GX.altitudeMode("relativeToSeaFloor"),
                KML.coordinates(
                    "146.825,12.233,400 "
                    "146.820,12.222,400 "
                    "146.812,12.212,400 "
                    "146.796,12.209,400 "
                    "146.788,12.205,400"
                ),
            ),
        )
    )
    kml_str = etree.tostring(kml)
    return HttpResponse(kml_str, content_type="application/vnd.google-earth.kml")
示例#5
0
    def test_basic_kml_document(self):
        """Tests the creation of a basic KML with Google Extensions ."""
        doc = KML.kml(
            GX.Tour(
                GX.Playlist(
                    GX.SoundCue(
                        KML.href('http://dev.keyhole.com/codesite/cntowerfacts.mp3')
                    ),
                    GX.Wait(
                        GX.duration(10)
                    ),
                    GX.FlyTo(
                        GX.duration(5),
                        GX.flyToMode('bounce'),
                        KML.LookAt(
                            KML.longitude(-79.387),
                            KML.latitude(43.643),
                            KML.altitude(0),
                            KML.heading(-172.3),
                            KML.tilt(10),
                            KML.range(1200),
                            KML.altitudeMode('relativeToGround'),
                        )
                    )
                )
            )
        )
        self.assertTrue(Schema('kml22gx.xsd').validate(doc))

        data = etree.tostring(doc, encoding='ascii')
        expected = \
            b'<kml xmlns:gx="http://www.google.com/kml/ext/2.2" ' \
            b'xmlns:atom="http://www.w3.org/2005/Atom" ' \
            b'xmlns="http://www.opengis.net/kml/2.2">' \
            b'<gx:Tour>' \
            b'<gx:Playlist>' \
            b'<gx:SoundCue>' \
            b'<href>http://dev.keyhole.com/codesite/cntowerfacts.mp3</href>' \
            b'</gx:SoundCue>' \
            b'<gx:Wait>' \
            b'<gx:duration>10</gx:duration>' \
            b'</gx:Wait>' \
            b'<gx:FlyTo>' \
            b'<gx:duration>5</gx:duration>' \
            b'<gx:flyToMode>bounce</gx:flyToMode>' \
            b'<LookAt>' \
            b'<longitude>-79.387</longitude>' \
            b'<latitude>43.643</latitude>' \
            b'<altitude>0</altitude>' \
            b'<heading>-172.3</heading>' \
            b'<tilt>10</tilt>' \
            b'<range>1200</range>' \
            b'<altitudeMode>relativeToGround</altitudeMode>' \
            b'</LookAt>' \
            b'</gx:FlyTo>' \
            b'</gx:Playlist>' \
            b'</gx:Tour>' \
            b'</kml>'

        self.assertXmlEquivalentOutputs(data, expected)
示例#6
0
def get_kml_doc(llhs):
  """Generates a KML document from a Pandas table of single point
  solutions. Requires columns lat, lon, and height.

  """
  from pykml.parser import Schema
  from pykml.factory import KML_ElementMaker as KML
  from pykml.factory import GX_ElementMaker as GX
  center = llhs[['lat', 'lon', 'height']].mean()
  elts = lambda e: '%s,%s,%d' % (e['lon'], e['lat'], e['height'])
  coords = ' '.join(llhs.apply(elts, axis=1).values)
  xml_coords = KML.coordinates(coords)
  doc = KML.kml(
          KML.Placemark(
            KML.name("gx:altitudeMode Example"),
            KML.LookAt(
              KML.longitude(center.lon),
              KML.latitude(center.lat),
              KML.heading(center.height),
              KML.tilt(70),
              KML.range(6300),
              GX.altitudeMode("relativeToSeaFloor"),),
            KML.LineString(
              KML.extrude(1),
              GX.altitudeMode("relativeToSeaFloor"),
              xml_coords
            )
          )
        )
  return doc
示例#7
0
 def get_track(self, model_url=None):
   track = GX.Track(id=self.track_id)
   track.append(GX.altitudeMode('absolute'))
   while self.has_next_packet():
     self.get_next_packet().append_telemetry_to(track)      
   #if model_url is not None:
   #  track.append(KML.Model(KML.Link(KML.href(model_url)), KML.Orientation(KML.heading(180))))
   return track
示例#8
0
 def generate_update(self, change=None, create=None, delete=None):
   placemark = GX.Placemark(targetId=self.pm_id)
   track = GX.Track(targetId=self.track_id)
   while self.has_next_packet():
     placemark.append(KML.description(self.get_description()))
     self.get_next_packet().append_telemetry_to(track)
   if placemark.countchildren() > 0:
     change.append(placemark)
   if track.countchildren() > 0:
     create.append(track)
示例#9
0
def init_kml(KMLname):
    # start with a base KML tour and playlist
    tour_doc = KML.kml(
        KML.Document(
          GX.Tour(
            KML.name(KMLname),
            GX.Playlist(),
    		),
        )
    )
    return tour_doc
示例#10
0
 def build_xml(self):
     track = GX.Track()
     for position in self.track.positions:
         track.append(
             KML.when(
                 "%s" %
                 (position.timestamp.strftime('%Y-%m-%dT%H:%M:%SZ'), )))
     for position in self.track.positions:
         track.append(
             GX.coord("%f %f %d" %
                      (float(position.lon) / 10000000,
                       float(position.lat) / 10000000, position.alt)))
     return track
示例#11
0
文件: task.py 项目: kant/pycondor
def task_to_kml_with_pykml(df_task, outdir, filename_base, disp):
    from lxml import etree
    from pykml.parser import Schema
    from pykml.factory import KML_ElementMaker as KML
    from pykml.factory import GX_ElementMaker as GX

    s_coords = task_to_string(df_task)
    (lat, lon) = calculate_center(df_task)

    #def turn_point_to_placemark(tp):
    #    placemark = KML.Placemark(
    #        KML.name(tp['Name']),
    #        KML.description(tp['Name']),
    #        KML.Point(
    #            KML.coordinates(tp['Lon'], tp['Lat'], tp['Altitude'])
    #        ),
    #    )
    #    return(placemark)
    #placemarks = [turn_point_to_placemark(tp) for i, tp in df_task.iterrows()]

    doc = KML.kml(
        KML.Placemark(
            KML.name("Condor task '%s'" % filename_base),
            KML.LookAt(
                KML.longitude(lon),
                KML.latitude(lat),
                KML.heading(0),
                KML.tilt(60),
                KML.range(80000),
                GX.altitudeMode("relativeToSeaFloor"),
                #GX.altitudeMode("absolute"),
            ),
            KML.LineString(
                KML.extrude(1),
                GX.altitudeMode("relativeToSeaFloor"),
                #GX.altitudeMode("absolute"),
                KML.coordinates(s_coords),
            ),
        ),
        #*placemarks
    )
    if disp:
        print(etree.tostring(doc, pretty_print=True))
    # output a KML file (named based on the Python script)
    filename_out = os.path.join(outdir, filename_base + '.kml')
    print("Output '%s'" % filename_out)
    outfile = file(filename_out, 'w')
    outfile.write(etree.tostring(doc, pretty_print=True))

    assert Schema('kml22gx.xsd').validate(doc)
示例#12
0
def task_to_kml_with_pykml(df_task, outdir, filename_base, disp):
    from lxml import etree
    from pykml.parser import Schema
    from pykml.factory import KML_ElementMaker as KML
    from pykml.factory import GX_ElementMaker as GX

    s_coords = task_to_string(df_task)    
    (lat, lon) = calculate_center(df_task)
    
    #def turn_point_to_placemark(tp):
    #    placemark = KML.Placemark(
    #        KML.name(tp['Name']),
    #        KML.description(tp['Name']),
    #        KML.Point(
    #            KML.coordinates(tp['Lon'], tp['Lat'], tp['Altitude'])
    #        ),
    #    )
    #    return(placemark)
    #placemarks = [turn_point_to_placemark(tp) for i, tp in df_task.iterrows()]

    doc = KML.kml(
        KML.Placemark(
            KML.name("Condor task '%s'" % filename_base),
            KML.LookAt(
                KML.longitude(lon),
                KML.latitude(lat),
                KML.heading(0),
                KML.tilt(60),
                KML.range(80000),
                GX.altitudeMode("relativeToSeaFloor"),
                #GX.altitudeMode("absolute"),
            ),
            KML.LineString(
                KML.extrude(1),
                GX.altitudeMode("relativeToSeaFloor"),
                #GX.altitudeMode("absolute"),
                KML.coordinates(s_coords),
            ),
        ),
        #*placemarks
    )
    if disp:
        print(etree.tostring(doc, pretty_print=True))
    # output a KML file (named based on the Python script)
    filename_out = os.path.join(outdir, filename_base + '.kml')
    print("Output '%s'" % filename_out)
    outfile = file(filename_out,'w')
    outfile.write(etree.tostring(doc, pretty_print=True))

    assert Schema('kml22gx.xsd').validate(doc)
示例#13
0
 def test_basic_kml_document(self):
     """Tests the creation of a basic KML with Google Extensions ."""
     doc = KML.kml(
         GX.Tour(
             GX.Playlist(
                 GX.SoundCue(
                     KML.href("http://dev.keyhole.com/codesite/cntowerfacts.mp3")
                 ),
                 GX.Wait(
                     GX.duration(10)
                 ),
                 GX.FlyTo(
                     GX.duration(5),
                     GX.flyToMode("bounce"),
                     KML.LookAt(
                         KML.longitude(-79.387),
                         KML.latitude(43.643),
                         KML.altitude(0),
                         KML.heading(-172.3),
                         KML.tilt(10),
                         KML.range(1200),
                         KML.altitudeMode("relativeToGround"),
                     )
                 )
             )
         )
     )
     self.assertTrue(Schema("kml22gx.xsd").validate(doc))
     self.assertEqual(
         etree.tostring(doc).decode(),
         '<kml '
              'xmlns:atom="http://www.w3.org/2005/Atom" '
              'xmlns:gx="http://www.google.com/kml/ext/2.2" '
              'xmlns="http://www.opengis.net/kml/2.2">'
           '<gx:Tour>'
             '<gx:Playlist>'
               '<gx:SoundCue>'
                 '<href>http://dev.keyhole.com/codesite/cntowerfacts.mp3</href>'
               '</gx:SoundCue>'
               '<gx:Wait>'
                 '<gx:duration>10</gx:duration>'
               '</gx:Wait>'
               '<gx:FlyTo>'
                 '<gx:duration>5</gx:duration>'
                 '<gx:flyToMode>bounce</gx:flyToMode>'
                 '<LookAt>'
                   '<longitude>-79.387</longitude>'
                   '<latitude>43.643</latitude>'
                   '<altitude>0</altitude>'
                   '<heading>-172.3</heading>'
                   '<tilt>10</tilt>'
                   '<range>1200</range>'
                   '<altitudeMode>relativeToGround</altitudeMode>'
                 '</LookAt>'
               '</gx:FlyTo>'
             '</gx:Playlist>'
           '</gx:Tour>'
         '</kml>'
     )
示例#14
0
    def makeplacemark(self):
        if self.__pointcount == 0:
            # We have no points since last placemark. Don't do anything.
            return

        if not self.__isstride:
            self.__coordstr += ' {},{},0 {},{},0'.format(
                self.__prevplacemarklng, self.__prevplacemarklat,
                self.__currlng, self.__currlat)

        placemark = KML.Placemark()
        geometry = KML.MultiGeometry(
            KML.LineString(KML.tessellate('1'),
                           GX.altitudeMode('clampToGround'),
                           KML.coordinates(self.__coordstr)))

        if self.__styletag is not None:
            placemark.append(KML.styleUrl('#' + str(self.__styletag)))

        placemark.append(geometry)

        if self.__startime is not None and self.__endtime is not None:
            placemark.append(_maketimespan(self.__startime, self.__endtime))

        self.__kmlcontainer.append(placemark)
        self.__coordstr = ''
        self.__pointcount = 0
        self.__prevplacemarklat = self.__currlat
        self.__prevplacemarklng = self.__currlng
示例#15
0
    def gen_kml(self):
        """
        Generate a KML file with keypoints on the locations of the pictures, including height
        :return:
        """
        style_dot = "sn_shaded_dot"
        style_path = "red_path"

        doc = KML.kml(
            KML.Document(
                KML.Name("GPS of the images"),
                KML.Style(
                    KML.IconStyle(
                        KML.scale(0.4),
                        KML.Icon(
                            KML.href(
                                "http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png"
                            )),
                    ),
                    id=style_dot,
                ),
                KML.Style(KML.LineStyle(
                    KML.color('7f0000ff'),
                    KML.width(6),
                    GX.labelVisibility('1'),
                ),
                          id=style_path)))

        # create points
        for i, gps in enumerate(self.tagged_gps):
            ii = i + 1
            doc.Document.append(
                KML.Placemark(
                    KML.styleUrl('#{0}'.format(style_dot)),
                    KML.Point(
                        KML.extrude(True), KML.altitudeMode('absolute'),
                        KML.coordinates("{},{},{}".format(
                            gps.lon, gps.lat, gps.alt))),
                    KML.name(str(ii))
                    if ii % 5 == 0 or ii == 1 else KML.name()))

        # create the path
        doc.Document.append(
            KML.Placemark(
                KML.styleUrl('#{0}'.format(style_path)),
                KML.LineString(
                    KML.altitudeMode('absolute'),
                    KML.coordinates(' '.join([
                        "{},{},{}".format(gps.lon, gps.lat, gps.alt)
                        for gps in self.tagged_gps
                    ])))))

        s = etree.tostring(doc)

        file_path = self.output + 'GoogleEarth_points.kml'
        f = open(file_path, 'w')
        f.write(s)
        f.close()

        print '[INFO] KML file generated on:', file_path
示例#16
0
 def writecoord(self):
     fea_list = self.loadjson(self.path)['features']
     num = 1
     for i in fea_list:
         coorlist = i['geometry'][
             'coordinates']  #[[8.4882786, 49.9307422], [8.4879952, 49.930298], [8.4878599, 49.9300566]]
         coord_str = ''
         for cood in coorlist:
             if isinstance(cood, list):
                 coord_str += str(cood[0]) + ',' + str(cood[1]) + ',0 '
             else:
                 pass
         lookat = KML.Placemark(
             KML.name(num),
             KML.LookAt(KML.longitude(cood[0]), KML.latitude(cood[1]),
                        KML.heading('-60'), KML.tilt('8.3'),
                        KML.range('500')),
             KML.styleUrl('coolor1'),
             KML.Point(
                 GX.drawOrder('1'),
                 KML.coordinates(str(cood[0]) + ',' + str(cood[1]) + ',0 '),
             ),
         )
         place = KML.Placemark(
             KML.name(num), KML.styleUrl('#type1'), KML.visibility('1'),
             KML.description(''),
             KML.LineString(KML.extrude('1'), KML.coordinates(coord_str)))
         self.fld.append(place), self.fld.append(lookat)
         num += 1
     with open('./new.kml', 'w') as f:
         f.write(etree.tostring(self.fld, pretty_print=True))
示例#17
0
def create_flyto_camera(location):

    flyto = GX.FlyTo(
        GX.duration(0.5),
        GX.flyToMode('smooth'),
    )
    flyto.append(
        KML.Camera(
            KML.longitude(location['loc'].longitude),
            KML.latitude(location['loc'].latitude),
            KML.altitude(location['loc'].altitude),
            KML.heading(location['loc'].heading),
            KML.tilt(location['loc'].tilt),
            KML.roll(location['loc'].roll),
            KML.altitudeMode('relativeToGround'),
        ))
    return flyto
示例#18
0
def constructKML(urls, course_name):
    """
	Create KML files given the urls and the course names. 
	"""
    doc = GX.kml()
    for url in urls:
        # print url #see if it prints urls
        name = url.split('/')[-1]
        point = points_dict.get(url)
        if point:
            langt, longt = point.strip('POINT()').split(' ')
            pm = GX.Placemark(GX.name(name),
                              GX.Point(GX.coordinates(langt + ',' + longt)))
            doc.append(pm)
    xml = lxml.etree.tostring(doc, pretty_print=True, xml_declaration=True)
    with open(OUTPUT_FOLDER + course_name + '.kml', 'w') as f:
        f.write(xml)
示例#19
0
def create_flyto_camera(location):
    
    flyto = GX.FlyTo(
        GX.duration(0.5),
        GX.flyToMode('smooth'),
    )
    flyto.append(
        KML.Camera(
            KML.longitude(location['loc'].longitude),
            KML.latitude(location['loc'].latitude),
            KML.altitude(location['loc'].altitude),
            KML.heading(location['loc'].heading),
            KML.tilt(location['loc'].tilt),
            KML.roll(location['loc'].roll),
            KML.altitudeMode('relativeToGround'),
        )
    )
    return flyto
示例#20
0
    def find_to_stand_over_the_placemark(self, duration, longitude, latitude, kml_doc):
        # rota fins estar a sobre de la ciutat i apropar-se
        kml_doc.Document[gxns + "Tour"].Playlist.append(
            GX.FlyTo(
                GX.duration(duration),
                GX.flyToMode("smooth"),
                KML.LookAt(
                    KML.longitude(longitude),
                    KML.latitude(latitude),
                    KML.altitude(0),
                    KML.heading(0),
                    KML.tilt(0),
                    KML.range(self.range),
                    KML.altitudeMode("relativeToGround"),
                )
            ),
        )

        return kml_doc
示例#21
0
    def get_away_from_placemark(self, data, kml_doc):
        # fly to a space viewpoint. Allunyar-se de la ciutat per buscar el seguent punt
        kml_doc.Document[gxns + "Tour"].Playlist.append(
            GX.FlyTo(
                GX.duration(8.0),
                GX.flyToMode("bounce"),
                KML.LookAt(
                    KML.longitude(float(data.longitude)),
                    KML.latitude(float(data.latitude)),
                    KML.altitude(0),
                    KML.heading(0),
                    KML.tilt(0),
                    KML.range(self.range),
                    KML.altitudeMode("relativeToGround"),
                )
            ),
        )

        return kml_doc
示例#22
0
 def SetView(self, lat=0.0, lon=0.0, heading=0.0, tilt=0.0, view_range=0.0):
     look_at_ = KML.LookAt(
         KML.longitude(lon),
         KML.latitude(lat),
         KML.heading(heading),
         KML.tilt(tilt),
         KML.range(view_range),
         GX.altitudeMode('absolute'),
     )
     self.KmlDoc.Document.append(look_at_)
示例#23
0
def constructKML(urls, course_name):
	"""
	Create KML files given the urls and the course names. 
	"""
	doc = GX.kml()
	for url in urls:
		# print url #see if it prints urls 
		name = url.split('/')[-1]
		point = points_dict.get(url)
		if point:
			langt, longt = point.strip('POINT()').split(' ')
			pm = GX.Placemark(
				GX.name(name),
				GX.Point(
					GX.coordinates(langt + ',' + longt))
				)
			doc.append(pm)
	xml = lxml.etree.tostring(doc, pretty_print=True, xml_declaration=True)
	with open(OUTPUT_FOLDER+course_name+'.kml', 'w') as f:
		f.write(xml)
示例#24
0
def addsegment(kmlcontainer, styletag, lata, lnga, latb, lngb, name='segment'):
    coordstr = ' {},{},0 {},{},0'.format(lnga, lata, lngb, latb)

    placemark = KML.Placemark(
        KML.styleUrl('#' + str(styletag)), KML.name(name),
        KML.MultiGeometry(
            KML.LineString(KML.tessellate('1'),
                           GX.altitudeMode('clampToGround'),
                           KML.coordinates(coordstr))))

    kmlcontainer.append(placemark)
示例#25
0
    def fly_to_the_placemark(self, longitude, latitude, params, mode, kml_doc):
        # fly to the data
        kml_doc.Document[gxns + "Tour"].Playlist.append(
            GX.FlyTo(
                GX.duration(params[0]),
                GX.flyToMode(mode),
                KML.LookAt(
                    KML.longitude(longitude),
                    KML.latitude(latitude),
                    KML.altitude(params[1]),
                    KML.heading(params[2]),
                    KML.tilt(params[3]),
                    KML.name(params[4].upper()),
                    KML.range(params[5]),
                    KML.altitudeMode("relativeToGround"),
                )
            ),
        )

        return kml_doc
示例#26
0
    def generateKML_Line_Track_Experience (self,data_points):
        linetrack_experience_kml_doc = self.KML_file_header(["",""],"Line Track Experience")

        longitude = str(data_points[0]).split(",")[0].split("['")[1]
        latitude = str(data_points[0]).split(",")[1].split("']")[0]
        linetrack_experience_kml_doc = self.find_to_stand_over_the_placemark(2.0,longitude,latitude,linetrack_experience_kml_doc)

        i = 0
        while i < len(data_points)-1:
            data_list = []
            data_list.append(str(data_points[i]).split(",")[0].split("['")[1])
            data_list.append(str(data_points[i]).split(",")[1].split("']")[0])
            data_list.append(str(data_points[i+1]).split(",")[0].split("['")[1])
            data_list.append(str(data_points[i+1]).split(",")[1].split("']")[0])
            iid = str((i+1))
            linetrack_experience_kml_doc = self.add_placemark_simple_line(data_list,iid,linetrack_experience_kml_doc)

            i = i+1

        i = 0
        while i < len(data_points)-1:
            linetrack_experience_kml_doc.Document[gxns + "Tour"].Playlist.append(GX.Wait(GX.duration(0.06)))

            linetrack_experience_kml_doc.Document[gxns + "Tour"].Playlist.append(
                GX.AnimatedUpdate(
                    KML.Update(
                        KML.Change(
                            KML.Placemark(
                                KML.visibility(1),
                                targetId=str((i+1)),
                            )
                        )
                    )
                )
            )

            i = i+1

        return self.save_kml_file(self.kml_name, linetrack_experience_kml_doc)
示例#27
0
 def build_xml(self):
     track = GX.Track(
     )
     for position in self.track.positions:
         track.append(KML.when("%s" % (
                 position.timestamp.strftime('%Y-%m-%dT%H:%M:%SZ'),)
         ))
     for position in self.track.positions:
         track.append(GX.coord("%f %f %d" % (
                             float(position.lon)/10000000,
                             float(position.lat)/10000000,
                             position.alt))
         )
     return track
示例#28
0
def addboundingbox(kmlcontainer, styletag, nelat, nelng, swlat, swlng):
    coordstr = ' {},{},0'.format(nelng, nelat)
    coordstr += ' {},{},0'.format(nelng, swlat)
    coordstr += ' {},{},0'.format(swlng, swlat)
    coordstr += ' {},{},0'.format(swlng, nelat)
    coordstr += ' {},{},0'.format(nelng, nelat)

    placemark = KML.Placemark(
        KML.styleUrl('#' + str(styletag)),
        KML.Polygon(
            KML.tessellate('1'), GX.altitudeMode('clampToGround'),
            KML.outerBoundaryIs(KML.LinearRing(KML.coordinates(coordstr)))))

    kmlcontainer.append(placemark)
def compute_kml_point_description(coord, name):
    coords_str = " " + ",".join(str(num) for num in coord) + " "
    description = KML.Placemark(
        KML.name(name),
        KML.Point(
            # https://developers.google.com/kml/documentation/altitudemode
            # possible values:
            #   from the surface of the Earth(relativeToGround)
            #   above sea level(absolute)
            #   from the bottom of major bodies of water (relativeToSeaFloor)
            GX.altitudeMode("absolute"),
            KML.coordinates(coords_str),
        ),
    )
    return description
示例#30
0
文件: ge_game.py 项目: initze/GE_game
 def make_kml(self, lon, lat):
     """
     :return: write kml file from defined properties
     """
     doc = KML.kml(
     etree.Comment(' required when using gx-prefixed elements '),
     GX.FlyTo(
     GX.flyToMode('bounce'),
     GX.duration('0.5')
     ),
     KML.Placemark(
     KML.name('gx:altitudeMode Example'),
     KML.Camera(
       KML.altitude(self.vh),
       KML.longitude(str(lon)),
       KML.latitude(str(lat))
     ),
     ),
     )
     string = etree.tostring(etree.ElementTree(doc),pretty_print=True)
     #writeToFile
     f = open(self.outfile, 'w')
     f.writelines(string)
     f.close()
示例#31
0
def addpolygon(kmlcontainer, styletag, coordlist, name='polygon'):
    coordstr = ''
    first = None

    for coord in coordlist:
        if first is None:
            first = coord

        coordstr += ' {},{},0'.format(coord.lon, coord.lat)

    coordstr += ' {},{},0'.format(first.lon, first.lat)

    placemark = KML.Placemark(
        KML.name(name), KML.styleUrl('#' + str(styletag)),
        KML.Polygon(
            KML.tessellate('1'), GX.altitudeMode('clampToGround'),
            KML.outerBoundaryIs(KML.LinearRing(KML.coordinates(coordstr)))))

    kmlcontainer.append(placemark)
def compute_kml_line_3d_description(coord_list, name):

    coord_str_list = [" "]
    for coord in coord_list:
        coords_str = ",".join(str(num) for num in coord) + " "
        coord_str_list.append(coords_str)

    description = KML.Placemark(
        KML.name(name),
        KML.LineString(
            # https://developers.google.com/kml/documentation/altitudemode
            # possible values:
            #   from the surface of the Earth(relativeToGround)
            #   above sea level(absolute)
            #   from the bottom of major bodies of water (relativeToSeaFloor)
            GX.altitudeMode("absolute"),
            KML.coordinates(*coord_str_list),
        ),
    )
    return description
示例#33
0
def append_linestring(timeDiff, dist, normalized, thisStyle, row):
	doc.append(
		KML.Placemark(
			KML.name("Point " + str(count/lineReduceNumBy)),
			KML.ExtendedData(
				KML.Data(KML.value(timeDiff), name="Time Length"),
				KML.Data(KML.value(dist), name="Distance Metres"),
				KML.Data(KML.value(dist/timeDiff.seconds), name="Average Speed m/s"),
				KML.Data(KML.value(normalized), name="Normalized Speed"),
			),
			KML.styleUrl("#{}".format(thisStyle)),
			KML.LineString(
				KML.extrude('1'),
				GX.altitudeMode('relative'),
				KML.coordinates(
					previousPoint,
					"{},{},{}".format(row['LOCATION Longitude : '],row['LOCATION Latitude : '],0)
				)						
			)

		))
示例#34
0
def addsegments(kmlcontainer, styletag, points, stride=50):
    pointiter = iter(points)

    try:
        initialpoint = next(pointiter)
    except StopIteration:
        raise ValueError('Number of points is 0')

    nsegmentsadded = 0
    currlat = initialpoint[0]
    currlng = initialpoint[1]
    coordstr = ''

    for i, point in enumerate(pointiter):
        if (i + 1) % stride != 0:
            continue

        nextlat = point[0]
        nextlng = point[1]

        coordstr += ' {},{},0 {},{},0'.format(currlng, currlat, nextlng,
                                              nextlat)

        currlat = nextlat
        currlng = nextlng

        nsegmentsadded += 1

    if nsegmentsadded == 0:
        coordstr += ' {},{},0 {},{},0'.format(initialpoint[1], initialpoint[0],
                                              currlng, currlat)

    placemark = KML.Placemark(
        KML.styleUrl('#' + str(styletag)),
        KML.MultiGeometry(
            KML.LineString(KML.tessellate('1'),
                           GX.altitudeMode('clampToGround'),
                           KML.coordinates(coordstr))))

    kmlcontainer.append(placemark)
示例#35
0
    def show_placemark_balloon(self, duration, target, kml_doc):
        # show the placemark balloon

        kml_doc.Document[gxns + "Tour"].Playlist.append(
            GX.AnimatedUpdate(
                GX.duration(1.0),
                KML.Update(
                    KML.targetHref(),
                    KML.Change(
                        KML.Placemark(
                            KML.visibility(1),
                            GX.balloonVisibility(1),
                            targetId=target.replace(' ', '_')
                        )
                    )
                )
            )
        )

        kml_doc.Document[gxns + "Tour"].Playlist.append(GX.Wait(GX.duration(duration)))

        kml_doc.Document[gxns + "Tour"].Playlist.append(
            GX.AnimatedUpdate(
                GX.duration(0.5),
                KML.Update(
                    KML.targetHref(),
                    KML.Change(
                        KML.Placemark(
                            GX.balloonVisibility(0),
                            targetId=target.replace(' ', '_')
                        )
                    )
                )
            )
        )

        return kml_doc
示例#36
0
def output_data_to_file(road_data):
    stylename = 'blueLine'
    doc = KML.kml(
        KML.Document(
            KML.Name("yan an"),
            KML.Style(KML.LineStyle(KML.color('FFF00014'), KML.width('5.0')),
                      id=stylename)))

    for road in road_data:
        pm = KML.Placemark(
            KML.name(road.road_id), KML.styleUrl('#{0}'.format(stylename)),
            KML.LineString(
                KML.extrude(0), GX.altitudeMode("absolute"),
                KML.coordinates(' '.join([
                    turn_3857_project_to_4326(p)
                    for p in road.points_with_z_value_list
                ]))))
        doc.Document.append(pm)

    f = open("model/test_yan_an4.kml", 'w')
    f.write(str(etree.tostring(doc)))
    f.close()
示例#37
0
def addcircle(kmlcontainer,
              styletag,
              node,
              radius,
              name='circle',
              nsegments=50):
    if nsegments < 3:
        raise ValueError('Circle must be made up of 3 or more segments.')

    arclength = 360.0 / float(nsegments)
    currdegree = 0.0
    currnode = None
    coordstr = ''
    firstnode = None

    for i in range(nsegments):
        nextnode = node.destinationnode(currdegree, radius)

        if currnode is not None:
            coordstr += ' {},{},0 {},{},0'.format(currnode.lon, currnode.lat,
                                                  nextnode.lon, nextnode.lat)
        else:
            firstnode = nextnode

        currnode = nextnode
        currdegree += arclength

    if firstnode is not None:
        coordstr += ' {},{},0 {},{},0'.format(currnode.lon, currnode.lat,
                                              firstnode.lon, firstnode.lat)

    placemark = KML.Placemark(
        KML.styleUrl('#' + str(styletag)), KML.name(name),
        KML.Polygon(
            KML.tessellate('1'), GX.altitudeMode('clampToGround'),
            KML.outerBoundaryIs(KML.LinearRing(KML.coordinates(coordstr)))))

    kmlcontainer.append(placemark)
示例#38
0
        GX.Playlist(),
    )
)

with open("colorado_river_linestring.kml", 'rb') as f:
    linestring_doc = parse(f)

# get the coordinate string of the first KML coordinate element
coord_str = str(
    linestring_doc.getroot().find(".//{http://www.opengis.net/kml/2.2}coordinates")
).strip()

for vertex in coord_str.split(' '):
    (lon, lat, alt) = vertex.split(',')
    flyto = GX.FlyTo(
        GX.duration(2),
        GX.flyToMode("smooth"),
        KML.Camera(
            KML.longitude(lon),
            KML.latitude(lat),
            KML.altitude(0),
            KML.heading(-129.7),
            KML.tilt(90.0),
            KML.altitudeMode("relativeToGround"),
        )
    )
    tour_doc[gxns + "Tour"].Playlist.append(flyto)

assert Schema('kml22gx.xsd').validate(tour_doc)
print(etree.tostring(tour_doc, pretty_print=True))
示例#39
0
from lxml import etree
from pykml.parser import Schema
from pykml.factory import KML_ElementMaker as KML
from pykml.factory import GX_ElementMaker as GX

doc = KML.kml(
    KML.Placemark(
        KML.name("gx:altitudeMode Example"),
        KML.LookAt(
            KML.longitude(146.806),
            KML.latitude(12.219),
            KML.heading(-60),
            KML.tilt(70),
            KML.range(6300),
            GX.altitudeMode("relativeToSeaFloor"),
        ),
        KML.LineString(
            KML.extrude(1),
            GX.altitudeMode("relativeToSeaFloor"),
            KML.coordinates(
              "146.825,12.233,400 "
              "146.820,12.222,400 "
              "146.812,12.212,400 "
              "146.796,12.209,400 "
              "146.788,12.205,400"
            )
        )
    )
)
示例#40
0
    def gen_klm(self):
        """
        Generate a KML file with keypoints on the locations of the pictures, including height
        :return:
        """
        style_dot = "sn_shaded_dot"
        style_path = "red_path"

        doc = KML.kml(
            KML.Document(
                KML.Name("GPS of the images"),
                KML.Style(
                    KML.IconStyle(
                        KML.scale(0.4),
                        KML.Icon(
                            KML.href("http://maps.google.com/mapfiles/kml/shapes/shaded_dot.png")
                        ),
                    ),
                    id=style_dot,
                ),
                KML.Style(
                    KML.LineStyle(
                        KML.color('7f0000ff'),
                        KML.width(6),
                        GX.labelVisibility('1'),
                    ),
                    id=style_path
                )   
            )
        )

        # create points
        for i, gps in enumerate(self.tagged_gps):
                ii = i + 1
                doc.Document.append(
                    KML.Placemark(
                        KML.styleUrl('#{0}'.format(style_dot)),
                        KML.Point(
                            KML.extrude(True),
                            KML.altitudeMode('relativeToGround'),
                            KML.coordinates("{},{},{}".format(gps.lon, gps.lat, gps.alt))
                        ),
                        KML.name(str(ii)) if ii % 5 == 0 or ii == 1 else KML.name()
                    )
                )

        # create the path
        doc.Document.append(
            KML.Placemark(
                KML.styleUrl('#{0}'.format(style_path)),
                KML.LineString(
                    KML.altitudeMode('relativeToGround'),
                    KML.coordinates(
                        ' '.join(["{},{},{}".format(gps.lon, gps.lat, gps.alt) for gps in self.tagged_gps])
                    )
                )
            )
        )

        s = etree.tostring(doc)

        file_path = self.output + 'GoogleEarth_points.kml'
        f = open(file_path,'w')
        f.write(s)
        f.close()

        print '[INFO] KML file generated on:', file_path
示例#41
0
    def __tour__(self):
        # Define a variable for the Google Extensions namespace URL string
        gxns = '{' + nsmap['gx'] + '}'

        tour = GX.Tour(KML.name('Play me!'), GX.Playlist())

        tour.Playlist.append(
            GX.FlyTo(
            GX.duration(5),
            GX.flyToMode('smooth'),
            KML.LookAt(
                KML.longitude(-45),
                KML.latitude(-43),
                KML.altitude(0),
                KML.heading(355),
                KML.tilt(55),
                KML.range(6000000.0),
                KML.altitudeMode('absolute'))))

        tour.Playlist.append(
            GX.FlyTo(
            GX.duration(10),
            GX.flyToMode('smooth'),
            KML.LookAt(
                KML.longitude(-80),
                KML.latitude(63),
                KML.altitude(0),
                KML.heading(345),
                KML.tilt(45),
                KML.range(10000000.0),
                KML.altitudeMode('absolute'))))

        tour.Playlist.append(
            GX.FlyTo(
            GX.duration(10),
            GX.flyToMode('smooth'),
            KML.LookAt(
                KML.longitude(-131),
                KML.latitude(63),
                KML.altitude(0),
                KML.heading(345),
                KML.tilt(35),
                KML.range(20000000.0),
                KML.altitudeMode('absolute'))))

        tour.Playlist.append(
            GX.FlyTo(
            GX.duration(5),
            GX.flyToMode('smooth'),
            KML.LookAt(
                KML.longitude(53),
                KML.latitude(25),
                KML.altitude(0),
                KML.heading(270),
                KML.tilt(35),
                KML.range(20000000.0),
                KML.altitudeMode('absolute'))))

        tour.Playlist.append(
            GX.FlyTo(
            GX.duration(10),
            GX.flyToMode('smooth'),
            KML.LookAt(
                KML.longitude(140),
                KML.latitude(-4),
                KML.altitude(0),
                KML.heading(0),
                KML.tilt(55),
                KML.range(10000000.0),
                KML.altitudeMode('absolute'))))

        return tour
示例#42
0
    def read_track_from_gpx(self, 
                            filepath, 
                            filebase, 
                            trackfolder,
                            colourIndex):
        """
        Read a single GPX file and extract the track(s), converting them to a 
        list of KML tracks.  Append or replace each track in the trackfolder.
        This fills the trackfolder in makekml.
        
        Arguments:
        filepath: the full path to the GPX file
        filebase: the basename of the GPX file, used to name the KML tracks
        trackfolder: a KML.Folder to hold track Placemarks
        colourIndex: the next colourIndex to use when creating a linestyle
        
        On successful exit, trackfolder and colourIndex will have been updated.
        """
        args = self.config['arguments']
        gpxtree = etree.parse(filepath).getroot()        
        namespace = gpxtree.nsmap[None]
        if self.verbosity > 1:
            print('namespace for ' + filepath + ': ' + namespace, 
                  file=sys.stderr)
        
        print('{%s}trk' % namespace, file=sys.stderr)
        print(namespace + 'trk', file=sys.stderr)
        for gpxtrack in gpxtree.getiterator('{%s}trk' % namespace):
            print('got here', file=sys.stderr)
            # Extract the track name from the GPX track
            try:
                trackname = gpxtrack.find('{%s}name' % namespace).text
            except:
                print('track does not have name in ' + filepath, 
                      file=sys.stderr)
                trackname = filebase
            print('trackname = ' + trackname, file=sys.stderr)

            # does a Placemark already exist with this name?
            placemark = None
            for pm in trackfolder.findall('GX.Placemark'):
                if pm.find('KML.name').text == trackname:
                    placemark = pm
                    break
            if 'replace' in args and args['replace']:
                trackfolder.drop(placemark)
                placemark = None
            
            if not placemark:
                # Create a new Placemark to hold the KML track(s)
                colourID = '#colour' + str(self.colourIndex)
                self.colourIndex = (self.colourIndex + 1) % self.colourSetLen

                placemark = KML.Placemark(
                    KML.visibility('1'),
                    KML.name(trackname),
                    KML.description(trackname + ' from ' + filebase),
                    KML.styleUrl(colourID)
                    )
                trackfolder.append(placemark)

                tracklist = []
                for gpxtrkseg in gpxtrack.getiterator('{%s}trkseg' % namespace):
                    # A GPX trkseg translates into aGX.track
                    kmltrack = GX.Track(
                        KML.altitudeMode('clampToGround')
                        )
                    whenlist = []
                    coordlist = []
                    for gpxtrkpoint in gpxtrkseg:
                        lat = gpxtrkpoint.attrib['lat']
                        lon = gpxtrkpoint.attrib['lon']
                        alt = gpxtrkpoint.find('{%s}ele'% namespace).text
                        time = gpxtrkpoint.find('{%s}time'% namespace).text
                        
                        whenlist.append(GX.when(time))
                        coordlist.append(GX.coord('{0} {1} {2}'.format(lon, 
                                                                       lat, 
                                                                       alt)))
                    for w in whenlist:
                        kmltrack.append(w)
                    for c in coordlist:
                        kmltrack.append(c)
                    tracklist.append(kmltrack)
                
                if tracklist:
                    if len(tracklist) > 1:
                        multitrack = GX.MultiTrack()
                        for t in tracklist:
                            multitrack.append(t)
                        placemark.append(multitrack)
                    else:
                        placemark.append(tracklist[0])
                else:
                    print('no tracks found in ' + filepath, file=sys.stderr)
示例#43
0
   ),
   id="pushpin"
 ),
 KML.Placemark(
   KML.name("Pin on a mountaintop"),
   KML.styleUrl("#pushpin"),
   KML.Point(
     KML.coordinates(170.1435558771009,-43.60505741890396,0)
   ),
   id="mountainpin1"
 ),
 GX.Tour(
   KML.name("Play me!"),
   GX.Playlist(
     GX.FlyTo(
       GX.duration(3),
       GX.flyToMode("bounce"),
       KML.Camera(
         KML.longitude(170.157),
         KML.latitude(-43.671),
         KML.altitude(9700),
         KML.heading(-6.333),
         KML.tilt(33.5),
       )
     ),
     GX.AnimatedUpdate(
       GX.duration(5),
       KML.Update(
         KML.targetHref(),
         KML.Change(
           KML.IconStyle(
示例#44
0
route = json.loads( urllib2.urlopen(URL).read() )

pList = ''
for point in route:
    pList = pList + str(point['lon']) + ',' + str(point['lat']) +',1,'

pm = KML.Placemark(
    KML.name('Curiosity traversal'),
    KML.LookAt(
        KML.longitude(route[0]['lon']),
        KML.latitude(route[0]['lat']),
        KML.heading('0'),
        KML.tilt('40'),
        KML.range('2000'),
        GX.altitudeMode('relativeToSeaFloor'),
        ),
    KML.LineStyle(
        KML.color('#00FFFF'),
        KML.width(10)
    ),
    KML.altitudeMode('clampToGround'),
    KML.LineString(KML.extrude('1'), GX.altitudeMode('relativeToSeaFloor'), KML.coordinates(pList))
    )

folder = KML.Folder()
folder.append(pm)

# create a document element with a single label style
kmlobj = KML.kml(
    KML.Document(
        GX.Tour(
            KML.name("Play me!"),
            GX.Playlist(),
        ),
        KML.Folder(
            KML.name('Features'),
            id='features',
        ),
    )
)
for feature in feature_list:
    # import ipdb; ipdb.set_trace()
    # fly to a space viewpoint
    tour_doc.Document[gxns + "Tour"].Playlist.append(
        GX.FlyTo(
            GX.duration(5),
            GX.flyToMode("smooth"),
            KML.LookAt(
                KML.longitude(feature['lon']),
                KML.latitude(feature['lat']),
                KML.altitude(0),
                KML.heading(0),
                KML.tilt(0),
                KML.range(10000000.0),
                KML.altitudeMode("relativeToGround"),
            )
        ),
    )
    # fly to the feature
    tour_doc.Document[gxns + "Tour"].Playlist.append(
        GX.FlyTo(
示例#46
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()
示例#47
0
文件: mapper.py 项目: FranMcG/mapper
def create_kml_tour(addresses, filename):
    '''
    Creates a kml tour of the sites
    Modified from pykml example here https://pythonhosted.org/pykml/examples/tour_examples.html
    python
    Generate a KML document of a tour based on rotating around locations.
    '''
    tilt = 20
    distance = 20

    # define a variable for the Google Extensions namespace URL string
    gxns = '{' + nsmap['gx'] + '}'

    # start with a base KML tour and playlist
    tour_doc = KML.kml(
        KML.Document(
          GX.Tour(
            KML.name("Play me!"),
            GX.Playlist(),
          ),
          KML.Folder(
            KML.name('Sites'),
            id='sites',
          ),
        )
    )

    for address in addresses:
        #import ipdb; ipdb.set_trace()
        # fly to a space viewpoint
        tour_doc.Document[gxns+"Tour"].Playlist.append(
          GX.FlyTo(
            GX.duration(5),
            GX.flyToMode("smooth"),
            KML.LookAt(
              KML.longitude(address['longitude']),
              KML.latitude(address['latitude']),
              KML.altitude(0),
              KML.heading(0),
              KML.tilt(0),
              KML.range(10000000.0),
              KML.altitudeMode("relativeToGround"),
            )
          ),
        )
        # fly to the address
        tilt = tilt + 10
        distance = distance + 10
        tour_doc.Document[gxns+"Tour"].Playlist.append(
          GX.FlyTo(
            GX.duration(0.25),
            GX.flyToMode("smooth"),
            KML.LookAt(
              KML.longitude(address['longitude']),
              KML.latitude(address['latitude']),
              KML.altitude(0),
              KML.heading(0),
##              KML.tilt(address['tilt']),
##              KML.range(address['range']),
              KML.tilt(tilt),
              KML.range(distance),
              KML.altitudeMode("relativeToGround"),
            )
          ),
        )
        
        # add a placemark for the address
        tour_doc.Document.Folder.append(
          KML.Placemark(
            KML.name("?"),
            KML.description(
                "<h1>{name}</h1><br/>{desc}".format(
                        name=address['Site'],
                        desc=address['Bandwidth'],
                )
            ),
            KML.Point(
              KML.extrude(1),
              KML.altitudeMode("relativeToGround"),
              KML.coordinates("{lon},{lat},{alt}".format(
                      lon=address['longitude'],
                      lat=address['latitude'],
                      alt=50,
                  )
              )
            ),
            id=address['Site'].replace(' ','_')
          )
        )
        # show the placemark balloon
        tour_doc.Document[gxns+"Tour"].Playlist.append(
            GX.AnimatedUpdate(
              GX.duration(2.0),
              KML.Update(
                KML.targetHref(),
                KML.Change(
                  KML.Placemark(
                    KML.visibility(1),
                    GX.balloonVisibility(1),
                    targetId=address['Site'].replace(' ','_')
                  )
                )
              )
            )
        )

        tour_doc.Document[gxns+"Tour"].Playlist.append(GX.Wait(GX.duration(2.0)))

        tour_doc.Document[gxns+"Tour"].Playlist.append(
            GX.AnimatedUpdate(
              GX.duration(2.0),
              KML.Update(
                KML.targetHref(),
                KML.Change(
                  KML.Placemark(
                    GX.balloonVisibility(0),
                    targetId=address['Site'].replace(' ','_')
                  )
                )
              )
            )
        )
        
        
        # spin around the address
        for aspect in range(0,360,10):

            tour_doc.Document[gxns+"Tour"].Playlist.append(
                GX.FlyTo(
                    GX.duration(0.25),
                    GX.flyToMode("smooth"),
                        KML.LookAt(
                              KML.longitude(address['longitude']),
                              KML.latitude(address['latitude']),
                              KML.altitude(0),
                              KML.heading(aspect),
                              KML.tilt(tilt),
                              KML.range(distance),
                              KML.altitudeMode("relativeToGround"),
                        )
                    )
            )

        for angle in range(0,360,10):
            tour_doc.Document[gxns+"Tour"].Playlist.append(
              GX.FlyTo(
                GX.duration(0.25),
                GX.flyToMode("smooth"),
                KML.LookAt(
                  KML.longitude(address['longitude']),
                  KML.latitude(address['latitude']),
                  KML.altitude(0),
                  KML.heading(angle),
##                  KML.tilt(address['tilt']),
##                  KML.range(address['range']),
                  KML.tilt(tilt),
                  KML.range(distance),
                  KML.altitudeMode("relativeToGround"),
                )
              )
            )

        tour_doc.Document[gxns+"Tour"].Playlist.append(GX.Wait(GX.duration(1.0)))

    #    tour_doc.Document[gxns+"Tour"].Playlist.append(
    #        GX.TourControl(GX.playMode("pause"))
    #    )

        # fly to a space viewpoint
        tour_doc.Document[gxns+"Tour"].Playlist.append(
          GX.FlyTo(
            GX.duration(5),
            GX.flyToMode("bounce"),
            KML.LookAt(
              KML.longitude(address['longitude']),
              KML.latitude(address['latitude']),
              KML.altitude(0),
              KML.heading(0),
              KML.tilt(0),
              KML.range(10000000.0),
              KML.altitudeMode("relativeToGround"),
            )
          ),
        )

    # check that the KML document is valid using the Google Extension XML Schema
    #assert(Schema("kml22gx.xsd").validate(tour_doc))
    #always bombs
#    print etree.tostring(tour_doc, pretty_print=True)

    # output a KML file (named based on the Python script)
    outfile = kmlfile + '_tour.kml'
    with open(outfile,'w') as file:
        file.write(etree.tostring(tour_doc, pretty_print=True))

    return
示例#48
0
 def append_telemetry_to(self, element):
   #if self.has_timestamp():
   #  element.append(KML.when(self.get_nice_timestamp()))
   if self.has_position():
     if self.packet.position[2] != 110001:
       element.append(GX.coord(self.get_nice_position()))
示例#49
0
    def makeFile(self):


        # define a variable for the Google Extensions namespace URL string
        gxns = '{' + nsmap['gx'] + '}'

        stylename = "sn_shaded_dot"
        # start with a base KML tour and playlist
        tour_doc = KML.kml(
            KML.Document(
                GX.Tour(
                    KML.name("Play me!"),
                    GX.Playlist(),
                ),
                KML.Folder(
                    KML.name('Features'),
                    id='features',
                ),
                KML.Style(
                    KML.IconStyle(
                        KML.scale(1.2),
                        KML.Icon(
                            KML.href(self.icon)
                        ),
                    ),
                    id=stylename,
                )
            )
        )
        for data in self.data_set:
            # import ipdb; ipdb.set_trace()
            # fly to a space viewpoint
            tour_doc.Document[gxns + "Tour"].Playlist.append(
                GX.FlyTo(
                    GX.duration(5),
                    GX.flyToMode("smooth"),
                    KML.LookAt(
                        KML.longitude(float(data['coordinates']['lng'])),
                        KML.latitude(float(data['coordinates']['lat'])),
                        KML.altitude(0),
                        KML.heading(0),
                        KML.tilt(0),
                        KML.range(10000000.0),
                        KML.altitudeMode("relativeToGround"),
                    )
                ),
            )
            # fly to the data
            tour_doc.Document[gxns + "Tour"].Playlist.append(
                GX.FlyTo(
                    GX.duration(5),
                    GX.flyToMode("bounce"),
                    KML.LookAt(
                        KML.longitude(float(data['coordinates']['lng'])),
                        KML.latitude(float(data['coordinates']['lat'])),
                        KML.altitude(0),
                        KML.heading(0),
                        KML.tilt(data['data']),
                        KML.name(data['data']),
                        KML.range(self.range),
                        KML.altitudeMode("relativeToGround"),
                    )
                ),
            )
            # spin around the data
            for aspect in range(0, 360, 10):
                tour_doc.Document[gxns + "Tour"].Playlist.append(
                    GX.FlyTo(
                        GX.duration(0.25),
                        GX.flyToMode("smooth"),
                        KML.LookAt(
                            KML.longitude(float(data['coordinates']['lng'])),
                            KML.latitude(float(data['coordinates']['lat'])),
                            KML.altitude(0),
                            KML.heading(aspect),
                            KML.tilt(data['data']),
                            KML.name(data['data']),
                            KML.range(self.range),
                            KML.altitudeMode("relativeToGround"),
                        )
                    )
                )
            tour_doc.Document[gxns + "Tour"].Playlist.append(GX.Wait(GX.duration(1.0)))

            # tour_doc.Document[gxns+"Tour"].Playlist.append(
            #        GX.TourControl(GX.playMode("pause"))
            #    )

            # add a placemark for the data
            tour_doc.Document.Folder.append(
                KML.Placemark(
                    KML.name(data['data']),
                    KML.description(
                        "<h1>" + data['data'] + "</h1>"
                    ),
                    KML.styleUrl('#{0}'.format(stylename)),
                    KML.Point(
                        KML.extrude(1),
                        KML.altitudeMode("relativeToGround"),
                        KML.coordinates("{lon},{lat},{alt}".format(
                            lon=float(data['coordinates']['lng']),
                            lat=float(data['coordinates']['lat']),
                            alt=50,
                        )
                        )
                    ),
                    id=data['data'].replace(' ', '_')
                )
            )
            # show the placemark balloon
            tour_doc.Document[gxns + "Tour"].Playlist.append(
                GX.AnimatedUpdate(
                    GX.duration(2.0),
                    KML.Update(
                        KML.targetHref(),
                        KML.Change(
                            KML.Placemark(
                                KML.visibility(1),
                                GX.balloonVisibility(1),
                                targetId=data['data'].replace(' ', '_')
                            )
                        )
                    )
                )
            )

            tour_doc.Document[gxns + "Tour"].Playlist.append(GX.Wait(GX.duration(2.0)))

            tour_doc.Document[gxns + "Tour"].Playlist.append(
                GX.AnimatedUpdate(
                    GX.duration(2.0),
                    KML.Update(
                        KML.targetHref(),
                        KML.Change(
                            KML.Placemark(
                                GX.balloonVisibility(0),
                                targetId=data['data'].replace(' ', '_')
                            )
                        )
                    )
                )
            )
            # fly to a space viewpoint
            tour_doc.Document[gxns + "Tour"].Playlist.append(
                GX.FlyTo(
                    GX.duration(5),
                    GX.flyToMode("bounce"),
                    KML.LookAt(
                        KML.longitude(float(data['coordinates']['lng'])),
                        KML.latitude(float(data['coordinates']['lat'])),
                        KML.altitude(0),
                        KML.heading(0),
                        KML.tilt(0),
                        KML.range(10000000.0),
                        KML.altitudeMode("relativeToGround"),
                    )
                ),
            )

        # check that the KML document is valid using the Google Extension XML Schema
        # assert(Schema("kml22gx.xsd").validate(tour_doc))

        # print etree.tostring(tour_doc, pretty_print=True)

        # output a KML file (named based on the Python script)
        outfile = file("kmls_management/static/" + self.kml_name, 'w')
        outfile.write(etree.tostring(tour_doc, pretty_print=True))
示例#50
0
z0 = loc0['altitude']
z1 = loc1['altitude']
deltat = (-vz - math.sqrt(vz**2 - 2 * g * (z0 - z1))) / g
deltat = 30  # set manually, not sure what is wrong with the previous eqn

#import ipdb; ipdb.set_trace()

# calculate the horizontal and rotational velocities
vy = (loc1['latitude'] - loc0['latitude']) / deltat
vx = (loc1['longitude'] - loc0['longitude']) / deltat
vh = (loc1['heading'] - loc0['heading']) / deltat
vt = (loc1['tilt'] - loc0['tilt']) / deltat

# create a tour object
tour_doc = kml.kml(kml.Folder(gx.Tour(
    kml.name("Play me!"),
    gx.Playlist(),
)))

tstep = 0.1
for t in drange(0, 15, tstep):
    pm = kml.Placemark(
        kml.name(str(t)),
        kml.Point(
            kml.altitudeMode("absolute"),
            kml.coordinates("{lon},{lat},{alt}".format(
                lon=loc0['longitude'] + vx * t,
                lat=loc0['latitude'] + vy * t,
                alt=loc0['altitude'] + vz * t + 0.5 * g * t**2,
            )),
        ))
    tour_doc.Folder.append(pm)
示例#51
0
    pm = kml.Placemark(
        kml.name(str(t)),
        kml.Point(
            kml.altitudeMode("absolute"),
            kml.coordinates("{lon},{lat},{alt}".format(
                lon=loc0['longitude'] + vx * t,
                lat=loc0['latitude'] + vy * t,
                alt=loc0['altitude'] + vz * t + 0.5 * g * t ** 2,
            )),

        )
    )
    tour_doc.Folder.append(pm)

    flyto = gx.FlyTo(
        gx.duration(tstep),
        gx.flyToMode("smooth"),
        kml.Camera(
            kml.longitude(loc0['longitude'] + vx * t),
            kml.latitude(loc0['latitude'] + vy * t),
            kml.altitude(loc0['altitude'] + vz * t + 0.5 * g * t ** 2),
            kml.heading(loc0['heading'] + vh * t),
            kml.tilt(loc0['tilt'] + vt * t),
            kml.altitudeMode("absolute"),
        )
    )
    tour_doc.Folder[GX_ns + "Tour"].Playlist.append(flyto)

assert Schema('kml22gx.xsd').validate(tour_doc)
print(etree.tostring(tour_doc,
                     pretty_print=True,
示例#52
0
    def appendTrackPlacemarks(self, doc, directory, et):
        """
        Append to the KML document doc a folder containing one or more tracks 
        for the JPEG files in directory, and a folder containing a set of 
        placemarks for each file.  A separate track will be generated for 
        each day, assigning colours in a cycle from the colourSet.
        
        Arguments:
        doc: the KML document to which the folder will be appended
        directory: the abspath to the directory containing the files
        et: an ExifTool object
        """
        # Extract time, orientation and GPS metadata from EXIF
        items = ['EXIF:DateTimeOriginal',
                 'EXIF:GPSStatus',
                 'EXIF:GPSMeasureMode',
                 'EXIF:GPSLongitude',
                 'EXIF:GPSLongitudeRef',
                 'EXIF:GPSLatitude',
                 'EXIF:GPSLatitudeRef',
                 'EXIF:GPSAltitude']
        basedir = os.path.basename(directory)

        # Gather JPEG metadata into places
        places = {}
        for f in os.listdir(directory):
            if self.verbosity > 0:
                print('search for JPEG files in ' + directory, 
                      file=sys.stderr)

            filebase, fileext = os.path.splitext(f)
            if fileext in ('.jpg', '.JPG', '.jpeg', '.JPEG'):
                filepath = os.path.join(directory, f)
                in_kml = ''

                tags = et.get_tags(items, filepath)
                if self.verbosity > 1:
                    for k in tags:
                        print(k, ' = ', tags[k], file=sys.stderr)

                if 'EXIF:GPSLongitude' in tags:
                    # GPS metadata id available
                    lat = lon = None
                    datestr = timestr = ''
                    alt = 0

                    if "EXIF:GPSLatitude" in tags:
                        lat = tags['EXIF:GPSLatitude']
                        if 'EXIF:GPSLatitudeRef' in tags and \
                           tags['EXIF:GPSLatitudeRef'] == 'S':

                            lat = -lat

                    if "EXIF:GPSLongitude" in tags:
                        lon = tags['EXIF:GPSLongitude']
                        if 'EXIF:GPSLongitudeRef' in tags and \
                           tags['EXIF:GPSLongitudeRef'] == 'W':

                            lon = -lon

                    if "EXIF:DateTimeOriginal" in tags:
                        m = re.match(r'\s*(\d+:\d+:\d+)\s+'
                                     r'(\d+:\d+:[\d.]+)\s*',
                                     tags['EXIF:DateTimeOriginal'])
                        datestr = re.sub(r':', '-', m.group(1))
                        timestr = m.group(2)

                    if "EXIF:GPSAltitude" in tags:
                        alt = tags['EXIF:GPSAltitude']

                    if self.verbosity > 1:
                        print(datestr,
                              timestr,
                              lat,
                              lon,
                              alt,
                              '\n',
                              file=sys.stderr)

                    if datestr and timestr and lat and lon:
                        in_kml = ' in kml'

                        if datestr not in places:
                            places[datestr] = {}
                        
                        timefile = timestr + filebase
                        if timefile not in places[datestr]:
                            places[datestr][timefile] = {}
                    
                        jpegmeta = places[datestr][timefile]
                        jpegmeta['filebase'] = filebase
                        jpegmeta['time'] = GX.when('T'.join(datestr, timestr))
                        jpegmeta['place'] = \
                            GX.coord('{0} {1} {2}'.format(lon, 
                                                          lat, 
                                                          alt))
                        jpegmeta['point'] = \
                            KML.Point(
                                KML.coordinates('{0},{1},{2}'.format\
                                                (lon, lat, 0)))
                        if self.config['arguments']['url']:
                            jpegmeta['fileurl'] = '/'.join(
                                self.config['arguments']['url'], basedir, f)
                        else:
                            jpegmeta['fileurl'] = '/'.join('file:/', filepath)

                if self.verbosity > 0:
                    print('    ' + f, in_kml, file=sys.stderr)

        # Build the track folder and placemark folder
        track_folder = KML.Folder()
        image_folder = KML.Folder()
        for datestr in sorted(places.keys()):
            colourID = '#colour' + str(self.colourIndex)
            placemark = KML.Placemark(
                KML.visibility('1'),
                KML.name(basedir),
                KML.description('Path taken at ' + basedir + ' on ' + 
                                datestr),
                KML.styleUrl(colourID)
                )
            self.colourIndex = (self.colourIndex + 1) % self.colourSetLen

            track = GX.Track(
                KML.altitudeMode('clampToGround')
                )
            for tf in sorted(places[datestr].keys()):
                # append when elements
                track.append(places[datestr][tf]['time'])
            for tf in sorted(places[datestr].keys()):
                # append coord elements
                track.append(jpegmeta[tf]['place'])
            placemark.append(track)
            track_folder.append(placemark)
            
            for tf in sorted(places[datestr].keys()):
                jpegmeta = places[datestr][tf]
                
                jpg = jpegmeta['filebase']
                cdatakey = 'CDATA' + directory + datestr + jpg
                self.cdatatext[cdatakey] = ('<![CDATA[<img src="' + 
                    jpegmeta['fileurl'] + ' width=400/><br/>' + 
                    'Taken at ' + directory + ' on ' + datestr + '<br/>]]>')
                image_folder.append( 
                    KML.Placemark(
                        KML.visibility('1'),
                        KML.styleUrl('#picture'),
                        KML.name(jpg),
                        KML.description('{' + cdatakey + '}'),
                        jpegmeta['point']
                    )
                )

        doc.append(track_folder)
        doc.append(image_folder)