예제 #1
0
def write_gpx(gpx, name, act_type):
    # You can add routes and waypoints, too...
    tzname = None
    npoints = None

    # polyline encoder default values
    numLevels = 18
    zoomFactor = 2
    epsilon = 0.0
    forceEndpoints = True

    ##print('Created GPX:', gpx.to_xml())
    ts = int(time.time())
    filename = "%s/%i.gpx" % (filebase, ts)
    a = open(filename, "w")
    a.write(gpx.to_xml())
    a.close()
    gpx.simplify()
    # gpx.reduce_points(1000)
    trk = pl.read_gpx_trk(gpx.to_xml(), tzname, npoints, 2, None)
    try:
        polyline = pl.print_gpx_google_polyline(trk, numLevels, zoomFactor, epsilon, forceEndpoints)
    except UnboundLocalError as er:
        print(er)
        print("Not enough points to create a polyline")
        polyline = ""
    # polyline="polyline"

    add_run(gpx, name, act_type, filename, polyline)
예제 #2
0
def write_gpx(gpx,name,act_type):
# You can add routes and waypoints, too...
    tzname=None
    npoints=None

    # polyline encoder default values
    numLevels = 18;
    zoomFactor = 2;
    epsilon = 0.0;
    forceEndpoints = True;

  ##print('Created GPX:', gpx.to_xml())
    ts = int(time.time())
    filename = "%s/%i.gpx" % (filebase,ts)
    a = open(filename, 'w')
    a.write(gpx.to_xml())
    a.close()
    gpx.simplify()
    #gpx.reduce_points(1000)
    trk = pl.read_gpx_trk(gpx.to_xml(),tzname,npoints,2,None)
    try:
    	polyline=pl.print_gpx_google_polyline(trk,numLevels,zoomFactor,epsilon,forceEndpoints)
    except UnboundLocalError as er:
    	print(er)
    	print("Not enough points to create a polyline")
    	polyline=""
    #polyline="polyline"

    add_run(gpx,name,act_type,filename,polyline)
def main():
    args = parse_args()
    with open(args.route_filename, 'r') as fp:
        route = json.load(fp)
    timezone = args.timezone and pytz.timezone(args.timezone) or None
    gpx = convert(route, timezone)
    if args.creator:
        gpx.creator = args.creator
    print gpx.to_xml()
예제 #4
0
def saveGPX(gpx, fn):
    if debugging:
        print('Created GPX:', gpx.to_xml())
    waypoints = len(gpx.waypoints)
    if waypoints == 0:
        print(f'GPX with {str(waypoints)} waypoints SKIPPED: {fn}')
        return
    f = open(fn, "w")
    f.write(gpx.to_xml())
    f.close()
    print(f'GPX with {str(waypoints)} points exported to {fn}')
예제 #5
0
def gen_gpx(list):
    gpx = gpxpy.gpx.GPX()
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # Create points:
    for i in list:
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(i["y"], i["x"]))
    print gpx.to_xml()
예제 #6
0
def gamepadStuff():
    gpsData = readFromNav()
    if gpsData:
        print("gpsData", gpsData)
        global gpsSpeed
        gpsSpeed['text'] = "{:.9f}".format(3.6 * gpsData["speed"])
        print(gpsSpeed['text'])
    global chokeIsOn
    if (not chokeIsOn):
        for event in pygame.event.get():
            if event.type == pygame.JOYBUTTONDOWN:
                print("Joystick button pressed.", event.dict['button'])
                if (event.dict['button'] == 15):
                    print("Starting new GPX file")
                    print('Created GPX:', gpx.to_xml())
                    timestr = time.strftime("%Y%m%d-%H%M%S")
                    with open("gpslog" + timestr + ".xml", "a") as text_file:
                        print(gpx.to_xml(), file=text_file)
                        elevationValue = 0
                        createGpxTrack()

            if event.type == pygame.JOYBUTTONUP:
                print("Joystick button released.")
            #Brake
            value = ((jStick.get_axis(12) * 100) + 100) / 2
            scale3.set(int(round(value)))
            value = 375 - (value) * 2.25
            brakeValue(str(+int(round(value))))
            #Speed
            #441 max
            # 150 min
            value = ((jStick.get_axis(13) * 100) + 150) / 2
            scale2.set(int(round(value)))
            value = (value) + 350
            speedValue(str(+int(round(value))))
            #Steer:
            #300 Min
            #445 Max
            value = ((jStick.get_axis(0) * 100)) / 2
            scale.set(int(round(value)))
            value = (value + 50) * 1.45 + 300
            steerValue(str(+int(round(value))))
        root.after(50, gamepadStuff)
        return
    else:
        toSet = chokeMinValue + randint(15, 35)
        scale2.set(toSet)
        sock.sendto(
            bytes('speed:' + str((chokeMinValue + toSet) + 350), 'UTF-8'),
            server_address)
    root.after(200, gamepadStuff)
예제 #7
0
def gamepadStuff():
	gpsData = readFromNav()
	if gpsData:
		print("gpsData", gpsData)
		global gpsSpeed
		gpsSpeed['text'] = "{:.9f}".format(3.6 * gpsData["speed"])
		print(gpsSpeed['text'])
	global chokeIsOn
	if(not chokeIsOn):
		for event in pygame.event.get(): 
			if event.type == pygame.JOYBUTTONDOWN:
				print("Joystick button pressed." , event.dict['button'])
				if(event.dict['button'] == 15):
					print("Starting new GPX file")
					print('Created GPX:', gpx.to_xml())
					timestr = time.strftime("%Y%m%d-%H%M%S")
					with open("gpslog"+ timestr + ".xml", "a") as text_file:
						print(gpx.to_xml(), file=text_file)
						elevationValue = 0
						createGpxTrack()

			if event.type == pygame.JOYBUTTONUP:
				print("Joystick button released.")
			#Brake
			value = ((jStick.get_axis(12) * 100)+ 100) / 2
			scale3.set(int(round(value)))
			value =  375 - (value)*2.25 
			brakeValue(str(+int(round(value))))
			#Speed
			#441 max
			# 150 min
			value = ((jStick.get_axis(13) * 100) +150) / 2
			scale2.set(int(round(value)))
			value =  (value) + 350
			speedValue(str(+int(round(value))))
			#Steer:
			#300 Min 
			#445 Max
			value = ((jStick.get_axis(0) * 100)) / 2
			scale.set(int(round(value)))
			value =  (value+50)*1.45 + 300
			steerValue(str(+int(round(value))))
		root.after(50, gamepadStuff)
		return
	else:
		toSet = chokeMinValue + randint(15,35)
		scale2.set(toSet)
		sock.sendto(bytes('speed:'+ str((chokeMinValue + toSet) +350),'UTF-8'), server_address)
	root.after(200, gamepadStuff)
예제 #8
0
    def to_gpx(self):
        self.images = sorted(self.images, key=lambda i: i.datetime)

        gpx = gpxpy.gpx.GPX()
        track = gpxpy.gpx.GPXTrack()
        gpx.tracks.append(track)


        prev_image = None
        current_segment = gpxpy.gpx.GPXTrackSegment()
        track.segments.append(current_segment)

        for img in self.images:
            print(img.datetime, img.lat, img.lng)
            point = gpxpy.gpx.GPXTrackPoint(img.lat, img.lng, time=img.datetime)

            if prev_image is not None:
                if prev_image.datetime.date() != img.datetime.date():
                    self.logger.debug("new day => new segment")
                    current_segment = gpxpy.gpx.GPXTrackSegment()
                    track.segments.append(current_segment)

            prev_image = img
            current_segment.points.append(point)


        return gpx.to_xml()
