def get_location(meta): if meta != None: # Dictionary of location data # ccc: pick results[0] right away results = location.reverse_geocode(meta)[0] name = results['Name'] try: street = results['Thoroughfare'] except KeyError: street = '' try: city = results['City'] except KeyError: city = '' try: state = results['State'] except KeyError: state = '' try: zipcode = results['ZIP'] except KeyError: zipcode = '' # If name is an address then use street name only, because address is close but not always exact as to where location actually is. if find_number(name): name = street the_location = '{}, {} {} @ {}'.format(city, state, zipcode, name) else: the_location = '' return the_location
def GetLocation(meta): gps = meta.get('{GPS}') if gps: lat = gps.get('Latitude',0.0) lon = gps.get('Longitude',0.0) lat_ref = gps.get('LatitudeRef', '') lon_ref = gps.get('LongitudeRef', '') # Southern hemisphere if lat_ref == 'S': lat = -lat # Western hemisphere if lon_ref == 'W': lon = -lon coordinates = {'latitude':lat, 'longitude':lon} # Dictionary of location data # ccc: pick results[0] right away results = location.reverse_geocode(coordinates)[0] name = results['Name'] street = results['Thoroughfare'] city = results['City'] state = results['State'] zipcode = results['ZIP'] # If name is an address then use street name only if find_number(name): name = street theLocation = '{}, {} {} @ {}'.format(city, state, zipcode, name) else: theLocation = '' return theLocation
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 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 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 GetLocation(meta): gps = meta.get('{GPS}', None) if gps: lat = gps.get('Latitude',0.0) lon = gps.get('Longitude',0.0) lat_ref = gps.get('LatitudeRef', '') lon_ref = gps.get('LongitudeRef', '') # Southern hemisphere if lat_ref == 'S': lat = -lat # Western hemisphere if lon_ref == 'W': lon = -lon coordinates = {'latitude':lat, 'longitude':lon} # Dictionary of location data # ccc: pick results[0] right away results = location.reverse_geocode(coordinates)[0] name = results['Name'] street = results['Thoroughfare'] city = results['City'] state = results['State'] zipcode = results['ZIP'] # If name is an address then use street name only if find_number(name): name = street theLocation = '{}, {} {} @ {}'.format(city, state, zipcode, name) else: theLocation = '' return theLocation
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 success_report(a, i, mfg, dt, gps): #fstr = f'{i:4}: SUCC\t{mfg:5}\t{dt}\t{gps}\t{a.creation_date}' results = None if a.location != None: results = location.reverse_geocode(a.location) fs = f'{i:4}: SUCC\t{a.creation_date}\t{a.location}\t{results}' print(fs) return
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 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 main(): coordinates = location.get_location() fullAddress = location.reverse_geocode(coordinates) street = fullAddress[0]['Street'] zip = fullAddress[0]['ZIP'] city = fullAddress[0]['City'] state = fullAddress[0]['State'] address = 'Your location is' + ' ' + street + ' ' + ' ' + zip + ' ' + city + ' ' + state return address
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 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 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
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 get_location(meta): if meta != None: # Dictionary of location data results = location.reverse_geocode(meta)[0] name = results['Name'] street = results.get('Thoroughfare', '') city = results.get('City', '') state = results.get('State', '') zipcode = results.get('ZIP', '') # If name is an address then use street name only, because address is close but not always exact as to where location actually is. if find_number(name): name = street the_location = '{}, {} {} @ {}'.format(city, state, zipcode, name) else: the_location = '' return the_location
def resolveAddress(): global user_address if loc.is_authorized(): _ad = loc.reverse_geocode(loc.get_location()) _street = _ad[0]['Street'].split() _city = _ad[0]['City'] _state = _ad[0]['State'] _zip = _ad[0]['ZIP'] _streetNo = _street[0] if '–' in _streetNo: _streetNo = _streetNo.split('–')[0] _street[0] = _streetNo user_address = (_street[0] + ' ' + _street[1] + ' ' + _street[2] + ' ' + _street[3] + ', ' + _city + ", " + _state + ' ' + _zip) #print(user_address) return True else: user_address = currentAddy() return True
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()
import smtplib, location, time from email.mime.text import MIMEText # SMTP-сервер server = "ServerAdress" port = 22 # Станартный порт user_name = "*****@*****.**" user_passwd = "Password" send_name = '*****@*****.**' s = smtplib.SMTP(server, port) s.ehlo() s.starttls() s.ehlo() s.login(user_name, user_passwd) location.start_updates() time.sleep(10) location.stop_updates() loc = location.get_location() addr = location.reverse_geocode(loc)[0] Text = 'Я нахожусь по адресу: ' + addr['Country'] + ', город ' + addr[ 'City'] + ', ' + addr['Name'] letter = MIMEText(Text, 'html', 'utf-8') letter['Subject'] = 'Текущая геолокация' letter['To'] = send_name letter = letter.as_string() s.sendmail(user_name, send_name, letter) s.close
# https://gist.github.com/drdrang/8329584 # A Pythonista script that gets the address, latitude, and longitude and sends them to Drafts. import sys import location, time import urllib, webbrowser # Handle argument, if present. try: a = sys.argv[1] except IndexError: a = '' # Get the GPS info. location.start_updates() time.sleep(5) loc = location.get_location() addr = location.reverse_geocode(loc) location.stop_updates() # Assemble the output. spot = '''%s%s %s, %s %s %.4f, %.4f''' % \ (a, addr[0]['Street'], addr[0]['City'], addr[0]['State'], addr[0]['ZIP'], loc['latitude'], loc['longitude']) # Send output to Drafts. webbrowser.open("drafts4://x-callback-url/create?text=" + urllib.quote(spot.encode('utf-8')))
def run(self, input): self.status = 'complete' loc = location.reverse_geocode(input.value) return ElementValue(type = self.get_output_type(), value = loc)
def getStreetAddress(loc = getLocation()): return location.reverse_geocode(loc)[0]
import location, requests, speech loc = location.reverse_geocode(location.get_location()) city_country = "{City},{Country}".format(**loc[0]) print(f"Weather in {city_country}:") APPID = "beb97c1ce62559bba4e81e28de8be095&q=" URL = f"http://api.openweathermap.org/data/2.5/weather?APPID={APPID}&q=" weather = requests.get(URL + city_country).json() print("\n".join(f"{key}: {value}" for key, value in weather.items())) speech.say( f"It is currently {weather['weather'][0]['main']} in {city_country}.")
current_time = int(time.time()) # tries to get the lat and long for the phone. If it fails, data for saved # default lat and long is used instead try: lat_long_dict = location.get_location() latitude = lat_long_dict.get('latitude') longitude = lat_long_dict.get('longitude') except: console.alert('Could not find GPS data') latitude = wc_config.default_latitude longitude = wc_config.default_longitude lat_long_dict = {'latitude': latitude, 'longitude': longitude} location_dict_list = location.reverse_geocode(lat_long_dict) location_dict = location_dict_list[0] # get address of current location to display in the alert from lat and long street = location_dict.get('Street') city = location_dict.get('City') state = location_dict.get('State') alert_message = street + '\n' + city + ', ' + state + '\n\n' res = requests.get('https://api.darksky.net/forecast/' + wc_config.api_key + '/' + str(latitude) + ',' + str(longitude) + ',' + str(current_time)) # parse json into way more data than necessary, but it might be handy later
# - <pythonista://insert_location.py?action=run&argv=[[draft]]&argv=address> # (Will insert the address of your current location.) # - <pythonista://insert_location.py?action=run&argv=[[draft]]&argv=link> # (Will insert a Google Maps link to your current location.) import location import re import sys import urllib import webbrowser a = re.sub(r"(.*\S)$", "\\1 ", sys.argv[1]) a = re.sub(r" \n$", "\n", a) location.start_updates() b = location.get_location() location.stop_updates() if sys.argv[2] == "address": b = location.reverse_geocode({"latitude": b["latitude"], "longitude": b["longitude"]}) b = b[0]["Street"] + ", " + b[0]["ZIP"] + " " + b[0]["City"] + ", " + b[0]["Country"] # b = re.sub(r"(P|p)latz", "\\1l.", b) # b = re.sub(r"(S|s)trasse", "\\1tr.", b) # b = re.sub(r", Switzerland", "", b) b = b.encode("utf-8") else: b = "<http://maps.google.com/?q=" + str(b["latitude"]) + "," + str(b["longitude"]) + ">" c = a + b webbrowser.open("drafts4://x-callback-url/create?text=" + urllib.quote(c))
def main(): #album_name = 'My Photo Stream' #albums = photos.get_albums() album_name = 'Camera Roll' albums = photos.get_smart_albums() album = get_album_byname(albums, album_name) print('Album: {}'.format(album.title)) if type(album) != photos.AssetCollection: sys.exit('Album not found!') print('Photo Count: {}'.format(len(album.assets))) i = 0 good = bad = heic = other = good_addr = bad_addr = 0 grg = True for a in album.assets: try: i += 1 ''' if i%25 == 0: time.sleep(5) ''' #p = a.get_image() #exif = exif_info.get_exif_data(p) dts = a.creation_date revgeo = None if a.location != None: revgeo = location.reverse_geocode(a.location) if len(revgeo) > 0: good_addr += 1 grg = True else: bad_addr += 1 grg = False #time.sleep(0.75) print(f'{i:4}: loc: {a.location}\t geo: {grg}\t{dts}\t{revgeo}') except KeyError as e: except_report(a, i, 'KEY ', e) bad += 1 except AttributeError as e: root, ext = get_filename(a) if ext == '.HEIC': heic += 1 except_report(a, i, 'ATTRIB', (f'* Filename: {root:15}\t' + str(e))) else: other += 1 except_report(a, i, 'ATTRIB', (f'. Filename: {root:15}\t' + str(e))) bad += 1 else: try: ''' dt = exif_info.get_datetimestamp(exif) mfg = exif_info.get_camera_mfg(exif) gps = exif_info.get_lat_lon(exif) ''' #success_report(a, i, None, None, None) #time.sleep(1) good += 1 except KeyError as e: except_report(a, i, 'KEY ', e) bad += 1 except AttributeError as e: except_report(a, i, 'ATTR', e) bad += 1 #--- End of asset loop print(f'Good: {good}') print(f'Bad : {bad}') print(f'HEIC: {heic}') print(f'other: {other}') print(f'Good Geo: {good_addr}') print(f'Bad Geo: {bad_addr}')
#check for internet #wifi_ip = socket.gethostbyname(socket.gethostname()) #print(wifi_ip) console.clear() location.start_updates() currentGeoLoc = location.get_location() location.stop_updates() print("----> GeoLoc") print(currentGeoLoc) print("----> GeoLoc end") addrList = location.reverse_geocode(currentGeoLoc) addrDict = addrList[0] print(addrDict.items()) print("------------") locStr = "" space = " " #check and add sublocality if 'SubLocality' in addrDict.keys(): locStr += addrDict['SubLocality'] else: print("No SubLocality")
location.start_updates() time.sleep(5) my_loc = location.get_location() acc = my_loc['horizontal_accuracy'] best_loc = my_loc best_acc = my_loc['horizontal_accuracy'] location.stop_updates() # example output of location.get_location() # 'vertical_accuracy': 14.31443007336287 # 'horizontal_accuracy': 1414.0 # 'timestamp': 1408639887.267081 # 'altitude': 1514.9893798828125 # 'longitude': -146.64942423483025 # 'course': -1.0 # 'latitude': 39.10669415937833 # 'speed': -1.0 datestamp = datetime.datetime.fromtimestamp(best_loc['timestamp']) time_str = datestamp.strftime('%Y-%m-%d %H:%M:%S') lat = best_loc['latitude'] lon = best_loc['longitude'] address = location.reverse_geocode({'latitude': lat, 'longitude': lon}) address = address[0]['Street'] + ', ' + address[0]['City'] + ', ' + address[0]['Country'] cmd = 'launch://ifttt/trigger?name=Panic&Value1={}&Value2={}&Value3={}&Value4={}&Value5={}'.format(urllib.quote(time_str), best_acc, lat, lon, urllib.quote(address)) webbrowser.open(cmd)
def run(self, input): self.status = 'complete' loc = location.reverse_geocode(input.value) return ElementValue(type=self.get_output_type(), value=loc)
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!!')
"\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 main(): #album_name = 'My Photo Stream' #albums = photos.get_albums() album_name = 'Camera Roll' albums = photos.get_smart_albums() album = get_album_byname(albums, album_name) print('Album: {}'.format(album.title)) if type(album) != photos.AssetCollection: sys.exit('Album not found!') photo_info_list = [] print('Photo Count: {}'.format(len(album.assets))) i = 0 kID = 'local_id' kDate = 'creation_date' kGeo = 'location' kLocID = 'location_idx' for a in album.assets: try: i += 1 photo_info = {} photo_info[kID] = a.local_id #iOS local filename photo_info[kDate] = a.creation_date #Photo date/timestamp photo_info[kGeo] = a.location #GPs lat/lon of photo photo_info[kLocID] = None #index into locations list photo_info_list.append(photo_info) except Exception as e: print(f'Exception: {e}') #--- End of asset loop print(f'Album: {album_name}') print(f'Count: {i}') print(f'\n===== Post sort ({kDate})') # Sort photo_info_list by creation date s_photo_list = sorted(photo_info_list, key=lambda p: p[kDate]) count = i = no_gps = 0 locations = [] #list of locations base_loc = None #current location radius_km = 0.05 #Distance to regard as zero print(f'Count sorted: {len(s_photo_list)}') for s in s_photo_list: dist = 0 i += 1 #print (f'{i:4}: {s}') if s[kGeo] == None: no_gps += 1 continue if s[kLocID] == None: #s[kLocID] = find_nearest_location(locations, s[kLocID]) if len(locations) != 0: for loc in locations: # See if current location is near existing location dist = haversine.haversine_dict(s[kGeo], loc) if dist <= radius_km: s[kLocID] = locations.index(loc) break if s[kLocID] == None: # Add current photo 's' to locations as it is not within radius # Add current location to locations list locations.append(s[kGeo]) s[kLocID] = locations.index(s[kGeo]) print(f'{i:4}: index:{s[kLocID]} latlon:{locations[s[kLocID]]}') else: dist = 'None' ''' print(f'# of Locations: {len(locations)}') i = 0 for ll in locations: i+= 1 print(f'{i:4}: {ll}') ''' print(f'No gps photos: {no_gps}') no_gps = 0 for s in s_photo_list: if s[kLocID] == None: no_gps += 1 print(f'{no_gps:3}: {s_photo_list.index(s)} - {s[kDate]}') print(f'No. photos no location idx: {no_gps}') i = total = 0 for ll in locations: x = 0 idx = locations.index(ll) for s in s_photo_list: if s[kLocID] == idx: x += 1 results = location.reverse_geocode(ll) print(f'idx: {idx:2} count: {x:4} loc:{results}') total += x print(f'Total loc pictures: {total}') print(f'============') list_by_location(locations, s_photo_list)
def getStreetAddress(loc): return location.reverse_geocode(loc)[0] label1.text = loc
"\n" + "Apple: http://maps.apple.com/?z=12&q=$lat,$long\n" + "\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); url = sys.argv[1]; #url="http://maps.apple.com/maps?address=31%20Stanton%20Road%20Bristol%20England%20BS10%205SJ%20United%20Kingdom&ll=51.504456,-2.590899&q=51.504456,-2.590899&t=m"; ll = urlparse.parse_qsl(url, True)[2][1].split(","); lat = float(ll[0]); long = float(ll[1]); address = location.reverse_geocode({"latitude" : lat, "longitude" : long})[0]; note = locationToNote (address, lat, long); ofnote = {"name" : address.get("Street"), "note" : note}; webbrowser.open("omnifocus:///add?" + urllib.urlencode(ofnote).replace('+','%20'));
# Inspired by: https://github.com/kultprok/pythonista-drafts-recipes/blob/master/weatherdata/weatherdata.py ''' Print out current weather at your current location. ''' import location, requests, time def getLocation(): location.start_updates() time.sleep(1) currLoc = location.get_location() location.stop_updates() # stop GPS hardware ASAP to save battery return currLoc your_loc = location.reverse_geocode(getLocation())[-1] # import pprint ; pprint.pprint(your_loc) # useful for debugging # See: http://bugs.openweathermap.org/projects/api/wiki fmt = 'http://api.openweathermap.org/data/2.5/weather?q={City},+{State},+{CountryCode}' # &units=metric' url = fmt.format(**your_loc).replace(' ', '+') print(url) weather = requests.get(url).json() if weather: # import pprint ; pprint.pprint(weather) # useful for debugging for item in ('temp_min', 'temp_max'): weather['main'][item] = weather['main'].get(item, None) # create values if they are not present # weather is optional in weather!! weather['weather'] = weather.get('weather', [ {'description' : 'not available'} ]) for item in ('sunrise', 'sunset'): weather['sys'][item] = time.ctime(weather['sys'][item]).split()[3] # just time, not date print('''Current weather at {name}, {sys[country]} is {weather[0][description]}. Temprature: {main[temp]}c ({main[temp_min]}c / {main[temp_max]}c) (min / max) Pressure: {main[pressure]} hPa Humidity: {main[humidity]}% Sunrise: {sys[sunrise]} Sunset: {sys[sunset]}
import location import re import sys import urllib.request, urllib.parse, urllib.error import webbrowser a = re.sub(r"(.*\S)$", "\\1 ", sys.argv[1]) a = re.sub(r" \n$", "\n", a) location.start_updates() b = location.get_location() location.stop_updates() if sys.argv[2] == "address": b = location.reverse_geocode({ "latitude": b["latitude"], "longitude": b["longitude"] }) b = b[0]["Street"] + ", " + b[0]["ZIP"] + " " + b[0]["City"] + ", " + b[0][ "Country"] # b = re.sub(r"(P|p)latz", "\\1l.", b) # b = re.sub(r"(S|s)trasse", "\\1tr.", b) # b = re.sub(r", Switzerland", "", b) b = b.encode("utf-8") else: b = "<http://maps.google.com/?q=" + str(b["latitude"]) + "," + str( b["longitude"]) + ">" c = a + b webbrowser.open("drafts4://x-callback-url/create?text=" + urllib.parse.quote(c))
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 direct_from_workflow(workflow): def decdeg2dmsz(dd): is_positive = dd >= 0 dd = abs(dd) minutes, seconds = divmod(dd * 3600, 60) degrees, minutes = divmod(minutes, 60) degrees = degrees if is_positive else -degrees degrees = int(degrees) minutes = int(minutes) z = int((seconds - int(seconds)) * 1e5) seconds = int(seconds) return [degrees, minutes, seconds, z] location.start_updates() gotloc = False for _ in range(30): loc = location.get_location() if (time.time() - loc['timestamp']) < 5: gotloc = True break time.sleep(0.5) location.stop_updates() if not gotloc: return 'Unknown' lat_dms = decdeg2dmsz(loc['latitude']) lat_ns = 'N' if lat_dms[0] < 0: lat_ns = 'S' lat_dms[0] *= -1 lon_dms = decdeg2dmsz(loc['longitude']) lon_ew = 'E' if lon_dms[0] < 0: lon_ew = 'W' lon_dms[0] *= -1 latlon = "{0[0]}˚{0[1]}'{0[2]}.{0[3]:05}\" {1}, {2[0]}˚{2[1]}'{2[2]}.{2[3]:05}\" {3}".format( lat_dms, lat_ns, lon_dms, lon_ew) geo = location.reverse_geocode(loc) if len(geo) == 0: geo = {} else: geo = geo[0] addr_bits = [ geo.get(bit, None) for bit in 'Street City State Country'.split() ] addr_bits = filter( lambda b: b is not None, addr_bits, ) addr = ', '.join(addr_bits) if addr != '': place = '{} ({})'.format(addr, latlon) else: place = latlon return place