Exemple #1
0
def switchToRouteDisplay(sender):
    global active
    active = ROUTE_DISPLAY
    view = ui.load_view(active)
    map = Map.MapView(frame=(81, 108, 252, 252))
    view.add_subview(map)
    view.present(orientations=['portrait'])

    location.start_updates()
    time.sleep(MAP_UPDATE_TIME)
    loc = location.get_location()
    location.stop_updates()

    # Update the map in the Route Display
    if loc:
        lat, lon = loc['latitude'], loc['longitude']
        map.set_region(lat, lon, MAP_ZOOM, MAP_ZOOM, animated=True)
        map.add_pin(lat, lon, 'Current Location', str((lat, lon)))
    """
	while (active == ROUTE_DISPLAY):
		location.start_updates()
		time.sleep(MAP_UPDATE_TIME)
		loc = location.get_location()
		location.stop_updates()
		lat, lon = loc['latitude'], loc['longitude']
		map.set_region(lat, lon, MAP_ZOOM, MAP_ZOOM, animated=True)
		map.add_pin(lat, lon, 'Current Location', str((lat, lon)))
	"""
    pass
Exemple #2
0
def __init__():
    view = ui.load_view(active)
    map = Map.MapView(frame=(81, 108, 252, 252))
    view.add_subview(map)
    view.present(orientations=['portait'])

    location.start_updates()
    time.sleep(MAP_UPDATE_TIME)
    loc = location.get_location()
    location.stop_updates()

    # Update the map in the splash screen
    if loc:
        lat, lon = loc['latitude'], loc['longitude']
        map.set_region(lat, lon, MAP_ZOOM, MAP_ZOOM, animated=True)
        map.add_pin(lat, lon, 'Current Location', str((lat, lon)))
    """
	while (active == SPLASH_SCREEN):
		location.start_updates()
		time.sleep(MAP_UPDATE_TIME)
		loc = location.get_location()
		location.stop_updates()
		lat, lon = loc['latitude'], loc['longitude']
		map.set_region(lat, lon, MAP_ZOOM, MAP_ZOOM, animated=True)
		map.add_pin(lat, lon, 'Current Location', str((lat, lon)))
	"""
    location.stop_updates()
    pass
Exemple #3
0
    def setup(self):
        global scale
        self.background_color = 'white'
        self.measuringOn = False  #am i taking in location coordinates?
        self.checkedOnce = 0  #counter for the mode (things happen sequentially so this works)
        # self.locations = [] #array of recorded coordinates
        #self.locations = [(40.4464,-79.9427),(40.4464,-79.9428),(40.4465,-79.9428),(40.4463,-79.9427),(40.4462,-79.9427),(40.4461,-79.9427),(40.446,-79.9427)]
        #self.locations = [(40.444,-79.9446),(40.444,-79.9445),(40.4441,-79.9446),(40.4441,-79.9447),(40.4442,-79.9447),(40.4443,-79.9447),(40.4444,-79.9447),(40.4444,-79.9448),(40.4445,-79.9447),(40.4446,-79.9447),(40.4446,-79.9446),(40.4447,-79.9446),(40.4448,-79.9446),(40.4449,-79.9445),(40.445,-79.9445)]
        #self.locations = [(40.444,-79.9446),(40.444,-79.9445),(40.4441,-79.9446),(40.4441,-79.9447),(40.4442,-79.9447),(40.4449,-79.9449)]
        self.locations = [(40.444, -79.9446), (40.444, -79.9445),
                          (40.4441, -79.9446), (40.4441, -79.9447),
                          (40.4442, -79.9447)]

        self.locationsLeft = []
        self.needMore = False  #need more values
        self.timerCount = 0  #timer to sync everything
        scale = self.size.w / 10  #scaling and UI Design
        self.MoreState = False  #activate by pressing the bottom dot
        self.loopPrompt = False  #if someone travels in a circle
        self.activator = False  #a temporary solution to a significant problem
        self.loopPromptState = 0  #to save circled location or not
        self.currentLoc = None
        #self.query = 'safari-http://maps.apple.com/?q=%s,%s' #apple maps
        self.query = 'safari-https://www.google.com/maps/dir/'  #google maps
        self.compassStat = False  #compass in NSEW mode or degrees
        self.pathState = False
        self.radius = scale
        self.clipState = False
        motion.start_updates()  #motion updates for compass
        location.start_updates()  #location start updates
	def run(self, input=''):
		location.start_updates()
		loc = location.get_location()
		location.stop_updates()
		titleParam = self.get_param_by_name('title').value
		loc['title'] = titleParam or 'Current Location'
		return ElementValue(type = self.get_output_type(), value = loc)