예제 #9
0
def downloader(activityID, filename):

	r = requests.get(STRAVA_STREAM_URL + activityID, params=DATA)

	json_track = json.loads(r.text)

	gpx = gpxpy.gpx.GPX()

	# Create first track in our GPX:
	gpx_track = gpxpy.gpx.GPXTrack()
	gpx.tracks.append(gpx_track)

	# Create first segment in our GPX track:
	gpx_segment = gpxpy.gpx.GPXTrackSegment()
	gpx_track.segments.append(gpx_segment)

	for latlng, altitude in list(zip(json_track['latlng'], json_track['altitude'])):
		gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(
			latlng[0], latlng[1], elevation=altitude))

	filename = filename if '.gpx' in filename else filename + '.gpx'

	with open(filename, 'w') as fw:
		fw.write(gpx.to_xml())

	fw.close()
예제 #10
0
def get_gpx(id):
    uri = f'https://data.gouv.nc/api/records/1.0/search/?dataset=sentiers-de-randonnee-en-province-sud&fields=id,title,description,tracewkt&rows=1&q=id%3D{id}'

    res = requests.get(uri, headers={'Authorization': f'Apikey {APIKEY}'})

    randonnee = res.json()['records'][0]['fields']

    gpx = gpxpy.gpx.GPX()

    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    for point in randonnee['tracewkt']['coordinates']:
        longitude, latitude = point
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(latitude, longitude))

    return app.response_class(response=json.dumps({
        'id':
        randonnee['id'],
        'title':
        randonnee['title'],
        'description':
        randonnee['description'],
        'gpx':
        gpx.to_xml()
    }),
                              status=200,
                              mimetype='application/json')
예제 #11
0
파일: codoon.py 프로젝트: bcc0421/VisHealth
    def trans(self , route ):
        points = route["data"]["points"]

        # Calculate offset of start point
        lat = points[0]["latitude"]
        lon = points[0]["longitude"]

        realoffset = self.justifyCityOffset( float(lat) ,float(lon) )
        print realoffset

        gpx = gpxpy.gpx.GPX()
        # Create route in our GPX:
        gpx_route = gpxpy.gpx.GPXRoute()

        i = 1
        for p in points:
            tmpname = "#%5d" % i
            tmptime = strptime( p["time_stamp"] , DATE_FORMAT )
            lat = float(p["latitude"]) + float(realoffset[0])
            lon = float(p["longitude"]) + float(realoffset[1])

            gpx_point = gpxpy.gpx.GPXRoutePoint( name = tmpname , longitude = lon , latitude = lat ,
                elevation = p["elevation"] , time = tmptime )
            # print gpx_point
            gpx_route.points.append( gpx_point )
            i = i + 1

        gpx.routes.append(gpx_route)

        # print 'Created GPX:', gpx.to_xml()
        return gpx.to_xml()
예제 #12
0
파일: Utrack.py 프로젝트: ernesst/Utrack
def leave(gpx):
    global info_display
    filename = str(round(time.time() * 1000))
    os.system('clear')
    print('\nGPX file Created : ' + filename + ".gpx")
    file = open("/home/phablet/Downloads/" + filename + ".gpx", "w+")
    file.write(gpx.to_xml())
    file.close()
    gpx_file = "/home/phablet/Downloads/" + filename + ".gpx"
    shutil.chown(gpx_file, user="******", group="phablet")
    gpx = gpxpy.parse(open(gpx_file))
    indentation = '   '
    info_display = ""
    length_2d = gpx.length_2d()
    length_3d = gpx.length_3d()
    info_display += "\n%sLength 2D: %s" % (indentation, format_long_length(length_2d))
    info_display += "\n%sLength 3D: %s" % (indentation, format_long_length(length_3d))
    moving_time, stopped_time, moving_distance, stopped_distance, max_speed = gpx.get_moving_data()
    info_display += "\n%sMoving time: %s" %(indentation, format_time(moving_time))
    info_display += "\n%sStopped time: %s" %(indentation, format_time(stopped_time))
    info_display += "\n%sMax speed: %s" % (indentation, format_speed(max_speed))
    info_display += "\n%sAvg speed: %s" % (indentation, format_speed(moving_distance / moving_time) if moving_time > 0 else "?")
    uphill, downhill = gpx.get_uphill_downhill()
    info_display += "\n%sTotal uphill: %s" % (indentation, format_short_length(uphill))
    info_display += "\n%sTotal downhill: %s" % (indentation, format_short_length(downhill))
    info_display += "\n\n\n"
    print(info_display)
    if args.activity:
        newlocation="/home/phablet/.local/share/activitytracker.cwayne18/{}".format(filename + ".gpx")
        copyfile(gpx_file, newlocation)
        shutil.chown(newlocation, user="******", group="phablet")
        add_run(gpx,filename,"", newlocation)
    p.kill()
    sys.exit()
def make_gpx_from_points(title, points_dict_list):
    gpx = gpxpy.gpx.GPX()
    gpx.nsmap[
        "gpxtpx"] = "http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx_track.name = title
    gpx_track.type = "Run"
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)
    for p in points_dict_list:
        if p.get("heart_rate") is None:
            point = gpxpy.gpx.GPXTrackPoint(**p)
        else:
            heart_rate_num = p.pop("heart_rate")
            point = gpxpy.gpx.GPXTrackPoint(**p)
            gpx_extension_hr = ElementTree.fromstring(
                f"""<gpxtpx:TrackPointExtension xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1">
                <gpxtpx:hr>{heart_rate_num}</gpxtpx:hr>
                </gpxtpx:TrackPointExtension>
            """)
            point.extensions.append(gpx_extension_hr)
        gpx_segment.points.append(point)
    return gpx.to_xml()
예제 #14
0
def CreateTrack(gliderName, lat, lon, **kwargs):
    gpx = gpxpy.gpx.GPX()
    # Create first track in our GPX:
    #gpx_track = gpxpy.gpx.GPXTrack()
    #gpx.tracks.append(gpx_track)
    # Create first segment in our GPX track:
    gpx_last_waypoint = gpxpy.gpx.GPXWaypoint(
        lat, lon, 0, datetime.datetime.today(), gliderName,
        'GliderLocation from Dockserver')
    gpx.waypoints.append(gpx_last_waypoint)

    if kwargs.has_key('wpt_lat') and kwargs.has_key('wpt_lon'):
        wpt_lat, wpt_lon = kwargs['wpt_lat'], kwargs['wpt_lon']
        gpx_aim_waypoint = gpxpy.gpx.GPXWaypoint(wpt_lat, wpt_lon)
        gpx.waypoints.append(gpx_aim_waypoint)

    #gpx_segment = gpxpy.gpx.GPXTrackSegment()
    #gpx_track.segments.append(gpx_segment)
    # Create points:
    #gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1234, 5.1234, elevation=0))
    #gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1235, 5.1235, elevation=0))
    #gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(2.1236, 5.1236, elevation=0))

    # You can add routes and waypoints, too...
    return gpx.to_xml()
