def load(self, filename): self.nodes = [] file = open(filename, 'r') if file: track = gpx.Trackpoints() # create new Trackpoints object track.import_locations(file) # load a gpx file into it for point in track[ 0]: #iterate over the points, track[0] is list of all points in file lat = point.latitude lon = point.longitude self.nodes.append([lat, lon]) file.close() self.numNodes = len(self.nodes) self.set("centreOnce", True) self.pos = int(self.get("replayStart", 0) * self.numNodes) #this seems to work only with GPX 1.0 # regexp = re.compile("<trkpt lat=['\"](.*?)['\"] lon=['\"](.*?)['\"]") # for text in file: # matches = regexp.match(text) # if(matches): # lat = float(matches.group(1)) # lon = float(matches.group(2)) # self.nodes.append([lat,lon]) # file.close() # self.numNodes = len(self.nodes) # self.set("centreOnce", True) # self.pos = int(self.get("replayStart",0) * self.numNodes) else: print("No file")
def load(self, filename): """load a GPX file to datastructure""" file = open(filename, 'r') if file: track = gpx.Trackpoints() # create new Trackpoints object track.import_locations(file) # load a gpx file into it self.tracks[filename] = track file.close() else: print("No file")
def load_tracklog(self, path, notify=True): """Load a GPX file to datastructure.""" # is the cache loaded if self.cache == {}: # load the cache self._load_cache() # just to be sure, refresh the tracklog list if needed if self._tracklog_list == []: self.list_available_tracklogs() start = clock() self.filename = path file = None try: file = open(path, 'rt') except Exception: self.log.exception("loading tracklog failed: %s", path) if notify: self.sendMessage('notification:loading %s#1' % path) if file: # TODO: add handling of other than GPX files # import the GPX module only when really needed from upoints import gpx track = gpx.Trackpoints() # create new Trackpoints object # lets assume we have only GPX 1.1 files TODO: 1.1 and 1.0 try: track.import_locations(file, "1.1") # load a gpx file into it except Exception: self.log.exception("loading tracklog failed") if notify: self.sendMessage('notification:loading tracklog failed#2') return file.close() type = "GPX" # TODO: more formats support track = GPXTracklog(track, path, type, self.cache, self.save) self.tracklogs[path] = track self.log.info("Loading tracklog \n%s\ntook %1.2f ms", path, (1000 * (clock() - start))) if notify: self.sendMessage('notification:loaded in %1.2f ms' % (1000 * (clock() - start))) return track else: self.log.info("No tracklog file")
def store_route(self, route, name="", cat='misc'): """store a route, found by Google Directions to a GPX file, then load this file to tracklogs list, return resulting path or None when storing fails""" # import the GPX module only when really needed from upoints import gpx newTracklog = gpx.Trackpoints() trackpoints = map(lambda x: gpx.Trackpoint(x[0], x[1]), route) newTracklog.append(trackpoints) timeString = strftime("%Y%m%d#%H-%M-%S", gmtime()) # gdr = Google Directions Result, TODO: alternate prefixes when we have more routing providers name = name.encode('ascii', 'ignore') filename = "gdr_%s%s.gpx" % (name, timeString) # TODO: store to more formats ? return self.store_tracklog(newTracklog, filename, cat, "GPX")
def saveToGPX(self, path, turns=False): """Save way to GPX file points are saved as trackpoints, message points as routepoints with turn description in the <desc> field """ try: # first check if we cant open the file for writing f = open(path, "wb") # Handle trackpoints trackpoints = gpx.Trackpoints() # check for stored timestamps if self._points and len(self._points[0]) >= 4: # LLET trackpoints.append( [gpx.Trackpoint(x[0], x[1], None, None, x[2], x[3]) for x in self._points] ) else: # LLE trackpoints.append( [gpx.Trackpoint(x[0], x[1], None, None, x[2], None) for x in self._points] ) # Handle message points # TODO: find how to make a GPX trac with segments of different types # is it as easy just dumping the segment lists to Trackpoints ? # message is stored in <desc> messagePoints = self.message_points index = 1 mpCount = len(messagePoints) if turns: # message points contain Turn-By-Turn directions routepoints = gpx.Routepoints() for mp in messagePoints: name = "" if turns: name = "Turn %d/%d" % (index, mpCount) lat, lon, elev, message = mp.get_llmi() routepoints.append(gpx.Routepoint(lat, lon, name, message, elev, None)) index += 1 log.info('%d points, %d routepoints saved to %s in GPX format', path, len(trackpoints), len(routepoints)) else: waypoints = [] for mp in messagePoints: name = "" if turns: name = "Turn %d/%d" % (index, mpCount) lat, lon, elev, message = mp.get_llmi() waypoints.append(gpx.Routepoint(lat, lon, name, message, elev, None)) index += 1 log.info('%d points, %d waypoints saved to %s in GPX format', len(trackpoints[0]), len(waypoints), path) # write the GPX tree to file # TODO: waypoints & routepoints support xmlTree = trackpoints.export_gpx_file() xmlTree.write(f) # close the file f.close() return True except Exception: log.exception('saving to GPX format failed') return False
def startLogging(self, name="", logType='gpx'): """Start a new log file :param str logType: tracklog output type :param str name: tracklog name :returns: tracklog filename or None :rtype: str or None """ if self.loggingEnabled: self.log.error("track logging already in progress") return None self.log.info("initializing the tracklog file") # zero the appropriate variables, etc. self.loggingEnabled = True self.loggingStartTimestamp = int(time.time()) self.maxSpeed = 0 self.avg1 = 0 self.avg2 = 0 self.avgSpeed = 0 self.currentTempLog = [] self.distance = 0 self.pxpyIndex.clear() logFolder = self.getLogFolderPath() name = self.generateLogName(name) self.logName = name filename = None if logType == 'gpx': # importing the GPX module can be time consuming so import it # when it is really needed self.log.info("GPX selected as format for the final output") from upoints import gpx self.currentLogGPX = gpx.Trackpoints() # set tracklog metadata self.currentLogGPX.name = name self.currentLogGPX.time = time.gmtime() # self.currentLogGPX.author = "modRana - a flexible GPS navigation system" # self.currentLogGPX.link = "http://nlp.fi.muni.cz/trac/gps_navigace" filename = "%s.gpx" % name self.logFilename = filename self.logPath = os.path.join(logFolder, filename) # initialize temporary CSV log files path1 = os.path.join(logFolder, "%s.temporary_csv_1" % name) path2 = os.path.join(logFolder, "%s.temporary_csv_2" % name) log1 = way.AppendOnlyWay() log1.startWritingCSV(path1) self.log1 = log1 log2 = way.AppendOnlyWay() log2.startWritingCSV(path2) self.log2 = log2 # start update and save timers self._startTimers() else: self.log.error("unknown track log format: %s" % logType) self.lastUpdateTimestamp = time.time() self.lastCoords = self.get('pos', None) self.log.info("tracklog file initialized") return filename