Exemple #5
0
def New(sender):
    label = sender.superview['label1']
    now = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')  # get realtime

    # get GPSdata
    location.start_updates()  # updata GPSdata
    gps = location.get_location()  # get GPSdata
    location.stop_updates()  # stop updating GPSdata

    # visualize GPSdata
    gps_text = ''
    for g in gps:
        gps_text = gps_text + str(g) + ':' + str(gps[g]) + '\n'
        #print(g)
        #print(gps[g])
    label.text = now + '\n' + gps_text  # Substitute GPSdata for UITextView

    # Edit GPS data and savd in csv file
    gps_dict = {'time': now}  # Type dictionary
    gps_dict.update(gps)  # Enter acquisition time first, then add GPS data

    # Create header for csv file
    gps_rows = []
    gps_rows.append(gps_dict)
    parameters = [
        'time', 'latitude', 'longitude', 'altitude', 'timestamp',
        'horizontal_accuracy', 'vertical_accuracy', 'speed', 'course'
    ]
    header = dict([(val, val) for val in parameters])

    # Open csv file and write GPS dictionary data
    with open('gps_log.csv', mode='w') as f:
        writer = csv.DictWriter(f, parameters, extrasaction='ignore')
        writer.writerows(gps_rows)
Exemple #6
0
def get_location():
    location.start_updates()
    time.sleep(1)
    loc = location.get_location()
    location.stop_updates()
    if loc:
        return loc['latitude'], loc['longitude']
def get_location_ios():
    try:
        console.show_activity()
        location.start_updates()
        coordinates = location.get_location()
        location.stop_updates()
        console.hide_activity()
        results = location.reverse_geocode(coordinates)

        if not results:
            results = [{'City': 'N/A', 'Country': 'N/A'}]

        dms_lat, dms_lng = dd2dms(coordinates['latitude'],
                                  coordinates['longitude'])

        return SimpleNamespace(**{
            'latitude': coordinates['latitude'],
            'longitude': coordinates['longitude'],
            'city': results[0]['City'],
            'country': results[0]['Country'],
            'altitude': float(coordinates['altitude']),
            'dms_latitude': dms_lat,
            'dms_longitude': dms_lng,
        })
    except Exception as e:
        print(e.with_traceback)
        print('Não foi possível obter a localização atual.'
              '\nA utilizar predefinição...\n')
        console.hide_activity()
        return None
Exemple #8
0
def get_location():
    import location
    console.show_activity()
    location.start_updates()
    ldata = location.get_location()
    city = location.reverse_geocode(ldata)[0].get('City')
    return city
def btm_Go(sender):

    v = sender.superview
    sender.alpha = 0.1
    if location.is_authorized():
        location.start_updates()
        loc = location.get_location()
        homeGPS = [loc['longitude'], loc['latitude']]
    else:
        homeGPS = [float(v['txtHomeLon'].text), float(v['txtHomeLat'].text)]
    #print(f'\n\nSearch Child:{v["txtChild"].text} Adult:{v["txtAdult"].text} within {v["txtDistance"].text}km, search nearest {v["txtMaxCount"].text} pharmacies from [{homeGPS[0]}, {homeGPS[1]}]')
    v['txtResult'].text = ''
    v['txtResult'].text += f'\n\nSearch Child:{v["txtChild"].text} Adult:{v["txtAdult"].text} within {v["txtDistance"].text}km, search nearest {v["txtMaxCount"].text} pharmacies from [{round(homeGPS[0],3)}, {round(homeGPS[1],3)}]'
    sleep(1)
    allData = getPharmaciesData()

    hits = filterOut(allData,
                     homeGPS,
                     distance=float(v['txtDistance'].text),
                     mask_child=int(v['txtChild'].text),
                     mask_adult=int(v['txtAdult'].text),
                     maxCount=int(v['txtMaxCount'].text))

    v['txtResult'].text += resultText(hits, allData)
    sleep(1)
    sender.alpha = 1.0