예제 #15
0
파일: omexport.py 프로젝트: persep/omexport
    def write_combined_track(self):
        "Write all database tracks to one GPX file"

        gpx = gpxpy.gpx.GPX()

        tracks = self.database.cursor()
        tracks.execute('''select _id, trackfolder, trackname, trackdescr from tracks
                          order by trackfolder, _id''')

        for row in tracks:
            track_id = row['_id']
            track_name = row['trackname']
            track_description = row['trackdescr']
            track_folder = row['trackfolder']

            print('Exporting track {} / {}'.format(track_folder, track_name))

            if not track_folder == '' and not track_folder == '---':
                track_name = '{} - {}'.format(track_folder, track_name)

            self.add_track_to_gpx(track_id, track_name, track_description, gpx)

        tracks.close()

        try:
            with open(self.output_file, 'w', encoding='utf-8') as file:
                file.write(gpx.to_xml())
        except OSError as ex:
            print('Error: Cannot write file {}: {} - using track-ID as name'.
                  format(self.output_file, ex))
예제 #16
0
def generate_gpx(*args, **kwargs):
    args = dict(request.args)
    if 'trip_name' not in args and 't' not in args:
        return bad_request_error_handler(NameError(f'Key trip_name not found'))
    trip_name = ''.join((args.get('trip_name', None) or args['t']))
    waypoints = get_waypoints_by_trip(trip_name)
    gpx = gpxpy.gpx.GPX()
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)
    for i in range(len(waypoints)):
        id, fms_key_id, id_fms, lat, long, alt, ts, bs, msg = waypoints[i]
        ts = str_ts_to_UTC_ts(ts)
        if msg:
            ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime(" (%m-%d %H:%M)")
            gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=msg + ts_msg, time=ts, name=msg + ts_msg))
        cur_pnt = gpxpy.gpx.GPXTrackPoint(latitude=lat, longitude=long, elevation=alt, comment=msg, time=ts)
        cur_pnt.description = f"Время: {ts} Заряд батареи {bs}"
        gpx_segment.points.append(cur_pnt)
    # Добавляем точку с временем последнего сообщения
    if waypoints:
        ts_msg = ts.astimezone(timezone(offset=timedelta(hours=+3))).strftime("%Y-%m-%d %H:%M:%S")
        gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(latitude=lat, longitude=long, elevation=alt, comment=ts_msg, time=ts, name=ts_msg))
    hdrs = Headers()
    hdrs.add('Content-Type', 'application/gpx+xml')
    hdrs.add('Content-Disposition', 'attachment', filename='track.gpx')
    return Response(gpx.to_xml(), headers=hdrs)
예제 #17
0
def gpx_export(move):

    gpx = gpxpy.gpx.GPX()
    gpx.creator = "OpenMoves - http://www.openmoves.net/"

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # Create points:
    gps_samples = move.samples.filter(
        Sample.sample_type.like('gps-%')).order_by(Sample.time.asc())

    if gps_samples.count() == 0:
        flash("No GPS samples found for GPX export", 'error')
        return None

    for gps_sample in gps_samples:
        gpx_segment.points.append(
            gpxpy.gpx.GPXTrackPoint(
                latitude=radian_to_degree(gps_sample.latitude),
                longitude=radian_to_degree(gps_sample.longitude),
                elevation=gps_sample.gps_altitude,
                time=move.date_time + gps_sample.time,
                position_dilution=gps_sample.gps_hdop))

    # You can add routes and waypoints, too...
    return gpx.to_xml()
예제 #18
0
def write_gpx(log_data: bytes, file_name: str) -> int:
    try:
        log = Locus(log_data)
    except LocusError:
        logger.warning("Log is blank. Not writing empty GPX file")
        return 0

    gpx = gpxpy.gpx.GPX()

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # Create points:
    for point in log:
        p = gpxpy.gpx.GPXTrackPoint(time=datetime.datetime.utcfromtimestamp(
            point["utc_time"]),
                                    latitude=point["latitude"],
                                    longitude=point["longitude"],
                                    elevation=point["height"])
        # TODO: Use GPX 1.1 extensions for speed and heading, but which ones?
        # {"nmea:speed": point["speed"] * 3.6 / 1.852}
        # {"nmea:heading": point["heading"]}
        gpx_segment.points.append(p)

    with open(file_name, "w") as f:
        f.write(gpx.to_xml(version="1.1"))

    return 0
예제 #19
0
def download(downId):

    # connect to database
    dbDown=mdb.connect(host="mysql.server",user="******", \
            db=dbName,passwd="you-wish")
    curDown=dbDown.cursor()

    curDown.execute("SELECT MapMyRunId, Lat, Lng FROM Points WHERE MapMyRunId = %s", (downId))
    query_results=curDown.fetchall()
    path=[]
    for result in query_results:
        path.append(dict(id=result[0],lat=result[1],lng=result[2]))

    # setup gpx file
    gpx = gpxpy.gpx.GPX()

    # create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx_track.name = 'test'
    gpx.tracks.append(gpx_track)
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # write route points to gpx file
    points_count = len(path)
    points_range = range(points_count)
    for point_num in points_range:
        point = path[point_num]
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(point['lat'], point['lng']))

    # gpx is essentially xml format, so form proper response
    response = make_response(gpx.to_xml())
    response.headers["Content-Disposition"] = "attachment; filename=route.gpx"
    return response
예제 #20
0
def gen_gpx(gpx_points):
    gpx = gpxpy.gpx.GPX()
    gpx.nsmap[
        "gpxtpx"] = "http://www.garmin.com/xmlschemas/TrackPointExtension/v1"
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)
    file_name = gpx_points[0].get("start_time")

    for p in gpx_points:
        # delete useless attr
        del p["start_time"]
        if p.get("heart_rate") is None:
            point = gpxpy.gpx.GPXTrackPoint(**p)
        else:
            heart_rate_num = p.pop("heart_rate")
            point = gpxpy.gpx.GPXTrackPoint(**p)
            gpx_extension_hr = ElementTree.fromstring(
                f"""<gpxtpx:TrackPointExtension xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1">
                <gpxtpx:hr>{heart_rate_num}</gpxtpx:hr>
                </gpxtpx:TrackPointExtension>
            """)
            point.extensions.append(gpx_extension_hr)
        gpx_segment.points.append(point)
    return gpx.to_xml(), file_name
예제 #21
0
def create_gpx(activity_meta):
    activity_ids = activity_meta['id']
    # types = ['time', 'distance', 'latlng', 'altitude', 'velocity_smooth', 'moving', 'grade_smooth', 'heartrate']
    types = ['time', 'latlng', 'altitude']
    for thisid in activity_ids:
        activity_data = client.get_activity_streams(thisid, types=types)
        # get start time for this activity
        starttime = activity_meta[activity_meta['id'] ==
                                  thisid]['start_date'].values[0]

        ### Create gpx output
        gpx = gpxpy.gpx.GPX()

        # Create first track in our GPX:
        gpx_track = gpxpy.gpx.GPXTrack()
        gpx.tracks.append(gpx_track)

        # Create first segment in our GPX track:
        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)

        for i in range(len(activity_data['time'].data)):
            lat = activity_data['latlng'].data[i][0]
            lon = activity_data['latlng'].data[i][1]
            ele = activity_data['altitude'].data[i]
            ts = pd.to_datetime(starttime) + datetime.timedelta(
                0, activity_data['time'].data[i])
            gpx_segment.points.append(
                gpxpy.gpx.GPXTrackPoint(lat, lon, elevation=ele, time=ts))

        filename = "strava_id_" + str(thisid) + ".gpx"
        with open(filename, "w") as f:
            f.write(gpx.to_xml())
        print("Generated file " + filename)
