def get_line(token, line_code): """ 获取线路信息 :param token: :param line_code: :return: """ user = hgetall(get_token(token)) if (not user) or int(user['role_type']) not in cs.SELECT_LINE_ROLE: return cs.AUTH_ERROR, None line_obj = Line.query.filter_by(line_code=line_code).first() if not line_obj: return cs.LINE_CODE_ERR, {'line_code': line_code} line = {} line['line_code'] = line_obj.line_code line['line_name'] = line_obj.line_name line['origin_name'] = get_location(line_obj.origin_code).location_name line['destination_name'] = get_location( line_obj.destination_code).location_name line['line_status'] = line_obj.line_status line['line_type'] = line_obj.line_type line['line_kilometre'] = line_obj.line_kilometre line['line_runtime'] = line_obj.line_runtime line['location_number'] = line_obj.location_number line['location_infos'] = [] # 获取径停点信息 location_objs = LineLocations.query.filter_by(fk_line_code=line_code).all() if location_objs: for item in location_objs: location_name = get_location(item.location_code).location_name line['location_infos'].append({ 'location_name': location_name, 'sequence': item.sequence }) return cs.OK, line
def get_info(view, date): i = views.index(view) if i != 4: j = view['table'].selected_row[1] entryType = {1: 'alarm', 2: 'event', 3: 'data', 4: 'sensor'} carbs = as_int(view['carbsfield'].text) if view['carbsfield'] else None insulin = as_float( view['insulinfield'].text) if view['insulinfield'] else None food = format_food(view['foodfield'].text) if view['foodfield'] else None act_ins = as_float( view['actinsfield'].text) if view['actinsfield'] else None isig = as_float(view['isigfield'].text) if view['isigfield'] else None dt = view['dtfield'].text if view['dtfield'] else None status = None if i == 2: k = view['table2'].selected_row[1] status = tables[4][k] if i == 4: ref = view['reffield'].text if view['reffield'].text else None lot = view['lotfield'].text if view['lotfield'].text else None info = { 'type': entryType[i], 'dateTime': str(date), 'REF': ref, 'LOT': lot, 'secondRound': view['recycle'].value, 'initSuccess': view['success'].value, 'location': location.get_location() } else: info = { 'type': entryType[i], 'dateTime': str(date), 'IG': as_int(view['igfield'].text), 'trend': as_int(view['trendfield'].text), 'BG': as_int(view['bgfield'].text), 'details': tables[i][j], 'status': status, 'carbs': carbs, 'insulin': insulin, 'activeInsulin': act_ins, 'food': food, 'isig': isig, 'dt': dt, 'location': location.get_location() } fo = lambda x: True if x == 0 else x info = {key: info[key] for key in info.keys() if fo(info[key])} return info
def get_cargo_order(token, cargo_order_number): """ 查看货物订单详情 :param token: :param cargo_order_number: :return: cs.OK, object """ user = hgetall(get_token(token)) if not user: return cs.AUTH_ERROR, None # 货物订单信息 cargo_order_obj = CargoOrder.query.filter_by( cargo_order_number=cargo_order_number).first() if not cargo_order_obj: return cs.NOT_CARGO_ORDER, None cargo_order = {} cargo_order['cargo_order_number'] = cargo_order_obj.cargo_order_number cargo_order['origin_name'] = get_location( cargo_order_obj.origin_code).location_name cargo_order['destination_name'] = get_location( cargo_order_obj.destination_code).location_name cargo_order['order_status'] = cargo_order_obj.order_status cargo_order['order_type'] = cargo_order_obj.order_type cargo_order['cargo_name'] = cargo_order_obj.cargo_name cargo_order['cargo_volume'] = cargo_order_obj.cargo_volume cargo_order['cargo_weight'] = cargo_order_obj.cargo_weight cargo_order[ 'specified_arrival_time'] = cargo_order_obj.specified_arrival_time cargo_order['consignor_name'] = cargo_order_obj.consignor_name cargo_order['consignor_telephone'] = cargo_order_obj.consignor_telephone cargo_order['consignee_name'] = cargo_order_obj.consignee_name cargo_order['consignee_telephone'] = cargo_order_obj.consignee_telephone cargo_order['create_time'] = cargo_order_obj.create_time # 货物订单流 cargo_order['order_flows'] = get_order_flows(cargo_order_number) # 货物订单操作日志 cargo_order['order_operations'] = get_operation_records(cargo_order_number) # 推送线路信息 line_nos = json.loads(rget(push_line(cargo_order_number))) line_list = [] for line_no in line_nos: line_obj = Line.query.filter_by( line_code=line_no, line_status=cs.LINE_STATUS_INFO[u"启用"]).first() line_dict = {} if line_obj: line_dict['line_code'] = line_obj.line_code line_dict['line_name'] = line_obj.line_name line_dict['line_kilometre'] = line_obj.line_kilometre line_dict['line_runtime'] = line_obj.line_runtime line_list.append(line_dict) cargo_order['push_lines'] = line_list # cargo_order['push_lines'] = rget(push_line(cargo_order_number)) return cs.OK, cargo_order
def get_line_locations(token, origin_code, destination_code, location_code, location_status, page_index, page_size): """ 获取转运中心列表 :param token: :param origin_code: :param destination_code: :param location_code: :param location_status: :param page_index: :param page_size: :return: cs.OK,{} """ user = hgetall(get_token(token)) if (not user) or int(user['role_type']) not in cs.SELECT_LINE_ROLE: return cs.AUTH_ERROR, None statment = '1=1' if origin_code: statment += " and (line_location.origin_code = '%s')" % origin_code if destination_code: statment += " and (line_location.destination_code = '%s')" % destination_code if location_code: statment += " and (line_location.location_code = '%s')" % location_code if location_status: statment += " and (line_location.location_status = '%s')" % location_status else: statment += " and (line_location.location_status = '%s')" % cs.LINE_STATUS_INFO[ u"启用"] print statment line_locations = LineLocations.query.filter(statment).order_by( LineLocations.update_time.desc()).paginate(page_index, page_size, False).items lines_count = db.session.query(LineLocations.id).filter(statment).count() rasult = {'line_objs': [], 'line_count': lines_count} for item in line_locations: line = {} line_obj = Line.query.filter_by(line_code=item.fk_line_code).first() line['line_code'] = line_obj.line_code line['line_name'] = line_obj.line_name line['origin_name'] = get_location(line_obj.origin_code).location_name line['destination_code'] = get_location( line_obj.destination_code).location_name line['line_kilometre'] = line_obj.line_kilometre line['line_runtime'] = line_obj.line_runtime line['location_number'] = line_obj.location_number rasult['line_objs'].append(line) return cs.OK, rasult
def get_lines(token, line_code, origin_code, destination_code, line_status, line_type, page_index, page_size): """ 货物线路列表 :param token: :param line_code: :param origin_code: :param destination_code: :param line_status: :param line_type: :param page_index: :param page_size: :return: cs.OK,{} """ user = hgetall(get_token(token)) if (not user) or int(user['role_type']) not in cs.SELECT_LINE_ROLE: return cs.AUTH_ERROR, None statment = '1=1' if line_code: statment += " and (line.line_code = '%s')" % line_code if origin_code: statment += " and (line.origin_code = '%s')" % origin_code if destination_code: statment += " and (line.destination_code = '%s')" % destination_code if line_type: statment += " and (line.line_type = '%s')" % line_type if line_status: statment += " and (line.line_status = '%s')" % line_status else: statment += " and (line.line_status = '%s')" % cs.LINE_STATUS_INFO[ u"启用"] lines_objs = Line.query.filter(statment).order_by( Line.update_time.desc()).paginate(page_index, page_size, False).items logger.info('get_lines statment is {}'.format(statment, )) lines_count = db.session.query(Line.id).filter(statment).count() rasult = {'line_objs': [], 'line_count': lines_count} for item in lines_objs: line = {} line['line_code'] = item.line_code line['line_name'] = item.line_name line['origin_name'] = get_location(item.origin_code).location_name line['destination_code'] = get_location( item.destination_code).location_name line['line_kilometre'] = item.line_kilometre line['line_runtime'] = item.line_runtime line['location_number'] = item.location_number rasult['line_objs'].append(line) return cs.OK, rasult
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 __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
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...')
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)
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 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(): import location console.show_activity() location.start_updates() ldata = location.get_location() city = location.reverse_geocode(ldata)[0].get('City') return city
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
def move(self, dir): new_location = self.loc._neighbor(dir) if new_location is None: print("You are out of Manhattan") else: self.loc = get_location(new_location) self.look()
def notify(): icon_path = "/home/dushyant/Desktop/Github/Weather-Notifier/weathernotifier/Weather-icon.png" place = get_location() resp = get_weather(place) print resp result = '' result += "Place : " + str(resp[0]["Place"]) result += "\nStatus : " + str(resp[6]) result += "\nCurrent Temperature (Celcius) : " + str(resp[1]["temp"]) result += "\nMax Temperature (Celcius) : " + str(resp[1]["temp_max"]) result += "\nMin Temperature (Celcius) : " + str(resp[1]["temp_min"]) result += "\nWind Speed (m/s) : " + str(resp[2]["speed"]) result += "\nHumidity (%) : " + str(resp[3]) result += "\nPressure (hpa) : " + str(resp[4]["press"]) result += "\nCloud Cover (%) : " + str(resp[5]) # print result # Notification Tool notify2.init("Weather Notifier") n = notify2.Notification("Weather Details", icon=icon_path) n.update("Weather Details", result) n.show()
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
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)
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 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)
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 place(): address_dict = location.get_location() location.start_updates() location.stop_updates() latitude = address_dict['latitude'] longitude = address_dict['longitude'] api(latitude, longitude)
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 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 ''
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
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])
def check_location(self) -> bool: try: input('\nЧтобы идти дальше нажми Enter >') except UnicodeDecodeError: animated_print( '\nНу, просили же только Enter нажать. Ладно, идем дальше.') os.system('cls||clear') location = get_location(self.state) animated_print(f'\nЛокация: {location}') return True
def result(): if request.method == 'POST': result = request.form.to_dict() result["city"] = get_location() result["category"] = get_categories(result["Pain"]) result["Location"] = request.form.get("Location") print(str(request.form.get("Location"))) db.insert(result) similar = similar_categories(result["category"]) return render_template("result.html",result = result, similar = similar)
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'])
def get_location(): """ Returns the latitude and longitude of the current location """ try: import location my_location = location.get_location() return [my_location['latitude'], my_location['longitude']] except: return [LATITUDE, LONGITUDE]
def add_waypoint(sender): if v['switch1'].value: curr_location = location.get_location() if v.waypoints == []: v.waypoints = np.array([[curr_location['latitude'], curr_location['longitude']]]) else: v.waypoints = np.append(v.waypoints, np.array([[curr_location['latitude'], curr_location['longitude']]]), axis=0) v['waypointList'].text = repr(v.waypoints) else: pass
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 message(name: str): msg = "Login alert for {}.\nThe following email was sent " \ "because a login was detected on your device on {} at {}. " \ "Your files are now unlocked and accessible from the " \ "location it was logged in on.\n\nIf this was you, disregard " \ "this email. However, if this was not, consider " \ "taking a look at your security " \ "settings. It was " \ "accessed at {}".format(name, datetime.today().strftime('%Y-%m-%d'), datetime.today().strftime('%H:%M:%S'), location.get_location()) return msg
def setTargetButton(sender): global Hint global CurrentHintID global CurrentHint global mustSave loc = location.get_location() CurrentHint[HINT_LONGITUDE] = loc['longitude'] CurrentHint[HINT_LATITUDE] = loc['latitude'] sound.play_effect('ui:click1', 1.0) mustSave = True refreshEditorItems()
def run_nightshift(): print "Trying to run nightshift" location_params = get_location() wallpaper_params = get_wallpaper_params() sunrise, sunset = get_sunrise_sunset(location_params["latitude"], location_params["longitude"]) step_count = wallpaper_params["step_count"] img_format = wallpaper_params["format"] last_id = -1 while True: current_time = datetime.datetime.now().time() last_id = update_nightshift(current_time, sunrise, sunset, step_count, img_format, last_id) time.sleep(15)
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 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)))
def add_waypoint(sender): if v['switch1'].value: current = location.get_location() curr_location = np.array([current['latitude'], current['longitude']]) heading = calculate_heading(mag) num_sides = int(v['num_sides'].text) dist_per_side = int(v['dist_per_side'].text) v.waypoints = geoCalc.get_polygon_waypoints(curr_location, heading, num_sides, dist_per_side) v['waypointList'].text = repr(v.waypoints) else: pass
def test_nightshift(): print "Testing nightshift: " location_params = get_location() wallpaper_params = get_wallpaper_params() sunrise, sunset = get_sunrise_sunset(location_params["latitude"], location_params["longitude"]) step_count = wallpaper_params["step_count"] img_format = wallpaper_params["format"] print "Sunrise is at {0} and sunset at {1}".format(sunrise, sunset) current_time = datetime.time(minute=2) start_time = datetime.time() last_id = -1 while current_time != start_time: current_time = (datetime.datetime.combine(datetime.datetime.today(), current_time) + datetime.timedelta(seconds=15)).time() last_id = update_nightshift(current_time, sunrise, sunset, step_count, img_format, last_id)
location.start_updates() time.sleep(3) last_time=time.time() while True: # current = location.get_location() # # long_lat = str(current['timestamp']) + ', ' + str(current['latitude']) + ', ' + str(current['longitude']) # # print long_lat delta_t = time.time() - last_time if delta_t > 3.: current = location.get_location() long_lat = str(current['timestamp']) + ', ' + str(current['latitude']) + ', ' + str(current['longitude']) print long_lat #location.stop_updates() last_time = time.time() current = None location.stop_updates() location.start_updates()
def getLocation(): location.start_updates() time.sleep(1) currLoc = location.get_location() location.stop_updates() # stop GPS hardware ASAP to save battery return currLoc
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 get_gps_reading(self): self.gps_readings.append(location.get_location()) self.next_gps_datetime = datetime.datetime.now() + self.gps_timedelta
@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()
"\n" + "Google: https://google.com/maps/place/$lat,$long/@$lat,$long,12z\n" + "\n" + "Open Street Map: http://www.openstreetmap.org/?mlat=$lat&mlon=$long#map=12/$lat/$long/m\n" + "\n" + "TomTom: tomtomhome://geo:action=show&lat=$lat&long=$long&name=Pin\n" + "\n" + "Waze: waze://?ll=$lat,$long&navigate=yes"); params = { "street" : address.get("Street"), "city" : address.get("City"), \ "zip" : address.get("ZIP"), \ "country" : address.get("Country"), "lat" : lat, "long" : long}; return tpl.substitute(params); location.start_updates(); here = location.get_location(); location.stop_updates(); lat = here.get("latitude"); long = here.get("longitude"); address = location.reverse_geocode(here)[0]; note = locationToNote(address, lat, long); ofnote = {"name" : address.get("Street"), "note" : note}; webbrowser.open("omnifocus:///add?" + urllib.urlencode(ofnote).replace('+','%20'));
def getLocation(): location.start_updates() currLoc = location.get_location() location.stop_updates() return currLoc
def get_lat_lon(): location.start_updates() loc_dict = location.get_location() location.stop_updates() return (loc_dict['latitude'], loc_dict['longitude'])