Exemple #10
0
def environ_data(sender):
    import motion
    import location

    motion.start_updates()
    location.start_updates()

    x = motion.get_attitude()
    environ['att'].text = str(x) + '\n' + environ['att'].text
    x = motion.get_gravity()
    environ['grav'].text = str(x) + '\n' + environ['grav'].text
    x = motion.get_user_acceleration()
    environ['acc'].text = str(x) + '\n' + environ['acc'].text
    x = motion.get_magnetic_field()
    environ['mag'].text = str(x) + '\n' + environ['mag'].text

    x = location.get_location()
    coord = {'latitude': x['latitude'], 'longitude': x['longitude']}
    print(coord)
    y = location.reverse_geocode(coord)
    print(y)
    environ['geo'].text = str(x)

    motion.stop_updates()
    location.stop_updates()
	def run(self, input=''):
		location.start_updates()
		loc = location.get_location()
		location.stop_updates()
		titleParam = self.get_param_by_name('title').value
		loc['title'] = titleParam or 'Current Location'
		return ElementValue(type = self.get_output_type(), value = loc)
Exemple #12
0
def get_location():
    import location
    console.show_activity()
    location.start_updates()
    ldata = location.get_location()
    city = location.reverse_geocode(ldata)[0].get('City')
    return city
def get_temperature():
	location.start_updates()
	latlong = location.get_location()
	coordinates = {"latitude": latlong["latitude"], "longitude": latlong["longitude"]}
	geo = location.reverse_geocode(coordinates)
	api_call = "http://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&APPID=apiKey".format(coordinates['latitude'],coordinates['longitude'])
	weather = requests.get(api_call)
	response = weather.json()
	temperature = round(1.8*(response['main']['temp'] -273) + 32, 2)
	description = response['weather'][0]['description']
	if description == "overcast clouds":
		speech.say("It appears to be a bit cloudy today", "en-UK")
		speech.say("The current temperature outside is {} degrees".format(temperature),"en-UK")
	elif description == "broken clouds":
		speech.say("Looks like some broken clouds today", "en-UK")
		speech.say("The current temperature outside is {} degrees".format(temperature), "en-UK")
	elif description == "moderate rain":
		speech.say("Appears to be a wet one today, might want to take an umbrella", "en-UK")
		speech.say("The current temperature outside is {} degrees".format(temperature), "en-UK")
	elif description == "light rain":
		speech.say("Appears there will be some light rain, might want to take an umbrella", "en-UK")
		speech.say("The current temperature outside is {} degrees".format(temperature), "en-UK")
	elif description == "clear sky":
		speech.say("Clear skies out right now, looks like a good way to start the day", "en-UK")
		speech.say("The current temperature outside is {} degrees".format(temperature), "en-UK")
	else:
		speech.say("Not sure you gave me enough code, you may need to add to my code base", "en-UK")
def main():
	global locs, path
	
	global own_ui_image,del_ui_image, grp_ui_image										
	own_ui_image = build_pin('emj:Man')
	del_ui_image = build_pin('iob:ios7_trash_outline_32')
	grp_ui_image = crosshair_pin()

	# create main view
	mv = ui.View()
	mv.name = 'Map for RocketBlaster05'
	mv.background_color = 'white'
	mv.present('fullscreen')
	w,h = ui.get_screen_size()
	# Create and present a MapView:
	v = MapView(frame=(0,0,w,h-76))
	mv.add_subview(v)
	v.long_press_action = long_press_action
	v.scroll_action = scroll_action
	path = 'locations.txt'
	locs = {}
	if os.path.exists(path):
		with open(path,mode='rt') as f:
			aux = {}
			content = f.read()
			locs = ast.literal_eval(content)
			# file content is {(lat,lon):data}
			# where data is - 'user'
			#								- 'trash'
			#								- [(lat,lon),(lat,lon),...]
			for pt in locs.keys():
				lat,lon = pt
				if locs[pt] == 'user':
					v.add_pin(lat, lon, 'user point', str((lat, lon)))
				elif locs[pt] == 'trash':
					v.add_pin(lat, lon, 'deleted user point', str((lat, lon)))
				else:
					subtit = ''
					for latg,long in locs[pt]:
						if subtit:
							subtit += '\n'
						subtit += str((latg,long))
					v.add_pin(lat, lon, 'deleted group', subtit)					
	# center on user location				
	import location
	location.start_updates()
	time.sleep(0.1)
	loc = location.get_location()
	location.stop_updates()
	if loc:
		lat, lon = loc['latitude'], loc['longitude']
		# add a purple pin for user's location
		v.user_annotation = v.add_pin(lat, lon, 'Current Location', str((lat, lon)))
		l = [(lat,lon)]	# include user location but not in locs
		for pt in locs.keys():
			lat,lon = pt
			l.append((lat,lon))
		min_lat,min_lon,max_lat,max_lon,d_lat,d_lon = compute_region_param(l)
		v.set_region((min_lat+max_lat)/2, (min_lon+max_lon)/2,1.2*(max_lat-min_lat), 1.2*(max_lon-min_lon), animated=True)	