예제 #22
0
def get_gpx(request, track_id):

    tracks = Track.objects.all()

    if not request.user.is_authenticated:
        tracks = Track.objects.filter(public=True)

    track =  get_object_or_404(tracks, id=track_id)

    gpx = gpxpy.gpx.GPX()
    gpx_track = gpxpy.gpx.GPXTrack(name=track.name)
    gpx.tracks.append(gpx_track)

    segments = Segment.objects.filter(track=track)

    for segment in segments:

        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        points = Point.objects.filter(segment=segment).order_by('date')

        for point in points:
            gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(
                point.latitude,
                point.longitude,
                elevation=point.altitude,
                time=point.date
            ))

        gpx_track.segments.append(gpx_segment)

    return HttpResponse(gpx.to_xml(), content_type="application/gpx+xml")
예제 #23
0
def write_gpx(log_data: bytes,  file_name: str) -> int:
    log = decode_gps_log(log_data)
    if log is None:
        logger.warning("Log is blank. Not writing empty GPX file")
        return 0

    gpx = gpxpy.gpx.GPX()

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # Create points:
    for point in log["waypoints"]:
        p = gpxpy.gpx.GPXTrackPoint(
            latitude=point["latitude"],
            longitude=point["longitude"],
            elevation=point["elevation"],
            time=point["utc_time"],
        )
        # TODO: Use GPX 1.1 extensions for speed and heading, but which ones?
        # {"nmea:speed": point["speed"] * 3.6 / 1.852}
        # {"nmea:heading": point["heading"]}
        gpx_segment.points.append(p)

    with open(file_name, "w") as f:
        f.write(gpx.to_xml(version="1.1"))

    return 0
예제 #24
0
def update_downloader(eps, npts, idx_cluster, relayoutData):

    mdf, lat0, lon0, zoom0 = filter_data(relayoutData)

    d = get_dbscan_data(mdf, eps, npts)

    tmp = d[d["cluster"] == idx_cluster]

    gpx = gpxpy.gpx.GPX()

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    for index, row in tmp.iterrows():
        lat = row["Lat"]
        lon = row["Lon"]
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(lat, lon))
    gpxString = "data:text/csv;charset=utf-8," + urllib.parse.quote(
        gpx.to_xml())
    return gpxString
예제 #25
0
def create_gpx(activities):
    # get point from activities
    for activity in activities:
        generatedName = USERNAME + "-" + str(uuid.uuid4())[:8] + str(
            uuid.uuid4())[:5]
        filename = "gpx/tmp/" + generatedName + ".gpx"

        points = polyline.decode(activity['map']['summary_polyline'])

        # init gpx file
        gpx = gpxpy.gpx.GPX()

        gpx_track = gpxpy.gpx.GPXTrack()
        gpx.tracks.append(gpx_track)

        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)

        for point in points:
            gpx_segment.points.append(
                gpxpy.gpx.GPXTrackPoint(point[0], point[1]))

        file = open(filename, "w")
        file.write(gpx.to_xml())
        file.close()
        cursor = DB.cursor()
        sql = "INSERT INTO tmp_gpx (name, user_id) VALUES (%s,%s)"

        cursor.execute(sql, (generatedName, USER_ID))
        DB.commit()
예제 #26
0
    def handle(self, *args, **options):
        session = requests.Session()
        # access_token = ''
        # params = {
        #     'access_token': access_token,
        #     'geometries': 'geojson',
        #     'overview': 'full'
        # }
        # for service in Service.objects.filter(operator='LYNX', current=True):
        #     print(service)
        #     linestrings = (self.get_linestring(session, access_token, params, ls) for ls in service.geometry)
        #     linestrings = (ls for ls in linestrings if ls)
        #     service.geometry = MultiLineString(*linestrings).simplify()
        #     service.save()

        for service in Service.objects.filter(current=True, operator='SNDR'):
            stopses = set()
            for file in service.get_files_from_zipfile():
                timetable = txc.Timetable(file)
                for grouping in timetable.groupings:
                    for journeypattern in grouping.journeypatterns:
                        stop_ids = [journeypattern.sections[0].timinglinks[0].origin.stop.atco_code]
                        for section in journeypattern.sections:
                            for timinglink in section.timinglinks:
                                stop_ids.append(timinglink.destination.stop.atco_code)
                        stopses.add(','.join(stop_ids))

            stopses = [string.split(',') for string in stopses]

            linestrings = []
            for stop_ids in stopses:
                stops = StopPoint.objects.in_bulk((stop_ids))

                gpx = gpxpy.gpx.GPX()
                gpx_track = gpxpy.gpx.GPXTrack()
                gpx.tracks.append(gpx_track)

                gpx_segment = gpxpy.gpx.GPXTrackSegment()
                gpx_track.segments.append(gpx_segment)

                for stop_id in stop_ids:
                    stop = stops[stop_id]
                    point = gpxpy.gpx.GPXTrackPoint(stop.latlong.y, stop.latlong.x)
                    gpx_segment.points.append(point)

                xml = gpx.to_xml()

                response = session.post('https://bustimes.org/match?type=json&points_encoded=false',
                                        headers={'Content-Type': 'application/gpx+xml'},
                                        data=xml)
                if response.ok:
                    json = response.json()
                    if json['map_matching']['distance']:
                        geometry = json['paths'][0]['points']
                        linestrings.append(GEOSGeometry(str(geometry)))

            service.geometry = MultiLineString(*linestrings)
            service.save()
            print(service.pk)
예제 #27
0
def process_and_save(input_file_path, new_time, new_filename):
    gpx_file = open(input_file_path, 'r')
    gpx = gpxpy.parse(gpx_file)
    delta = relativedelta(new_time, gpx.time)
    gpx.adjust_time(delta)

    with open(new_filename, 'w') as f:
        f.write(gpx.to_xml())
예제 #28
0
    def to_gpx(self):
        if self.point_file != None and os.path.isfile(self.point_file):
            st = os.stat(self.point_file)
            print("{0:s}, size {1:d}".format(self.point_file, st.st_size))

            df = pd.read_csv(self.point_file,
                             sep=",",
                             header=None,
                             names=["x", "y", "name"],
                             dtype={
                                 "x": np.object,
                                 "y": np.object,
                                 "name": np.object
                             })
            #
            # with open(self.point_file, "r", encoding='utf8') as f:
            #     rows = list(csv.reader(f))

            gpx = gpxpy.gpx.GPX()

            for index, r in df.iterrows():
                if len(r) != 0:
                    x1, y1, name = r['x'].strip(), r['y'].strip(
                    ), r['name'].strip()
                    print("x1={},y1={}, name={}".format(x1, y1, name))

                    x1, y1 = normalize(x1, y1)
                    print("{},{}, name={}".format(x1, y1, name))
                    '''
                        In fact, the ll supported by all GPS tool (ex. Map Generation Tool) is based wgs84 rather than twd67
                        Can't correctly shows the ll if only change change coordination format
                    '''
                    x3, y3 = pyproj.transform(crs_twd67, crs_wgs84, x1, y1)
                    print("{:5.8f},{:5.8f}, name={}".format(y3, x3, name))

                    # wp = GPXWaypoint(longitude=x3, latitude=y3, name=name, elevation="0.0", time=datetime.now(),
                    #                  symbol="Waypoint")

                    wp = GPXWaypoint(longitude=x3,
                                     latitude=y3,
                                     name=name,
                                     elevation="0.0",
                                     time=np.datetime64("now").astype(object),
                                     symbol="Waypoint")
                    gpx.waypoints.append(wp)

            # print(gpx.to_xml())

            name = os.path.splitext(
                self.point_file
            )[0] + ".gpx"  # rename the source file with .gpx extension
            path = os.path.abspath(self.point_file)
            gpx_file = os.path.join(path, name)

            print("writing xml to {}".format(gpx_file))
            with open(gpx_file, "w+", encoding='utf8') as f:
                f.write(gpx.to_xml(version="1.1"))
            print("done")
