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
Example #2
0
	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)
Example #3
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)
Example #4
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
Example #5
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()
Example #6
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
	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)
Example #8
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 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)	
Example #10
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)
Example #11
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']
Example #13
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)
Example #14
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])
Example #16
0
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 ''
Example #17
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'])
Example #18
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
	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
Example #20
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
Example #21
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)))
Example #22
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...')
Example #23
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)))
Example #24
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
	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
Example #27
0
def switchToRouteRecord(sender):
    active = ROUTE_RECORD
    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()

    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)))

    pass
Example #28
0
 async def authorized(self, instance, async_lib):
     location.start_updates()
     try:
         while True:
             timestamp = time.time()
             if not location.is_authorized():
                 await self.authorized.write(value=[0], timestamp=timestamp)
             else:
                 info = location.get_location()
                 await self.authorized.write(value=[1], timestamp=timestamp)
                 latitude = info.get('latitude', 0.)
                 longitude = info.get('longitude', 0.)
                 timestamp = info.get('timestamp', timestamp)
                 await self.coordinates.write(value=[latitude, longitude],
                                              timestamp=timestamp)
                 loc = location.reverse_geocode(
                     dict(latitude=latitude, longitude=longitude))
                 await self.location.write(value=[str(loc)],
                                           timestamp=timestamp)
             await async_lib.library.sleep(5.0)
     finally:
         location.stop_updates()
Example #29
0
	def newgps(self, view) :
		# GPSデータを取得
		location.start_updates()
		gps = location.get_location()
		location.stop_updates()
		
		# visualize all GPSdata
		#gps_text = ''
		#for g in gps :
		#	gps_text = gps_text + str(g) + ':' + str(gps[g]) + '\n'
		#label.text = gps_text
		
		# senderを使う場合
		#sender.superview['alti_text'].text = str(gps['altitude']) # 高度
		#sender.superview['longi_text'].text = str(gps['longitude']) # 経度
		#sender.superview['lati_text'].text = str(gps['latitude']) # 緯度
		
		view['alti_text'].text = str(gps['altitude']) # 高度
		view['longi_text'].text = str(gps['longitude']) # 経度
		view['lati_text'].text = str(gps['latitude']) # 緯度
		
		# csv用の辞書作成
		gps_dict = {'altitude':gps['altitude'],'longitude':gps['longitude'],'latitude':gps['latitude']}
		return gps_dict
Example #30
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!!')
Example #31
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
Example #33
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_(False)
	m.present()
	
#==============================

Example #34
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()


Example #35
0
	def will_close(self):
		# This will be called when a presented view is about to be dismissed.
		# You might want to save data here.
		location.stop_updates()
		motion.stop_updates()
Example #36
0
def get_lat_lon():
    location.start_updates()
    loc_dict = location.get_location()
    location.stop_updates()
    return (loc_dict['latitude'], loc_dict['longitude'])
Example #37
0
def getLocation(sender):
    location.start_updates()
    loc = location.get_location()
    location.stop_updates()

    label1.text += str(loc)
def getLocation():
	location.start_updates()
	currLoc = location.get_location()
	location.stop_updates()
	return currLoc
Example #39
0
import location  # iOS location information library

if location.is_authorized():
    location.start_updates(
    )  # start checking for location information, may speed up response to ‘get_location()’
    print(location.get_location())

    address = {
        'Street': 'Victoria Gardens Blvd',
        'City': 'Port Orange',
        'Country': 'USA'
    }
    result = location.geocode(address)

    print("Port Orange: " + str(result))

    print("Reverse geocode: " +
          str(location.reverse_geocode(location.get_location())))

    location.stop_updates()  # stop checking the current location

print('\n')

import clipboard

text = clipboard.get()
print("Clipboard Data: " + str(text))

text = clipboard.set('')
print("Clipboard Data: " + str(text))
Example #40
0
	def __exit__(self):
		location.stop_updates()
Example #41
0
def location_enabled():
	location.start_updates()
	yield
	location.stop_updates()
Example #42
0
if True:
    distance = 0  #total distance travelled
    startTime = time.time()  #set starting time of timer

    #to calculate distances two coordinates are needed. coord1 is the coordinate I was at, and coord2 is the coordinate I am at now

    coord2 = (location.get_location()['longitude'],
              location.get_location()['latitude'])
    now = time.time()
    while now - startTime < 10.:
        coord1 = coord2  #set coord1 to coord2 from previous loop repetition
        coord2 = (location.get_location()['longitude'],
                  location.get_location()['latitude']
                  )  #get current coordinates
        distance += distanceFromCoords(
            coord1[0], coord1[1], coord2[0], coord2[1]
        )  #add distance between coord1 and coord2 to the total distance travelled

        print('\n', round(now - startTime), ' dist=', distance, ' lat/long= ',
              coord2[0], ',', coord2[1])

        if now - startTime < 1.:
            #time.sleep(.1)
            time.sleep(1)
        else:
            time.sleep(1)
        now = time.time()

location.stop_updates()  #I know, this never gets executed :D