Exemple #15
0
def place():
    address_dict = location.get_location()
    location.start_updates()

    location.stop_updates()
    latitude = address_dict['latitude']
    longitude = address_dict['longitude']
    api(latitude, longitude)
Exemple #16
0
def place():
	address_dict = location.get_location()
	location.start_updates()
	
	location.stop_updates()
	latitude = address_dict['latitude']
	longitude = address_dict['longitude']
	api(latitude, longitude)
Exemple #17
0
def get_current_lat_lon():
  # Retrieve lat & lon from current locale
  location.start_updates()
  # Delay sometimes improves accuracy
  #time.sleep(1)
  address_dict = location.get_location()
  location.stop_updates()
  return address_dict['latitude'], address_dict['longitude']
 def get_current_lat_lon():
     # Retrieve lat & lon from current locale
     location.start_updates()
     # Delay sometimes improves accuracy
     #time.sleep(1)
     address_dict = location.get_location()
     location.stop_updates()
     return address_dict['latitude'], address_dict['longitude']
Exemple #19
0
def main():
    num_samples = 1000000
    arrayA = []
    arrayM = []
    #arrayG = []
    arrayP = []
    arrayJ = []
    arrayGPS = []  #GPS
    dataArray = []

    CMAltimeter = ObjCClass('CMAltimeter')
    NSOperationQueue = ObjCClass('NSOperationQueue')
    if not CMAltimeter.isRelativeAltitudeAvailable():
        print('This device has no barometer.')
        return
    altimeter = CMAltimeter.new()
    main_q = NSOperationQueue.mainQueue()
    altimeter.startRelativeAltitudeUpdatesToQueue_withHandler_(
        main_q, handler_block)
    motion.start_updates()
    location.start_updates()  # GPS
    print("Logging start...")
    sleep(1.0)
    for i in range(num_samples):
        sleep(0.05)
        a = motion.get_user_acceleration()
        m = motion.get_magnetic_field()
        j = motion.get_attitude()
        gps = location.get_location()  # GPS
        if a[1] > 0.8:
            break
        dataArray.append([relativeAltitude, a[2], m[0], m[1]])
        arrayA.append(a)
        arrayM.append(m)
        arrayJ.append(j)
        arrayP.append(relativeAltitude)
        arrayGPS.append(gps)  #GPS

    motion.stop_updates()
    location.stop_updates()  # GPS
    altimeter.stopRelativeAltitudeUpdates()
    print("Logging stop and Saving start...")
    import pickle
    f = open('yokohama.serialize', 'wb')
    #pickle.dump([arrayA, arrayM, arrayP],f)
    pickle.dump([arrayA, arrayM, arrayJ, arrayP, arrayGPS], f)  #GPS
    f.close
    print("Saving is finished.")
    x_values = [x * 0.05 for x in range(len(dataArray))]
    for i, color, label in zip(range(3), 'rgb', 'XYZ'):
        plt.plot(x_values, [g[i] for g in arrayM], color, label=label, lw=2)
    plt.grid(True)
    plt.xlabel('t')
    plt.ylabel('G')
    plt.gca().set_ylim([-100, 100])
    plt.legend()
    plt.show()
	def update(self):
		location.start_updates()
		time.sleep(0.1)
		loc = location.get_location()
		location.stop_updates()
		if loc:
			lat, lon = loc['latitude'], loc['longitude']
			# update face pin location
			coord = CLLocationCoordinate2D(lat, lon)
			self.user_annotation.setCoordinate_(coord, restype=None,  argtypes=[CLLocationCoordinate2D])
Exemple #21
0
def getGPS():
	if location.is_authorized():
		location.start_updates()
		sleep(1)
		loc=location.get_location()
		dialogs.alert(title='Location updated', message=f'[{loc["longitude"]:.3f},{loc["latitude"]:.3f}]\n or enter manually',button1='Got It', hide_cancel_button=True)
		return [loc['longitude'], loc['latitude']]
	else:
		dialogs.alert(title='Cannot get GPS', message='You have to enable it from setting/privacy or enter manually',button1='Got It', hide_cancel_button=True)
		return HOMEGPS