예제 #29
0
def clean_gpx_file(file_name):
    # file_name : gpx_file(with complete path)
    # return : name of created file
    # at this stage, due to have n/a fields we cannot use 'pygpx' to open this file
    # replace n/a with 0
    fin = open(file_name, "rt")
    data = fin.read()
    fin.close()
    data = data.replace('n/a', '0')
    fout = open(file_name, "wt")
    fout.write(data)
    fout.close()
    # read the file with gpxpy
    gpx_file = open(file_name, 'r')
    gpx = gpxpy.parse(gpx_file)
    # find 0 lat/lon fields and fill them by
    # interpolate between geometries around them
    wpts_len = len(gpx.waypoints)
    wpts = gpx.waypoints
    i = 1
    last_valid_lat = float(wpts[0].latitude)
    last_valid_lon = float(wpts[0].longitude)
    while i < wpts_len:
        j = 1
        lat_1 = float(wpts[i].latitude)
        lon_1 = float(wpts[i].longitude)
        if lat_1 == 0:
            lat_2 = 0
            lon_2 = 0
            while (j + i) < wpts_len and lat_2 == 0:
                lat_2 = float(wpts[i + j].latitude)
                lon_2 = float(wpts[i + j].longitude)
                j += 1
            lat_offset = (lat_2 - last_valid_lat) / j
            lon_offset = (lon_2 - last_valid_lon) / j
            for k in range(j - 1):
                gpx.waypoints[k + i].latitude = str(last_valid_lat +
                                                    (k + 1) * lat_offset)
                # print(gpx1.waypoints[k+i].latitude, k)
                gpx.waypoints[k + i].longitude = str(last_valid_lon +
                                                     (k + 1) * lon_offset)
            # print(gpx1.waypoints[i+1].latitude,i)
            last_valid_lat = lat_2
            last_valid_lon = lon_2
        else:
            last_valid_lat = lat_1
            last_valid_lon = lon_1
        i += j

    # save new file
    new_file = open(file_name[:-4] + '_cleaned.gpx', 'w')
    new_file.write(gpx.to_xml())
    new_file.close()
    # remove last file
    gpx_file.close()
    os.remove(file_name)
    return file_name[:-4] + '_cleaned.gpx'
예제 #30
0
    def generate(self):
        gpx = gpxpy.gpx.GPX()
        gpx.name = self.tour["name"]
        gpx.description = f"Distance: {str(int(self.tour['distance']) / 1000.0)}km, " \
                          f"Estimated duration: {str(round(self.tour['duration'] / 3600.0, 2))}h, " \
                          f"Elevation up: {self.tour['elevation_up']}m, " \
                          f"Elevation down: {self.tour['elevation_down']}m, " \
                          f"Grade: {self.tour['difficulty']['grade']}"

        gpx.author_name = self.tour["_embedded"]["creator"]["display_name"]
        gpx.author_link = "https://www.komoot.de/user/" + str(
            self.tour["_embedded"]["creator"]["username"])
        gpx.author_link_text = "View " + gpx.author_name + "'s Profile on Komoot"
        gpx.link = "https://www.komoot.de/tour/" + str(self.tour["id"])
        gpx.link_text = "View tour on Komoot"
        gpx.creator = self.tour["_embedded"]["creator"]["display_name"]

        track = gpxpy.gpx.GPXTrack()
        track.name = gpx.name
        track.description = gpx.description
        track.link = gpx.link
        track.link_text = gpx.link_text
        track.link_type = gpx.link_type

        gpx.tracks.append(track)

        segment = gpxpy.gpx.GPXTrackSegment()
        track.segments.append(segment)

        for coord in self.route:
            point = gpxpy.gpx.GPXTrackPoint(coord.lat, coord.lng)
            if coord.alt != coord.CONST_UNDEFINED:
                point.elevation = coord.alt
            if coord.time != coord.CONST_UNDEFINED:
                point.time = datetime.fromtimestamp(coord.time / 1000)
            segment.points.append(point)

        if not self.no_poi:
            for poi in self.pois:
                wp = gpxpy.gpx.GPXWaypoint(poi.point.lat, poi.point.lng)
                if poi.point.alt != poi.point.CONST_UNDEFINED:
                    wp.elevation = poi.point.alt
                if poi.point.time != poi.point.CONST_UNDEFINED:
                    wp.time = datetime.fromtimestamp(poi.point.time / 1000)

                wp.name = poi.name
                wp.description = poi.description
                wp.source = "Komoot"
                wp.link = poi.url
                wp.link_text = "View POI on Komoot"
                wp.type = poi.type
                wp.comment = poi.image_url

                gpx.waypoints.append(wp)

        return gpx.to_xml()
예제 #31
0
파일: codoon.py 프로젝트: AEKEYS/VisHealth
    def trans(self , route , type = "track"):
        name = route["data"]["start_time"]
        points = route["data"]["points"]

        # Calculate offset of start point
        lat = points[0]["latitude"]
        lon = points[0]["longitude"]

        realoffset = self.justifyCityOffset( float(lat) ,float(lon) )
        print realoffset

        gpx = gpxpy.gpx.GPX()

        if type == "route":
            # Create route in GPX Route Format:
            rtname = "Route %s" % name
            gpx_route = gpxpy.gpx.GPXRoute(name = rtname)

            i = 1
            for p in points:
                tmpname = "#%5d" % i
                tmptime = strptime( p["time_stamp"] , DATE_FORMAT )
                lat = float(p["latitude"]) + float(realoffset[0])
                lon = float(p["longitude"]) + float(realoffset[1])

                gpx_point = gpxpy.gpx.GPXRoutePoint( name = tmpname , longitude = lon , latitude = lat ,
                    elevation = p["elevation"] , time = tmptime )
                # print gpx_point
                gpx_route.points.append( gpx_point )
                i = i + 1

            gpx.routes.append(gpx_route)
        else:
            # Create route in GPX Track Format:
            trkname = "Track %s" % name
            gpx_track = gpxpy.gpx.GPXTrack(name = trkname)
            gpx_track_seg = gpxpy.gpx.GPXTrackSegment()

            i = 1
            for p in points:
                tmpname = "#%5d" % i
                tmptime = strptime( p["time_stamp"] , DATE_FORMAT )
                lat = float(p["latitude"]) + float(realoffset[0])
                lon = float(p["longitude"]) + float(realoffset[1])

                gpx_point = gpxpy.gpx.GPXTrackPoint( name = tmpname , longitude = lon , latitude = lat ,
                    elevation = p["elevation"] , time = tmptime )
                # print gpx_point
                gpx_track_seg.points.append( gpx_point )
                i = i + 1

            gpx_track.segments.append(gpx_track_seg)
            gpx.tracks.append(gpx_track)

        # print 'Created GPX:', gpx.to_xml()
        return gpx.to_xml()