Exemple #22
0
 def __init__(self, userid=None, panic=False):
     self.userid = userid or uuid.uuid4()
     self.panic = panic
     self.gps_readings = []
     self.send_records = []
     self.next_gps_datetime = None
     self.next_send_datetime = None
     location.start_updates()
     self.send_record()
     self.run()  # a self-running thread
def get_city_and_country():
    location.start_updates()
    loc = location.get_location()
    location.stop_updates()
    try:
        addressDict = location.reverse_geocode(loc)[0]  # grab the first loc
        return 'in {City} {Country}'.format(**addressDict)
    except (TypeError, KeyError) as e:
        print('Error in createCurrentLocationString(): {}'.format(e))
    return ''
Exemple #24
0
    def SetVariables(self):  # Get current location and time
        location.start_updates()  # Get location data from Phone
        loc = location.get_location()
        location.stop_updates()

        if (self.lat == ""):  # Set the Data if it's not already set
            self.lat = str(loc['latitude'])
        if (self.lng == ""):
            self.lng = str(loc['longitude'])
        if (self.timestamp == ""):
            self.timestamp = str(loc['timestamp'])
Exemple #25
0
def getLocation():
    import location
    import datetime
    import time
    "Returns current location"
    location.start_updates()
    time.sleep(3)
    current = location.get_location()
    location.stop_updates()
    address = location.reverse_geocode({'latitude': current['latitude'], 'longitude': current['longitude']})
    loc = address[0]['Street'] + ', ' + address[0]['City'] + ', ' + address[0]['Country'] 
    return loc
Exemple #26
0
def button_startgps(sender):
    location.start_updates()

    if location.is_authorized():
        location.start_updates()
        dialogs.hud_alert('GPS Started', 'success', 1)
    else:
        dialogs.alert(
            'App not authorized to use GPS. Enable GPS in system preferences.',
            'Plz fix',
            'Oh rats... gonna fix that now',
            hide_cancel_button=True)
 def setup(self):
     global scale
     self.background_color = 'white'
     self.measuringOn = False
     self.textState = ''
     self.checkedOnce = 0
     self.locations = []
     self.locationsReversed = []
     self.testCounter = 0
     scale = self.size.w / 10
     #motion start
     location.start_updates()
     #pitch,roll,yaw
     self.R = scale