예제 #32
0
def save_gpx(file, tracks):
    gpx = gpxpy.gpx.GPX()
    for t in tracks:
        g = t.as_gpxpy
        if isinstance(g, gpxpy.gpx.GPXWaypoint):
            gpx.waypoints.append(g)
        else:
            gpx.tracks.append(g)
    with open(file, "w") as fh:
        print(fh, gpx.to_xml())
예제 #33
0
def tupsToGpx(tups):
    gpx = gpxpy.gpx.GPX()
    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    # Create points:
    for pt in tups:
        gpx_segment.points.append(
            gpxpy.gpx.GPXTrackPoint(pt[0], pt[1], elevation=0))

    # You can add routes and waypoints, too...

    print 'Created GPX:', gpx.to_xml()
    return gpx.to_xml()
예제 #34
0
def save_gpx(gpx, filename, dry_run):
    """Save this GPX with the same name in a new subdirectory"""
    subdir = Path("split")
    new_filename = subdir.joinpath(Path(filename))

    if not dry_run:
        new_filename.parent.mkdir(parents=True, exist_ok=True)
        with open(new_filename, "w") as f:
            f.write(gpx.to_xml())

    print(colored(new_filename, "green"))
예제 #35
0
def create_gpx_track(data):
    gpx = gpxpy.gpx.GPX()
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)
    [
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(point[1], point[0]))
        for point in data
    ]
    return gpx.to_xml()
예제 #36
0
def main():
    """
    Main function to do the work
    """
    #
    # Handle CLI args
    #
    parser = argparse.ArgumentParser(description=('Take a directory of GPS tagged'
                                                  ' images and output GPX track'))

    parser.add_argument('-d', '--directory', default=[], action='append',
                        required=True, type=is_directory,
                        help='Which directory of images to process. Repeat to '
                        'process multiple directories.')

    parser.add_argument('--debug', default=False, action='store_true',
                        help='Enable additional output')

    parser.add_argument('-l', '--log-level', action='store', required=False,
                        choices=["debug", "info", "warning", "error", "critical"],
                        default=DEFAULT_LOG_LEVEL,
                        help='Logging verbosity. Default: {}'.format(DEFAULT_LOG_LEVEL))

    args = parser.parse_args()

    # Enable the debug level logging when in debug mode
    if args.debug:
        args.log_level = 'debug'

    # Configure logging
    logging.basicConfig(format='%(levelname)s:%(module)s.%(funcName)s:%(message)s',
                        level=getattr(logging, args.log_level.upper()))

    _get_logger().info("Log level is '%s'", args.log_level.upper())

    gpx = gpxpy.gpx.GPX()
    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    for directory in args.directory:
        # Create a segment in our GPX track:
        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)

        track = process_directory(directory)

        for track_time in sorted(track):
            #pprint(track[track_time])
            gpx_segment.points.append(track[track_time])

    #pprint(track)
    print(clean_output(gpx.to_xml()))
def convert_to_gpx(log_file, force=False):
    print log_file + ' converting ...'
    gpx_file = log_file + '.gpx'
    if force is False and os.path.isfile(gpx_file):
        print gpx_file + ' file exist, skip converting'
        return

    with open(log_file) as f:
        content = f.read().splitlines()

    for i, var in enumerate(content):
        content[i] = var.split('\t')

    gpx = gpxpy.gpx.GPX()

    gpx_track_file_name = os.path.basename(log_file)
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx_track.name = gpx_track_file_name
    gpx.tracks.append(gpx_track)

    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    last_point_date_time = get_date_time('1970-01-01 00:00:00')

    for i, v in enumerate(content):
        if len(v) < 5:
            continue

        point_date_time = get_date_time(v[0])
        delta = point_date_time - last_point_date_time
        if i != 0 and delta.seconds > 60 * 10:
            gpx_segment = gpxpy.gpx.GPXTrackSegment()
            gpx_track.segments.append(gpx_segment)

        last_point_date_time = point_date_time

        lat = v[1][1:]
        lon = v[2][1:]
        elevation = v[3]

        current_speed = v[4]
        magnetic_variation = v[5]
        point = gpxpy.gpx.GPXTrackPoint(lat, lon, elevation=elevation, time=point_date_time, speed=current_speed)
        point.magnetic_variation = magnetic_variation
        gpx_segment.points.append(point)

    result = gpx.to_xml()

    result_file = open(gpx_file, 'w')
    result_file.write(result)
    result_file.close()
    print log_file + ' - done'
예제 #38
0
def buildGPXfromCoordinatesList(wfile,listMessages):
    gpx = gpxpy.gpx.GPX()
    name = 1
    for msg in listMessages:
        if msg != None:
            try:
                gpx_waypoint=gpxpy.gpx.GPXWaypoint(name=name, latitude=msg[0], longitude=msg[1])
                gpx.waypoints.append(gpx_waypoint)
                name += 1
            except:
                pass
    wfile.write(gpx.to_xml().encode('utf-8'))
def join_gpx(first_track_start, second_track_start):
    first_track_start = minutes_to_military(first_track_start)
    second_track_start = minutes_to_military(second_track_start)
    directory_name = 'tracks/'
    saving_name = 'save/'
    saving_directory = os.path.join(directory_name, saving_name)
   #print "####", first_track_start, second_track_start


    files =[]
    for f in os.listdir(saving_directory):
        files.append(f)
    files.sort()

    segments_to_delete = []
    for f_prev, f, f_next in neighborhood(files):
        filename = os.path.join(saving_directory, f)
        file = open(filename, 'rb')
        gpx_xml = file.read()
        file.close()
        gpx = gpxpy.parse(gpx_xml)

        if f_next is not None:
            filename_next = os.path.join(saving_directory, f_next)
            file_next = open(filename_next, 'rb')
            gpx_xml_next = file_next.read()
            file_next.close()
            gpx_next = gpxpy.parse(gpx_xml_next)

        for track, track_next  in zip(gpx.tracks, gpx_next.tracks):
            for segment, segment_next in zip(track.segments, track_next.segments):

                if segment.points[0].time.strftime("%H%M") == first_track_start and \
                    segment_next.points[0].time.strftime("%H%M") == second_track_start:
                    segment.join(segment_next)
                    #segments_to_delete.append(filename)
                    segments_to_delete.append(filename_next)

                    gpx = gpxpy.gpx.GPX()
                    # Create first track in our GPX:
                    gpx_track = gpxpy.gpx.GPXTrack()
                    gpx.tracks.append(gpx_track)
                    # Create first segment in our GPX track:
                    gpx_track.segments.append(segment)

                    open(filename, 'w').close()
                    fo = open(filename, "wb")
                    fo.write(gpx.to_xml())
                    fo.close()


    for f in segments_to_delete:
        os.remove(f)
예제 #40
0
def buildGPX(wfile,listNMEAMessages):
    gpx = gpxpy.gpx.GPX()
    name = 1
    for msg in listNMEAMessages:
        if msg != None:
            try:
                if msg.latitude != None and msg.longitude != None and  msg.latitude != 0.0 and msg.longitude != 0.0:
                    gpx_waypoint=gpxpy.gpx.GPXWaypoint(name=name, latitude=msg.latitude, longitude=msg.longitude)
                    gpx.waypoints.append(gpx_waypoint)
                    name += 1
            except:
                pass
    wfile.write(gpx.to_xml().encode('utf-8'))
예제 #41
0
def write_gpx(path, data):
    gpx = gpxpy.gpx.GPX()

    gpx_track = gpxpy.gpx.GPXTrack()
    gpx.tracks.append(gpx_track)

    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    for point in data:
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(
            point[1], point[2], elevation=point[3], time=point[0]))

    with open(path, "w") as f:
        f.write(gpx.to_xml())
예제 #42
0
def writeWaypoint(waypoint, base_name, **options):
    gpxutils.applyDefaults(options)

    if waypoint:
        # Create new GPX file
        gpx = gpxpy.gpx.GPX()

        # Append waypoint
        gpx.waypoints.append(waypoint)

        keep = (not options['interactive']) or prompt('waypoint', waypoint.name, base_name, waypoint.time)
        if keep:
            outfile = createUniqueFile(base_name, 'wpt', waypoint.time, waypoint.name, **options)
            with outfile.open('w') as output:
                output.write(gpx.to_xml())
     def process_item(self, item, spider):
       
        #start time is always on the day at 12:00
        start_time = datetime.strptime(item["date"], '%d-%B-%Y')
        start_time = start_time + timedelta(hours=12)
        
        #Create time object from duration
        #print "duration %s " % (item["time"])
        duration_sec = float(seconds(item["time"]))
        #print "duration_sec %s" % duration_sec 
        #Count number of points, this to calculate timedelta for every point based on the speed
        points = float(len(item["Lat"]))
         
        #time delta at every point should be points / seconds 
        time_per_point_sec = (duration_sec / points)
        time_per_point = round(time_per_point_sec * 1000,0)  #in Milliseconds
        #print int(time_per_point)
        #create time object from it
        time_delta = datetime.strptime(str(int(time_per_point)), '%f')
        
        activityname = "Run at " + start_time.strftime('%d-%m-%Y')
        gpx = gpxpy.gpx.GPX()

        # Create first track in our GPX:
        gpx_track = gpxpy.gpx.GPXTrack(name=activityname)
        gpx.tracks.append(gpx_track)

        # Create first segment in our GPX track:
        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)
 
        # Create points:
        for i,lat in enumerate(item ["Lat"]):
            #print "lat nr %s is %s " % (i , lat)
            lng = item ["Lng"][i]
            #print "lng nr %s is %s  " % (i , lng) 
            start_time = start_time + timedelta(seconds=time_per_point_sec)
            #elevation_data = mod_srtm.get_data()
            #meter = elevation_data.get_elevation(lat,lng)
            gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(lat, lng, elevation=None, time=start_time ))
        
        filename = "gps_track" + item["date"] + ".gpx"
        print " number of points %s in file %s " % (points, filename)
        file = open(filename, "w")
        file.write(gpx.to_xml())
        file.close()
예제 #44
0
def create_gpx(records):
	gpx = gpxpy.gpx.GPX()

	# Create first track in our GPX:
	gpx_track = gpxpy.gpx.GPXTrack()
	gpx.tracks.append(gpx_track)

	# Create first segment in our GPX track:
	gpx_segment = gpxpy.gpx.GPXTrackSegment()
	gpx_track.segments.append(gpx_segment)

	# Create points:
	for record in records:
		gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(record['lat'], record['lon'], elevation=record['alt'],time=record['date']))

	# You can add routes and waypoints, too...
	return gpx.to_xml()
예제 #45
0
def write_gpx(data):

  gpx_file = open('/mnt/sdcard/test.gpx', 'w')

  gpx = gpxpy.gpx.GPX()

#  gpx = gpxpy.parse(gpx_file)

  gpx_track = gpxpy.gpx.GPXTrack()
  gpx.tracks.append(gpx_track)

  gpx_segment = gpxpy.gpx.GPXTrackSegment()
  gpx_track.segments.append(gpx_segment)

  gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(data.lat_dd, data.lon_dd, elevation=data.alt_m))

  gpx_file.write(gpx.to_xml())
  gpx_file.close()
def polyline_to_gpx(polyline = None):
    if polyline == None:
        raise Exception("Need a Google Polyline as parameter")

    waypoints = None
    try:
        waypoints = PolylineCodec().decode(polyline)
    except Exception as e:
        raise Exception("Error decoding polyline. err: {}".format(e))

    gpx = gpxpy.gpx.GPX()
    gpx.creator = "Ride with gpxpy"

    for point in waypoints:
        lat, lon = point
        gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(lat, lon))

    return gpx.to_xml()
예제 #47
0
def merge_tracks(tracks, output_file=None):
	gpx = gpxpy.gpx.GPX()
	for t in tracks:
		gpx.tracks.append(t)
		
	xml = gpx.to_xml()
	
	# save output gpx file
	if output_file:
		
		directory = '/'.join(output_file.split('/')[0:-1])
		print directory
		if not os.path.exists(directory):
		    os.makedirs(directory)
		
		
		f = open(output_file, 'w+')
		f.write(xml)
		f.close()
		print 'Wrote to file: %s' % output_file
def gpx_from_design_matrix(design_matrix, labels, centroids, f_name):
    # Output clusters
    gpx = gpxpy.gpx.GPX()

    for row in range(design_matrix.shape[0]):
        start_cluster = design_matrix[row, 0]
        start_centroid = centroids[start_cluster, :]

        end_cluster = labels[row]
        end_centroid = centroids[end_cluster, :]

        gpx_track = gpxpy.gpx.GPXTrack()
        gpx.tracks.append(gpx_track)

        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)

        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(start_centroid[0], start_centroid[1], name=str(start_cluster), symbol=str(start_cluster)))
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(end_centroid[0], end_centroid[1], name=str(end_cluster), symbol=str(end_cluster)))

    with open(f_name, 'w') as out:
        out.write(gpx.to_xml())
예제 #49
0
def gpx_create(list_of_runzi_points, name):
    # Creating a new file:
    # --------------------

    gpx = gpxpy.gpx.GPX()

    # Create first track in our GPX:
    gpx_track = gpxpy.gpx.GPXTrack()
    gpx_track.name = name
    gpx.tracks.append(gpx_track)

    # Create first segment in our GPX track:
    gpx_segment = gpxpy.gpx.GPXTrackSegment()
    gpx_track.segments.append(gpx_segment)

    for point in list_of_runzi_points:
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(point['latitude'], point['longitude'], time=point['time'],
                                                          elevation=point['elevation']))

    # You can add routes and waypoints, too...

    return gpx.to_xml()
예제 #50
0
파일: tasks.py 프로젝트: igiroux/gpolygpx
def gpolyfiles2shp(pattern, ofname=None):
    files = glob(pattern)
    gpx = GpxRoute()
    with ThreadPoolExecutor(max_workers=4) as pool:
        futures2poly = {pool.submit(get_content, fname): fname for fname in files}
        for future in as_completed(futures2poly):
            fname = futures2poly[future]
            print('Handling %r' % fname)
            if future.exception() is not None:
                print('%r generated an exception: %s' % (fname, future.exception()))
                continue

            pcodec = PolylineCodec()

            polyxy = pcodec.decode(future.result())
            gpx_route = new_gpx_route(polyxy, name=fname)
            gpx.routes.append(gpx_route)

    with open(ofname, 'wb') as ofile:
        ofile.write(gpx.to_xml())

    print(ofname)