Exemple #28
0
    def setup(self):
        self.background_color = 'white'
        self.measuringOn = False  #am i taking in location coordinates?
        self.checkedOnce = 0  #counter for the mode (things happen sequentially so this works)
        # self.locations = [] #array of recorded coordinates
        #self.locations = [(40.4464,-79.9427),(40.4464,-79.9428),(40.4465,-79.9428),(40.4463,-79.9427),(40.4462,-79.9427),(40.4461,-79.9427),(40.446,-79.9427)]
        #self.locations = [(40.444,-79.9446),(40.444,-79.9445),(40.4441,-79.9446),(40.4441,-79.9447),(40.4442,-79.9447),(40.4443,-79.9447),(40.4444,-79.9447),(40.4444,-79.9448),(40.4445,-79.9447),(40.4446,-79.9447),(40.4446,-79.9446),(40.4447,-79.9446),(40.4448,-79.9446),(40.4449,-79.9445),(40.445,-79.9445)]
        #self.locations = [(40.444,-79.9446),(40.444,-79.9445),(40.4441,-79.9446),(40.4441,-79.9447),(40.4442,-79.9447),(40.4449,-79.9449)]
        #self.locations = [(40.444,-79.9446),(40.444,-79.9445),(40.4441,-79.9446),(40.4441,-79.9447),(40.4442,-79.9447)]
        self.locations = [(40.429, -79.9594), (40.4288, -79.9598),
                          (40.4285, -79.9601), (40.4284, -79.9605),
                          (40.4281, -79.9608), (40.4279, -79.9612),
                          (40.4277, -79.9616), (40.4275, -79.962),
                          (40.4273, -79.9623), (40.4273, -79.9628),
                          (40.4275, -79.9632), (40.4277, -79.9635),
                          (40.4278, -79.9637), (40.4279, -79.9639),
                          (40.4281, -79.9642), (40.4287, -79.965)]
        #self.locations = [(40.429,-79.9594),(40.4288,-79.9598),(40.4285,-79.9601),(40.4284,-79.9605),(40.4281,-79.9608),(40.4279,-79.9612),(40.4277,-79.9616),(40.4275,-79.962),(40.4273,-79.9623),(40.4273,-79.9628),(40.4275,-79.9632),(40.4277,-79.9635),(40.4278,-79.9637),(40.4279,-79.9639),(40.4281,-79.9642),(40.4287,-79.965),(40.4200,-79.965)]
        #self.locations = [(40.429,-79.9594),(40.4288,-79.9598)]#(40.4285,-79.9601),(40.4284,-79.9605)]#(40.4281,-79.9608),(40.4279,-79.9612),(40.4277,-79.9616),(40.4275,-79.962),(40.4273,-79.9623),(40.4273,-79.9628),(40.4275,-79.9632),(40.4277,-79.9635),(40.4278,-79.9637),(40.4279,-79.9639),(40.4281,-79.9642),(40.4287,-79.965),(40.4200,-79.965)]
        self.photoLocations = []
        self.locationsLeft = []
        self.needMore = False  #need more values
        self.timerCount = 0  #timer to sync everything
        self.MoreState = False  #activate by pressing the bottom dot
        self.loopPrompt = False  #if someone travels in a circle
        self.activator = False  #a temporary solution to a significant problem
        self.loopPromptState = 0  #to save circled location or not
        self.currentLoc = None
        #self.query = 'safari-http://maps.apple.com/?q=%s,%s' #apple maps
        self.query = 'safari-https://www.google.com/maps/dir/'  #google maps
        self.compassStat = False  #compass in NSEW mode or degrees
        self.pathState = False
        self.clipState = False
        self.photoCount = 0
        self.imageMode = False
        self.imageModeOpen = False
        self.photoLibrary = None
        # self.photoLibraryName = self.photoLibrary.local_id

        #Organization/Design
        self.scale = self.size.w / 10  #scaling and UI Design
        self.centerX = self.size.w / 2
        self.centerY = self.size.h / 2
        self.centerX2 = self.size.w / 2
        self.centerY2 = self.size.h * (1 / 2) - self.scale * 3.5

        #updates start
        motion.start_updates()  #motion updates for compass
        location.start_updates()  #location start updates
	def createCurrentLocationString(self):
		import location
		location.start_updates()
		coordinates = location.get_location()
		location.stop_updates()

		try:
			addressDict = location.reverse_geocode(coordinates)[0]  # grab the first loc
			locationString = 'in {City} {Country}'.format(**addressDict)
		except (TypeError, KeyError) as e:
			if traceFlag: print('Error in createCurrentLocationString(): {}'.format(e))
			locationString = ''

		if traceFlag: print 'Returning location string ->>' + locationString
		return locationString
Exemple #30
0
def main():
	# Create and present a MapView:
	v = MapView(frame=(0, 0, 500, 500))
	v.long_press_action = long_press_action
	v.scroll_action = scroll_action
	v.present('sheet')
	# Add a pin with the current location (if available), and zoom to that location:
	import location
	location.start_updates()
	time.sleep(1)
	loc = location.get_location()
	location.stop_updates()
	if loc:
		lat, lon = loc['latitude'], loc['longitude']
		v.set_region(lat, lon, 0.05, 0.05, animated=True)
		v.add_pin(lat, lon, 'Current Location', str((lat, lon)))
Exemple #31
0
def main():
    console.alert('Motion Experiment 2',
                  'yo gang gang, we gonna measure this motion', 'Continue')
    location.start_updates()
    sleep(0.2)
    print('Capturing location data...')
    current = location.get_location()
    alt = current['altitude']
    print(alt)
    while True:
        sleep(1)
        current = location.get_location()
        alt = current['altitude']
        print(alt)
    location.stop_updates()
    print('Capture finished, plotting...')
Exemple #32
0
def getLocation():
    import location
    import datetime
    import time
    "Returns current location"
    location.start_updates()
    time.sleep(3)
    current = location.get_location()
    location.stop_updates()
    address = location.reverse_geocode({
        'latitude': current['latitude'],
        'longitude': current['longitude']
    })
    loc = address[0]['Street'] + ', ' + address[0]['City'] + ', ' + address[0][
        'Country']
    return loc
Exemple #33
0
def main():
    # Create and present a MapView:
    v = MapView(frame=(0, 0, 500, 500))
    v.long_press_action = long_press_action
    v.scroll_action = scroll_action
    v.present('sheet')
    # Add a pin with the current location (if available), and zoom to that location:
    import location
    location.start_updates()
    time.sleep(1)
    loc = location.get_location()
    location.stop_updates()
    if loc:
        lat, lon = loc['latitude'], loc['longitude']
        v.set_region(lat, lon, 0.05, 0.05, animated=True)
        v.add_pin(lat, lon, 'Current Location', str((lat, lon)))