예제 #51
0
def writeAndCreateNewFile(segment, base_name, track_name=None, **options):
    gpxutils.applyDefaults(options)

    if segment is not None and segment.get_points_no() > 1:
        # Create new GPX file
        gpx = gpxpy.gpx.GPX()

        # Create first track in our GPX:
        track = gpxpy.gpx.GPXTrack(name=track_name)
        gpx.tracks.append(track)

        # Add segment to our GPX track:
        track.segments.append(segment)
        
        time = segment.get_time_bounds().start_time

        keep = (not options['interactive']) or prompt('track', track_name, base_name, time)
        if keep:
            outfile = createUniqueFile(base_name, 'trk', time, track_name, **options)
            with outfile.open('w') as output:
                output.write(gpx.to_xml())
        
    # Return a new segment
    return gpxpy.gpx.GPXTrackSegment()
예제 #52
0
    def makegpx(self, filename):

        gpx = gpxpy.gpx.GPX()
        gpx_track = gpxpy.gpx.GPXTrack()
        gpx.tracks.append(gpx_track)

        gpx_segment = gpxpy.gpx.GPXTrackSegment()
        gpx_track.segments.append(gpx_segment)
        for coord in self.coords:
            coordtime = datetime.strptime(self.data['startTime'], "%Y-%m-%d %H:%M:%S.%f") + timedelta(seconds=coord['timeOffset'])
            #print coordtime
            #print coord['latitude'], coord['longitude'], self.data['startTime'], coord['timeOffset']
            gpx_segment.points.append(
                    gpxpy.gpx.GPXTrackPoint(
                        coord['latitude'],
                        coord['longitude'],
                        time=coordtime,
                        elevation=self.find_nearest_altitude(
                            coord['timeOffset'])['altitude']
                        )
                    )

        with open(filename, 'w') as fp:
            fp.write(gpx.to_xml())
예제 #53
0
파일: tasks.py 프로젝트: igiroux/gpolygpx
def gpoly2gpx(ifname, output_dir=None, json_path='routes/route/polyline-definition/polyline'):
    response = get_content(ifname)
    pcodec = PolylineCodec()
    item = get_item(response, json_path)
    if item is None:

        logging.error(
            'Bad input from file {ifname}'
            '`\n`--> response {response}'
            .format(**locals()))
        sys.exit(1)

    polyxy = pcodec.decode(item)
    gpx = GpxRoute()
    gpx_route = new_gpx_route(polyxy)
    gpx.routes.append(gpx_route)

    fname, extension = splitext(ifname)
    output_dir = output_dir or dirname(fname)
    ofname = join(output_dir, '{}.gpx'.format(basename(fname)))
    with open(ofname, 'wb') as ofile:
        ofile.write(gpx.to_xml())

    print(ofname)
예제 #54
0
	def mergeTracksToFile(self, outputFile):
		if not outputFile: 
			print 'No output file set'
			return False
			
		# create a merged file
		
		
		# save the file
		gpx = gpxpy.gpx.GPX()
		tracks = self.getMergedTracks()
		tracks = self.sortTracksByTime(tracks)
		
		for t in tracks:
			gpx.tracks.append(t)

		xml = gpx.to_xml()

		# save output gpx file
		
		f = open(outputFile, 'w+')
		f.write(xml)
		f.close()
		print 'Merged GPX file saved at: %s' % outputFile	
예제 #55
0
        for point in segment.points:
            print 'Point at ({0},{1}) -> {2}'.format(point.latitude, point.longitude, point.elevation)

for waypoint in gpx.waypoints:
    print 'waypoint {0} -> ({1},{2})'.format(waypoint.name, waypoint.latitude, waypoint.longitude)

for route in gpx.routes:
    print 'Route:'
    for point in route.points:
        print 'Point at ({0},{1}) -> {2}'.format(point.latitude, point.longitude, point.elevation)

# There are many more utility methods and functions:
# You can manipulate/add/remove tracks, segments, points, waypoints and routes and
# get the GPX XML file from the resulting object:

print 'GPX:', gpx.to_xml()

# Creating a new file:
# --------------------

gpx = gpxpy.gpx.GPX()

# Create first track in our GPX:
gpx_track = gpxpy.gpx.GPXTrack()
gpx.tracks.append(gpx_track)

# Create first segment in our GPX track:
gpx_segment = gpxpy.gpx.GPXTrackSegment()
gpx_track.segments.append(gpx_segment)

# Create points:
예제 #56
0
			if key_id != 1:
				newtimestamp = datetime.datetime.strptime(time_stmp, '%Y-%m-%d %H:%M:%S.%f')
				#print newtimestamp
				newertimestamp = time.mktime(newtimestamp.timetuple())
				#print newertimestamp
				gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(lat, lon, elevation=alt, time=newtimestamp))
	
	except sqlite3.Error, e:
		if con:
			con.rollback()
		
		print "Error %s:" % e.args[0]
		sys.exit(1)
	
	finally:
		if con:
			con.close()
	
	
	foo = gpx.to_xml()
	
	f = open(real_filename, 'w')
	f.write(foo)
	
	print 'Done.'

if __name__ == "__main__":
	# call with 2 args, first is your DB, second is output filename (no type)
	main(sys.argv[1], sys.argv[2])

예제 #57
0
            continue
        row_time = millisec_to_time(int(row['time']))
        timestamp = time_start + row_time
        #coordinates += '''%s,%s ''' % (row["longitude"],row["latitude"])
        gpx_segment.points.append(gpxpy.gpx.GPXTrackPoint(row["latitude"], row["longitude"], time=timestamp))

    
    #gpx_folder = gpx_file.split('.')[0]
    #if os.path.exists(gpx_folder) and os.path.isdir(gpx_folder):
    #    print gpx_folder, 'exists'
    #else:
    #    os.mkdir(gpx_folder)
    #gpx_path = os.path.join(gpx_folder,gpx_file)    
    
    
    gpx_writer = open(gpx_path,'w')
    gpx_writer.write(gpx.to_xml())
    gpx_writer.close()


# In[4]:

get_ipython().magic(u'pinfo gpxpy.gpx.GPXTrackPoint')



# In[ ]:



예제 #58
0
def createGPXFile(name,gpx):
	file = open(name+'.gpx','w')
	file.write(gpx.to_xml())
	file.close()
	return
예제 #59
0
파일: wm2gps.py 프로젝트: mkotsur/wm2gps
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)) + "/gpxpy")

import gpxpy, gpxpy.gpx


url = "http://api.wikimapia.org/?function=box&bbox=" + sys.argv[1] + "&key=225F1176-F8C948A8-9334FE28-F51181B6-17749F78-D35641D3-789AD3AA-D7D26C75&count=100&disable=polygon&language=en"

thereArePlaces = True

gpx = gpxpy.gpx.GPX()
page = 1

while (thereArePlaces):
    
    url = url + "&page=" + str(page)
    
    xmlContent = urllib.urlopen(url, 'r').read()
    tree = ET.fromstring(xmlContent)

    
    places = tree.findall('place')
    thereArePlaces = (len(places) != 0)

    for place in places:
        location = place.find('location')
        gpx.waypoints.append(gpxpy.gpx.GPXWaypoint(location.find('lat').text, location.find("lon").text, name = place.find('name').text))
        
    page = page + 1
  
print gpx.to_xml()