Exemple #34
0
def obter_localizacao():
    try:
        console.show_activity()
        location.start_updates()
        coordinates = location.get_location()
        location.stop_updates()
        console.hide_activity()
        results = location.reverse_geocode(coordinates)
        cidade = results[0]['City']
        pais = results[0]['CountryCode']
        return f'{cidade},{pais}'
    except Exception:
        print('Não foi possível obter a localização atual.'
              '\nA utilizar predefinição...\n')
        console.hide_activity()
        return LOCATION
	def createCurrentLocationString(self):
		import location
		location.start_updates()
		coordinates = location.get_location()
		addressDictionaries = location.reverse_geocode(coordinates)
		mycity = addressDictionaries[0]['City']
		mycountry = addressDictionaries[0]['Country']
		
		# if we can't get city and country not much point to continue
		if mycountry == None or mycity == None:
			return ""
		
		locationString = "in " + mycity + " " + mycountry
		location.stop_updates()
		
		if traceFlag: print 'Returning location string ->>' + locationString
		return locationString
    def createCurrentLocationString(self):
        import location
        location.start_updates()
        coordinates = location.get_location()
        location.stop_updates()

        try:
            addressDict = location.reverse_geocode(coordinates)[
                0]  # grab the first loc
            locationString = 'in {City} {Country}'.format(**addressDict)
        except (TypeError, KeyError) as e:
            if traceFlag:
                print('Error in createCurrentLocationString(): {}'.format(e))
            locationString = ''

        if traceFlag: print 'Returning location string ->>' + locationString
        return locationString
    def setup(self):
        global scale
        self.background_color = 'white'
        self.measuringOn = False
        self.textState = ''
        self.checkedOnce = 0
        self.locations = []
        self.locationsReversed = []
        self.testCounter = 0
        scale = self.size.w / 10

        #compass in NSEW mode or degrees
        self.compassStat = False

        #location start updates
        location.start_updates()
        self.R = scale
    def setup(self):
        global scale
        self.background_color = 'white'
        self.measuringOn = False  #am i taking in location coordinates?
        self.checkedOnce = 0  #counter for the mode (things happen sequentially so this works)
        self.locations = []  #array of recorded coordinates
        self.locationsReversed = []  #Useless?
        self.locationsLeft = []
        self.timerCount = 0  #timer to sync everything
        scale = self.size.w / 10  #scaling and UI Design
        self.MoreState = False  #activate by pressing the bottom dot
        #self.query = 'safari-http://maps.apple.com/?q=%s,%s' #apple maps
        self.query = 'safari-https://www.google.com/maps/dir/'  #google maps
        self.compassStat = False  #compass in NSEW mode or degrees
        self.radius = scale

        motion.start_updates()  #motion updates for compass
        location.start_updates()  #location start updates
Exemple #39
0
def main():
  # Initialize variables
  quoted_output = ''
  output = ''

  # Allow to run script stand alone
  try:
    arg = sys.argv[1]
  except IndexError:
    arg = ''

  print('\nThis script is now gathering your current GPS coordinates, allowing you to text your location and current weather.\n')

  # Start getting the location
  location.start_updates()

  # Allow for 4 loops to improve gps accuracy, if desired
  for i in range(4):
    time.sleep(5)
    my_loc = location.get_location()
    acc = my_loc['horizontal_accuracy']

    # First run
    if i == 0:
      best_loc = my_loc
      best_acc = my_loc['horizontal_accuracy']

      # Setup alert box
      title = 'Accuracy: {} meters.'.format(acc)
      msg = "Take more time to try to improve accuracy?"
      butt1 = "Good enough."
      butt2 = "Try harder (~25 secs)."
      # Allow a cancel
      try:
        answer = console.alert(title, msg, butt1, butt2)
      except:
        console.clear()
        # Call procedure if script called from another app
        if arg:
          do_args(arg, quoted_output, output)
        else:
          sys.exit('Cancelled')

      # If initial accuracy is good enough, give user the chance to break
      if answer == 1:
        break

      # If initial accuracy is not good enough, loop 4 more times and try to improve.
      elif answer == 2:
        pass

    if acc < best_acc:
      best_loc = my_loc
      best_acc = my_loc['horizontal_accuracy']

    print('Best accuracy is now {} meters.'.format(best_acc))

  location.stop_updates()

  lat = best_loc['latitude']
  lon = best_loc['longitude']

  # Setup alert box
  title = 'Select Type of GPS Data To Send:'
  butt1 = "Address"
  butt2 = "Coordinates"

  # Allow a cancel
  try:
    ans = console.alert(title,'', butt1, butt2)
  except:
    console.clear()
    # Call procedure if script called from another app
    if arg:
      do_args(arg, quoted_output, output)
    else:
      sys.exit('Cancelled')

  # Set up for Markdown if called from apps
  bold = '**' if arg else ''
  w_data = get_weather(lat, lon, bold)

  if ans == 1:
    data_type = 'address and weather were'
    a = location.reverse_geocode({'latitude': lat,'longitude': lon})

    b = '{0}{Street}, {City} {State} {ZIP}{0}, {Country}'.format(bold, **a[0])

    datestamp = datetime.datetime.fromtimestamp(best_loc['timestamp'])
    d = datestamp.strftime('%A, %m-%d-%Y @ %I:%M:%S %p')

    output = 'My location as of {} is {}, with an accuracy of about {} meters.'.format(d, b, best_acc)

  elif ans == 2:
    data_type = 'coordinates and weather were'
    output = 'Click on http://maps.apple.com/?q={},{} for a map to my current location.'.format(lat, lon)

  output = output + w_data
  quoted_output = urllib.quote(output, safe = '')

  # Call procedure if script called from another app
  if arg:
    do_args(arg, quoted_output, output)

  # Code below is excuted if script called as stand alone from Pythonista...

  # Check if Launch Center Pro is installed...
  if webbrowser.can_open('launch://'):
    # Setup alert box
    title = 'Send Your GPS & Weather Data To:'
    butt1 = "Clipboard"
    butt2 = "SMS Msg"
    butt3 = "Email"

    # Allow a cancel
    try:
      ans = console.alert(title, '', butt1, butt2, butt3)
    except:
      console.clear()
      sys.exit('Cancelled')

    if ans == 1:
      clipboard.set('')
      clipboard.set(output + w_data)
      console.clear()
      print('Your GPS {} copied to the clipboard.'.format(data_type))
    elif ans == 2:
      cmd = 'launch://messaging?body={}'.format(quoted_output)
      webbrowser.open(cmd)
      console.clear()
    elif ans == 3:
      cmd = 'launch://email?body={}'.format(quoted_output)
      webbrowser.open(cmd)
      console.clear()
  else:
    # Output to clipboard only
    clipboard.set(output)
    console.clear()
    print('Your GPS {} copied to the clipboard.'.format(data_type))

  sys.exit('Finished!!')
def getLocation():
    location.start_updates()
    time.sleep(1)
    currLoc = location.get_location()
    location.stop_updates() # stop GPS hardware ASAP to save battery
    return currLoc
Exemple #41
0
		
	@on_main_thread
	def add_pin(self, lat, lon, title, subtitle=None, select=False):
		'''Add a pin annotation to the map'''
		MKPointAnnotation = ObjCClass('MKPointAnnotation')
		coord = CLLocationCoordinate2D(lat, lon)
		annotation = MKPointAnnotation.alloc().init().autorelease()
		annotation.setTitle_(title)
		if subtitle:
			annotation.setSubtitle_(subtitle)
		annotation.setCoordinate_(coord, restype=None, argtypes=[CLLocationCoordinate2D])
		self.mk_map_view.addAnnotation_(annotation)
		if select:
			self.mk_map_view.selectAnnotation_animated_(annotation, True)
	
	@on_main_thread
	def remove_all_pins(self):
		'''Remove all annotations (pins) from the map'''
		self.mk_map_view.removeAnnotations_(self.mk_map_view.annotations())
		
if __name__ == '__main__':
	m = MapView()
	location.start_updates()
	loc = location.get_location()
	location.stop_updates()
	m.add_pin(lat = loc['latitude'], lon = loc['longitude'],title='Test')
	m.mk_map_view.setShowsUserLocation_(True)
	m.present()


def getLocation():
	location.start_updates()
	currLoc = location.get_location()
	location.stop_updates()
	return currLoc
Exemple #43
0
def get_lat_lon():
    location.start_updates()
    loc_dict = location.get_location()
    location.stop_updates()
    return (loc_dict['latitude'], loc_dict['longitude'])