def FoodScore(location, t=None): #pass place id instead? from googleplaces import GooglePlaces import math gplaces = GooglePlaces("AIzaSyB1qIvuAxzchC8QWG2Y0nn_9LnYsshrApw") rank = 0 if t != None: if t in typerank: rank = typerank.index(t) + 1 mult = (1 + (rank / 8)) else: return 0 query = gplaces.text_search(location=location, radius=0) raw = query.raw_response['results'][0] rscore = raw['rating'] * ( 1 + 1 / (1 + math.pow(math.e, -raw['user_ratings_total']))) if t == None: place = query.places[0] place.get_details() for t in place.details['types']: if t in typerank: if typerank.index(t) > rank: rank = typerank.index(t) if rank == 0: return 0 mult = (1 + (rank / 8)) return 1.25 * mult * rscore
def search_places(query_search, places): from googleplaces import GooglePlaces YOUR_API_KEY = 'AIzaSyA1Ox-CnVRe2684Lxqf_oXDjV0imAY1wx4' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search( query = query_search, radius = 200000) for i in range(10): places[i]["name"] = "" places[i]["rating"] = "" places[i]["address"] = "" places[i]["wesbite"] = "" places[i]["number"] = "" entry = 0 for place in query_result.places: # Returned places from a query are place summaries. place.get_details() places[entry]["name"] = str(place.name) rate = str(place.rating) places[entry]["rating"] = rate + u"\u2b50" places[entry]["address"] = str(place.formatted_address) places[entry]["wesbite"] = str(place.website) places[entry]["number"] = str(place.local_phone_number) entry += 1 if (entry > 9): break print places
def getOneWaypoint(waypoint, reference = None): pool = ConnectionPool('vendalize') cfmapWaypoint = pycassa.ColumnFamilyMap(data.Waypoint, pool, 'waypoints') #map waypoints to Waypoint Class si = sunburnt.SolrInterface("http://54.225.230.44:8983/solr/vendalize.waypoints/") wp = waypoint.lower() wp = re.sub('[^\w\s]+','', wp) response = si.query(waypoint_c=wp).execute(constructor=data.Waypoint) if len(response) > 0: #found waypoint in database so use the googleid as reference for data result = response[0] key = result.key reference = result.googlereference google_places = GooglePlaces(config.Config.googlePlacesAPIKey) place = {} if reference: place = google_places.get_place(reference) if not place: return getOneWaypoint(waypoint, None) #reference lookup failed, try text search else: query_result = google_places.text_search( query = waypoint) if len(query_result.places) > 0: place = (query_result.places)[0] place.get_details() return place
def search_for_web_results(file_location_of_list_of_practices, YOUR_API_KEY, directory_where_you_want_to_save_the_new_file): practices = pd.read_excel(file_location_of_list_of_practices) #print(practices) for index, row in practices.iterrows(): practice_name = getattr(row, "Common Account Name") practice_address = getattr(row, "Physical Street") practice_city = getattr(row, "Physical City") practice_state = getattr(row, "Physical State/Province") practice_zip = str(getattr(row, "Physical Zip/Postal Code")) google_places = GooglePlaces(YOUR_API_KEY) query_result = google_places.text_search(query = practice_name + ' ' + practice_address + ' ' + practice_city + ' ' + practice_state + ' ' + practice_zip) print(len(query_result.places)) for place in query_result.places: try: place.get_details() practices.iloc[index, 11] = place.name practices.iloc[index, 12] = place.formatted_address practices.iloc[index, 13] = place.international_phone_number practices.iloc[index, 14] = place.place_id practices.iloc[index, 15] = place.url practices.iloc[index, 16] = place.website practices.iloc[index, 17] = place.permanently_closed except: continue os.chdir(directory_where_you_want_to_save_the_new_file) practices.to_excel(new_file_name, index = False)
def main(): """ Read input json file, get place_id for each country by Google API and write result json to output file. """ google_places = GooglePlaces(GOOGLE_GEO_API_KEY) result = [] with open(INPUT_FILE_NAME) as json_file: data = json.load(json_file) for country in data: place_id = None country_name = country.get(FIELD_NAME) print(country_name) if country_name: country_search = google_places.text_search(query=country_name, language=LANG) if country_search and country_search.places: place_id = country_search.places[0].place_id print(place_id) result.append({ FIELD_NAME_RU: country.get(FIELD_NAME_RU), FIELD_NAME: country_name, FIELD_PLACE_ID: place_id }) with open(OUTPUT_FILE_NAME, 'w') as outfile: json.dump(result, outfile, ensure_ascii=False, indent=4)
def api(request): if request.method == 'POST': try: q = request.POST['query'] query_text = QueryText.objects.get(query=q) return JsonResponse( {'results': list(query_text.querydata_set.all().values())}) except QueryText.DoesNotExist: google_places = GooglePlaces( 'AIzaSyCYwqirZB73zzrsHF3P7y0XZRX0df2c2TM') query_result = google_places.text_search(query=q, radius=500, lat_lng={ 'lat': -33.8665433, 'lng': 151.1956316 }) qt = QueryText(query=q) qt.save() qt_loaded = QueryText.objects.get(query=q) arr = [] for item in query_result.places: lat = item.geo_location['lat'] long = item.geo_location['lng'] obj = QueryData(query_id=qt_loaded.id, lat=lat, long=long) arr.append({'lat': float(lat), 'long': float(long)}) obj.save() return JsonResponse({'results': arr}) assert isinstance(request, HttpRequest) return render(request, 'app/api.html', { 'title': 'Home Page', 'year': datetime.now().year, })
def attractions(): selectedChoices = ChoiceObj('multi_attractions', session.get('selected')) form_splace = SearchPlaceForm() form_stweets = SearchTweetsForm(obj=selectedChoices) attractions, attractions_next_page, attractions_next_page2 = None, None, None list_attractions = () GOOGLEMAPS_KEY = "AIzaSyCc3VpBAxqVIwkCvQC1ibFGFnqJbXDmxwE" google_places = GooglePlaces(GOOGLEMAPS_KEY) if form_splace.validate_on_submit(): place_name = form_splace.place_name.data attractions = google_places.text_search(query=place_name + ' tourist attractions', language='id') # if have more than 20 if attractions.has_next_page_token: time.sleep(2) attractions_next_page = google_places.text_search( pagetoken=attractions.next_page_token) # if have more than 40 if attractions_next_page.has_next_page_token: time.sleep(2) attractions_next_page2 = google_places.text_search( pagetoken=attractions_next_page.next_page_token) if attractions: la = list(list_attractions) for place in attractions.places: la.append(place.name) if attractions_next_page: for place in attractions_next_page.places: la.append(place.name) if attractions_next_page2: for place in attractions_next_page2.places: la.append(place.name) list_attractions = tuple(la) form_stweets.multi_attractions.choices = [(att, att) for att in list_attractions] form_stweets.latitude.data = form_splace.lat.data form_stweets.longitude.data = form_splace.lng.data form_stweets.place.data = place_name return render_template('index.html', form_splace=form_splace, form_stweets=form_stweets)
def dbupdate(request): key = os.environ['MAP_KEY'] google_places = GooglePlaces(key) query_result_raw = Winery.objects.all() for query in query_result_raw: print(query) call = google_places.text_search(query=query) if (call.has_attributions): query.rating = call._response['results'][0]['rating'] if float(query.rating) > 0: query.save()
def locations(place, type): if(type.lower() == "sightseeing"): place = "Zurich Main Station" type = "points of interest" PLACES_API_KEY = os.environ['PLACES_API_KEY'] places = GooglePlaces(PLACES_API_KEY) result = places.text_search(type + " near " + place) locations = [] for place in result._places: locations.append([str(place._geo_location['lat']), str(place._geo_location['lng']), place.name]) return json_response(locations)
def get_places(): API_KEY = os.getenv("GOOGLE_API_KEY") google_places = GooglePlaces(API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search(location='DePauw University', radius=5) # If types param contains only 1 item the request to Google Places API # will be send as type param to fullfil: # http://googlegeodevelopers.blogspot.com.au/2016/02/changes-and-quality-improvements-in_16.html places = query_result.places return places
def to_golocation(tosearch): YOUR_API_KEY = 'AIzaSyCTqay66rwdaS5CdL9C2BArgrh5Xxwprfs' #'AIzaSyDWvbupdPsaDcbzBsEjc7El5QYDu6eregc' #'AIzaSyAROXFHSbtR0OA1hNKP8VaBRaUzUegksPA' google_places = GooglePlaces(YOUR_API_KEY) query_result = google_places.text_search(query=tosearch) if len(query_result.places) >= 1: place = query_result.places[0] place.get_details() return place.geo_location else: return None
def matchtoGoogleP(placename, lat, lng): """ Method matches a placename and its coordinates (WGS84) to a corresponding place from Google API """ lat_lng = {} lat_lng['lat'] = lat lat_lng['lng'] = lng google_places = GooglePlaces(YOUR_API_KEY) place = None try: query_result = google_places.text_search(placename, lat_lng, radius=300) #if query_result.has_attributions: # print query_result.html_attributions if len(query_result.places) > 0: place = query_result.places[0] place.get_details() except GooglePlacesError as error_detail: # You've passed in parameter values that the Places API doesn't like.. print(error_detail) sleep(3) #query_result = google_places.text_search(placename,lat_lng,radius=300) #if query_result.has_attributions: # print query_result.html_attributions return place # The following method has to make a further API call. # Referencing any of the attributes below, prior to making a call to # get_details() will raise a googleplaces.GooglePlacesAttributeError. ## print place.details # A dict matching the JSON response from Google. ## print place.website ## print place.types ## print place.details['opening_hours'] ## #print place.details['reviews'] ## if 'reviews' in place.details.keys(): ## for r in place.details['reviews']: ## print r['text'] ## print place.rating return place
def new_game(new_city, keywords): google_places = GooglePlaces(app.config['API_KEY']) print("Next results are in " + new_city) global city city = new_city query_results = None try: query_results = google_places.text_search(location=city, query=keywords, radius=8000) except ValueError: print("city not found") # has to be called in order for the details to be fetched if not query_results == None: if len(query_results.places) > 1: for p in query_results.places: p.get_details() # sorted by number of reviews in descending order global sorted_results sorted_results = query_results.places
def new_game(new_city, keywords): google_places = GooglePlaces(app.config['API_KEY']) print("Next results are in " + new_city) global city city = new_city query_results = None try: query_results = google_places.text_search( location=city, query=keywords, radius=8000) except ValueError: print("city not found") # has to be called in order for the details to be fetched if not query_results == None: if len(query_results.places) > 1: for p in query_results.places: p.get_details() # sorted by number of reviews in descending order global sorted_results sorted_results = query_results.places
from googleplaces import GooglePlaces, types, lang YOUR_API_KEY = 'YOUR_API_KEY' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search(query = 'Restaurant in Boston',location='Boston, United States',radius=20000) # If types param contains only 1 item the request to Google Places API # will be send as type param to fullfil: # http://googlegeodevelopers.blogspot.com.au/2016/02/changes-and-quality-improvements-in_16.html #if query_result.has_attributions: #print(query_result.html_attributions) print("~~~~~~~~~~~") i =0 num = 5 for place in query_result.places: # Returned places from a query are place summaries. print(place.name) print(place.geo_location) print(place.place_id) # The following method has to make a further API call. place.get_details() # Referencing any of the attributes below, prior to making a call to # get_details() will raise a googleplaces.GooglePlacesAttributeError. print(place.details) # A dict matching the JSON response from Google.
import time, json #import pandas as pd import csv query_result_next_page = None invalid_requests_found = 0 request_count = 0 API_KEY = 'AIzaSyD_4AJz6aSbnh6u_54shNpPOVt7867FNWM' google_places = GooglePlaces(API_KEY) with open("izmirokul.csv", mode='w', newline='') as locationsFile: locationsWriter = csv.writer(locationsFile, delimiter=',') query = input("Search query: ") query_result = google_places.text_search(query) for place in query_result.places: locationsWriter.writerow( [place.name, place.geo_location['lat'], place.geo_location['lng']]) print(place.name, place.geo_location) morePages = True while True: time.sleep(2) request_count = request_count + 1 try: if query_result.has_next_page_token: query_result_next_page = google_places.text_search( pagetoken=query_result.next_page_token) for place in query_result_next_page.places:
from googleplaces import GooglePlaces import csv import time places = GooglePlaces("AIzaSyAbG5vBlnNli4gilP1CWWmgCYWy-oyWd8c") marker_text = """ new google.maps.Marker({position: new google.maps.LatLng(%s, %s), map: map, title:"%s"}); """ js = [] with open("csvs/2014_with_locations.csv", 'rU') as f: for row in csv.reader(f): print row name = row[1].strip() + ' ' + row[2].strip() loc = row[0] + ', ' + row[3] print loc res = places.text_search(query=loc) if res: p = res.places[0] coor = p.geo_location print coor lname = p.name js.append(marker_text % (coor['lat'], coor['lng'], lname + ', ' + name)) time.sleep(.5) for t in js: print t
from googleplaces import GooglePlaces, types, lang import sys YOUR_API_KEY = 'AIzaSyDqv4bCDaERdDUOUMPV1Lw9dJ57hQlV1N8' google_places = GooglePlaces(YOUR_API_KEY) argument = sys.argv[1] # You may prefer to use the text_search API, instead. query_result = google_places.text_search(query=argument) # If types param contains only 1 item the request to Google Places API # will be send as type param to fullfil: # http://googlegeodevelopers.blogspot.com.au/2016/02/changes-and-quality-improvements-in_16.html if query_result.has_attributions: print query_result.html_attributions for place in query_result.places: # Returned places from a query are place summaries. print place.name print place.geo_location print place.place_id # The following method has to make a further API call. place.get_details() # Referencing any of the attributes below, prior to making a call to # get_details() will raise a googleplaces.GooglePlacesAttributeError. print place.details # A dict matching the JSON response from Google. print place.local_phone_number print place.international_phone_number print place.website
# request project data and load JSON response = urllib.urlopen( projectURL ) project = json.loads( response.read() ) institution = project["pi_institution"] print(institution) print("") # Check whether institution is "Department...", "Red McCombs..." etc, do something # TO-DO if institution not in locations_dict: # Query google places text search for institution query_result = google_places.text_search(institution) places = query_result.places location = None # Check if query returned any results if len(places) > 0: # Only one place object should be returned place = places[0] # Unpack longitude and latitude location = {} location["lat"] = str(place.geo_location["lat"]) location["long"] = str(place.geo_location["lng"])
help="Type of place") p.add_argument("-v", "--verbose", action="store_true", dest="verbose", help="Verbose mode [Off]") args = p.parse_args() google_places = GooglePlaces(config.APIKEY) print("Connecting to DB:", args.dbname) db = TinyDB(args.dbname) places = db.table('places') query_result = google_places.text_search(query=args.KW, language=args.language) Filter = Query() for place in query_result.places: # Returned places from a query are place summaries. print(place.name) print(place.geo_location) print(place.place_id) place.get_details() # Referencing any of the attributes below, prior to making a call to # get_details() will raise a googleplaces.GooglePlacesAttributeError. #print(place.details.keys()) # A dict matching the JSON response from Google. print(place.formatted_address) print(place.local_phone_number) print(place.international_phone_number) print(place.website)
#json data object data = {} #with google places api, #can do 100 text searches in a 24 hour period for free with each key. #the nearby search can do 100x more than text searches in a 24 hour period PLACES_API_KEY = "AIzaSyCxfuFaoxIgRisdI_FvpY8kvtBMt5z-ZaQ" google_places = GooglePlaces(PLACES_API_KEY) #if we want user input from the command line, uncomment the next 2 lines. #user_input = raw_input("Please enter the brand name and location (what you would search in Google, e.g. starbucks king and university waterloo): ") #print "You entered:", user_input #if raw input uncommented, comment the following line. user_input = "Starbucks 247 King Waterloo" query_result = google_places.text_search( query=string.replace(user_input, " ", "+")) #if query_result.has_attributions: #print query_result.html_attributions for place in query_result.places: data["name"] = place.name #each store has a unique id, we don't want to store the same information twice data["id"] = place.place_id #data['location'] = place.geo_location #print data #print place.name #print place.geo_location #print place.place_id #need to call an additional details function to get the below options
#if query_result.has_attributions: # print query_result.html_attributions #for place in query_result.places: # print place.name # print place.geo_location # print place.place_id csvfile = open('names.csv', 'a') fieldnames = ['name', 'phone', 'website', 'address'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() query_result = google_places.text_search( location='Orlando', query='Indian Grocery', radius=1000, types=types.TYPE_GROCERY_OR_SUPERMARKET) if query_result.has_attributions: print query_result.html_attributions for place in query_result.places: place.get_details() writer.writerow({ 'name': place.name, 'phone': place.local_phone_number, 'website': place.website, 'address': place.formatted_address })
class GoogleMapsProcessor(object): def __init__(self): self.google_places = GooglePlaces(settings.MAPS_API_KEY) def search(self, keyword, latlng): """ Search Google Places for Businesses """ # You may prefer to use the text_search API, instead. search_tokens = keyword.split(' ') response = [] for token in search_tokens: query_result = self.google_places.nearby_search( lat_lng=latlng, keyword=token, radius=10000, types=[ types.TYPE_AMUSEMENT_PARK, types.TYPE_BAKERY, types.TYPE_BAR, types.TYPE_BOOK_STORE, types.TYPE_CAFE, types.TYPE_CLOTHING_STORE, types.TYPE_CONVENIENCE_STORE, types.TYPE_DEPARTMENT_STORE, types.TYPE_FOOD, types.TYPE_GROCERY_OR_SUPERMARKET, types.TYPE_HARDWARE_STORE, types.TYPE_HEALTH, types.TYPE_HOME_GOODS_STORE, types.TYPE_LIBRARY, types.TYPE_LIQUOR_STORE, types.TYPE_MEAL_DELIVERY, types.TYPE_MEAL_TAKEAWAY, types.TYPE_MOVIE_THEATER, types.TYPE_MUSEUM, types.TYPE_NIGHT_CLUB, types.TYPE_PARK, types.TYPE_PHARMACY, types.TYPE_RESTAURANT, types.TYPE_SHOE_STORE, types.TYPE_SHOPPING_MALL, types.TYPE_STORE, ]) for place in query_result.places: # Returned places from a query are place summaries. cache = {} place.get_details() cache['id'] = place.place_id cache['name'] = place.name cache['address'] = place.formatted_address cache['website'] = place.website cache['phone'] = place.local_phone_number cache['lat'] = float(place.geo_location.get('lat')) cache['lng'] = float(place.geo_location.get('lng')) cache['rating'] = place.rating cache['types'] = place.types[0] if len( place.types) > 0 else 'Others' for photo in place.photos: photo.get(maxheight=800, maxwidth=533) cache['photo'] = photo.url break response.append(cache) return response """ Search Expedia Hotels """ def search_by_text(self, name, lat, lng): latlng = {'lat': lat, 'lng': lng} query_result = self.google_places.text_search( lat_lng=latlng, query=name, radius=10, types=[ types.TYPE_AMUSEMENT_PARK, types.TYPE_BAKERY, types.TYPE_BAR, types.TYPE_BOOK_STORE, types.TYPE_CAFE, types.TYPE_CLOTHING_STORE, types.TYPE_CONVENIENCE_STORE, types.TYPE_DEPARTMENT_STORE, types.TYPE_FOOD, types.TYPE_GROCERY_OR_SUPERMARKET, types.TYPE_HARDWARE_STORE, types.TYPE_HEALTH, types.TYPE_HOME_GOODS_STORE, types.TYPE_LIBRARY, types.TYPE_LIQUOR_STORE, types.TYPE_MEAL_DELIVERY, types.TYPE_MEAL_TAKEAWAY, types.TYPE_MOVIE_THEATER, types.TYPE_MUSEUM, types.TYPE_NIGHT_CLUB, types.TYPE_PARK, types.TYPE_PHARMACY, types.TYPE_RESTAURANT, types.TYPE_SHOE_STORE, types.TYPE_SHOPPING_MALL, types.TYPE_STORE, ]) return query_result def get_place(self, place_id): place = self.google_places.get_place(place_id) cache = {} place.get_details() details = place.details detail_keys = details.keys() # Get Reviews cache['reviews'] = [] if 'reviews' in detail_keys: result = [] for review in details['reviews']: cache = {} cache['rating'] = review.get('rating') cache['rating_range'] = range(int( review.get('rating'))) if review.get('rating') else 0 cache['photo'] = review.get('profile_photo_url') cache['text'] = review.get('text') cache['name'] = review.get('author_name') cache['time'] = review.get('time') result.append(cache) cache['reviews'] = result cache['review_count'] = len(cache['reviews']) cache['id'] = place.place_id cache['name'] = place.name cache['address'] = place.formatted_address cache['website'] = place.website cache['phone'] = place.local_phone_number cache['vicinity'] = place.vicinity cache['lat'] = float(place.geo_location.get('lat')) cache['lng'] = float(place.geo_location.get('lng')) cache['rating'] = place.rating cache['rating_range'] = range(int(place.rating)) if place.rating else 0 cache['types'] = place.types[0] if len(place.types) > 0 else 'Others' cache['photos'] = [] for photo in place.photos: photo.get(maxheight=1400, maxwidth=470) cache['banner'] = photo.url break for photo in place.photos: photo.get(maxheight=800, maxwidth=533) cache['photos'].append(photo.url) return cache
def home(request): """Renders the home page.""" social = request.user.social_auth.get(provider='instagram') token = social.extra_data['access_token'] user_data = UserData.objects.filter(userid=social.uid) if request.method == 'POST': tag = request.POST['tag'] dist = request.POST['dist'] loc = request.POST['loc'] lim = request.POST['lim'] if user_data: user_data.update(dist=dist, tag=tag, loc=loc, lim=lim) user_data = user_data[0] else: user_data = UserData(userid=social.uid, dist=dist, tag=tag, loc=loc, lim=lim) user_data.save() if not user_data: user_data = UserData(userid=social.uid, dist='', tag='', loc='', lim='') user_data.save() elif not request.method == 'POST': user_data = user_data[0] userids = [] userids.append('5385953857') #jadedh userids.append('17025099') #alex_vahid userids.append('314279076') #shikhataori userids.append('38461369') #k.annis userids.append('29023929') #saribe0 userids.append('175984836') #emily_achter caches = JsonCache.objects.all() if not caches: for userid in userids: refresh_cache(userid, token) caches = JsonCache.objects.all() lat = "42.3601" #Boston long = "-71.057" if user_data.loc: google_places = GooglePlaces('AIzaSyCYwqirZB73zzrsHF3P7y0XZRX0df2c2TM') places = google_places.text_search(query=user_data.loc, ) if places: lat = places.places[0].geo_location['lat'] long = places.places[0].geo_location['lng'] elif request.method == 'POST': lat = request.POST['lat'] long = request.POST['long'] return_pics = [] for cache in caches: timestamp = datetime.strptime(cache.timestamp, "%Y-%m-%d %H:%M:%S.%f") elapsed = datetime.now() - timestamp if elapsed > timedelta(minutes=15): cache.json = refresh_cache(str(cache.userid), token) jsonObj = json.loads(cache.json) if 'data' in jsonObj: for pic in jsonObj['data']: if user_data.lim and len(return_pics) >= int(user_data.lim): break if user_data.tag: tag_exists = False if pic['tags']: for tag in pic['tags']: if user_data.tag in tag: tag_exists = True if not tag_exists: continue loc = pic['location'] if loc and 'latitude' in loc: if user_data.dist: if distance(float(loc['latitude']), float(loc['longitude']), float(lat), float(long)) > float(user_data.dist): continue if 'caption' in pic and pic['caption']: caption = pic['caption']['text'] return_pics.append({ 'lat': float(loc['latitude']), 'long': float(loc['longitude']), 'pic': pic['images']['standard_resolution']['url'], 'caption': caption.replace("\'", "") }) if request.method == 'POST': return JsonResponse({ 'results': return_pics, 'lat': float(lat), 'long': float(long) }) #social = request.user.social_auth.get(provider='instagram') #token = social.extra_data['access_token'] #r = requests.get('https://api.instagram.com/v1/tags/boston/media/recent?access_token='+token) #jsonObj = json.loads(r.text) #loc = jsonObj['data'][0]['location'] assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { 'title': 'Home Page', 'year': datetime.now().year, 'return_pics': mark_safe( json.dumps({ 'results': return_pics, 'lat': float(lat), 'long': float(long) })), 'tag': user_data.tag, 'loc': user_data.loc, 'dist': user_data.dist, 'lim': user_data.lim })
def show_request(): _request = request.args.get('text') _userid = request.args.get('user') _request = re.sub('[^A-Za-z0-9 ]+', '', _request) print _request, _userid # Time at which the request was made timestamp = str(datetime.datetime.now()) # Get the intent of the request intent = _classifier(_request) # Generate Response ''' Response format : response['response_type'] = "Information" or "Recommendation" or "Fallback" response['response_category'] = "Time" or "Metadata" or "Weather" or "Music" or "Movie" or "Place" or "Food" or "News" or "WolframAlpha" response['response_status'] = 1 for success, 0 for failure ''' response = {} movie_recommendations = [] response['response_status'] = 0 try: if intent == "Time": response['response_text'] = "Time is " + str( datetime.datetime.now()) response['response_type'] = "Information" response['response_status'] = 1 response['response_category'] = "Time" elif intent == "Metadata": print "Inside Metadata \n" response_text = "I am Priya, a voice controlled family assistant. Created by students of San Jose State University." response_text += " I can tell time, weather updates, read news. Give recommendations on music, movie, places to visit and much more. " response_text += "You could say, " commands = [ " Who is CEO of Facebook?", " What is meaning of Whimsical?", " Tell me about movie Avatar.", " Recommend me a movie.", " Whats new?", " How is the weather in San Jose?", " Play top songs from India", " What is the population of USA?", " What is capital of Greece?", " Who invented Camera?", " what is square root of ten?" ] random.shuffle(commands) questions = "".join(c for c in commands[0:2]) response_text += questions response_text += " What would you like to ask? " response['response_text'] = response_text response['response_type'] = "Information" response['response_status'] = 1 response['response_category'] = "Metadata" elif intent == "Weather": output = weather.get_weather_data(_request) response['response_text'] = output['response_text'] response['response_category'] = "Weather" response['response_type'] = "Information" response['response_status'] = output['response_status'] elif intent == "Movie": print "Inside movies" conn = mysql.connect() cur = conn.cursor() select_stmt = "SELECT * FROM tbl_user WHERE user_name = %(user_id)s" cur.execute(select_stmt, {'user_id': _userid}) rows = cur.fetchone() cur.close() twitter_username = "" movie_history_list = [] tag_list = [] print "\n\n Row:" print rows print "\n\n" if rows != None: twitter_username = rows[4] movie_history_list = rows[7].split(',') tag_list = rows[6].split(',') print twitter_username, movie_history_list, tag_list ''' movie_history_list = ["Tomorrowland (2015)","You Only Live Twice (1967)","Southland Tales (2006)","Money Train (1995)","Four Rooms (1995)"] tag_list = ["adventure", "feel good", "life", "new york city", "police"] twitter_username = "******" ''' obj = MovieRecommender() output = obj.get_movies(_request, username=twitter_username, movie_history_list=movie_history_list, tag_list=tag_list) response['response_text'] = output['response_text'] response['response_category'] = "Movie" response['response_type'] = output['response_type'] response['response_status'] = output['response_status'] elif intent == "Places": API_KEY = 'xxx' google_places = GooglePlaces(API_KEY) query_result = google_places.text_search(query=_request, language='en', radius=20000) places_result = "You can visit" if query_result is not None: for place in query_result.places: # Returned places from a query are place summaries. places_result += " " + place.name print "Inside place" response['response_text'] = places_result response['response_category'] = "Place" response['response_type'] = "Information" response['response_status'] = 1 elif intent == "Food": output = food.get_food_data(_request) #output = {} # Get recipe for the particular food_name response['response_text'] = output['response_text'] response['response_category'] = "Food" response['response_type'] = "Information" response['response_status'] = output['response_status'] elif intent == "News": output = news.get_news(_request) response['response_text'] = output['response_text'] response['response_category'] = "News" response['response_type'] = "Information" response['response_status'] = output['response_status'] elif intent == "Fallback": response['response_text'] = _request response['response_category'] = "Fallback" response['response_type'] = "WolframAlpha" response['response_status'] = 0 else: response['response_text'] = error response['response_category'] = "Not Found" response['response_status'] = 0 except: print "\n\n Unexpected error:", sys.exc_info()[0] response['response_text'] = _request + error2 response['response_category'] = intent response['response_status'] = 0 json_response = json.dumps(response) _store_in_db(timestamp, _request, intent) return json_response, 200
from googleplaces import GooglePlaces, types, lang import json YOUR_API_KEY = 'AIzaSyCTqay66rwdaS5CdL9C2BArgrh5Xxwprfs' #'AIzaSyDWvbupdPsaDcbzBsEjc7El5QYDu6eregc' #'AIzaSyAROXFHSbtR0OA1hNKP8VaBRaUzUegksPA' google_places = GooglePlaces(YOUR_API_KEY) # cities = [] badminton = {} g = open('cities.txt', 'r') lines = g.readlines() for city in lines: query_result = google_places.text_search( location= city,radius = 50000,query='badminton court') #if query_result.has_attributions: # print query_result.html_attributions #print query_result print city for place in query_result.places: place.get_details() print place.name #print place.geo_location #print place.place_id badminton[place.place_id] = place.details print len(badminton)
class GoogleMaps(object): def __init__(self): self._GOOGLE_MAPS_KEY = "AIzaSyB5YDw-6B89z0kxdO3m8k5lnF_glbmpXrQ" self._Google_Places = GooglePlaces(self._GOOGLE_MAPS_KEY) self._Google_Geocod = googlemaps.Client(key=self._GOOGLE_MAPS_KEY) def text_search(self, query, language=None, location=None): text_query_result = self._Google_Places.text_search(query=query, language=language, location=location) result_class = text_query_result.places result_dict = result_class[0].__dict__ return result_dict['_geo_location']['lat'], result_dict[ '_geo_location']['lng'] def calcDistance(self, Lat_A, Lng_A, Lat_B, Lng_B): EARTH_RADIUS = 6378.137 radLat1 = radians(Lat_A) radLat2 = radians(Lat_B) a = radLat1 - radLat2 b = radians(Lng_A) - radians(Lng_B) s = 2 * asin( sqrt( pow(sin(a / 2), 2) + cos(radLat1) * cos(radLat2) * pow(sin(b / 2), 2))) s = s * EARTH_RADIUS return s def driving_info(self, Lat_A, Lng_A, Lat_B, Lng_B): now = datetime.now() directions_result = self._Google_Geocod.directions( str(Lat_A) + ',' + str(Lng_A), str(Lat_B) + ',' + str(Lng_B), mode="driving", avoid="ferries", departure_time=now) return directions_result[0]['legs'][0]['duration'][ 'text'], directions_result[0]['legs'][0]['distance']['text'] def distance_unit(self, distance_str): distance_str = distance_str.split() if distance_str[1] == 'mi': return float(distance_str[0]) * 1.6 elif distance_str[1] == 'km': return float(distance_str[0]) elif distance_str[1] == 'm': if float(distance_str[0]) < 1000: return 0 return float(distance_str[0]) / 1000 elif distance_str[1] == 'ft': if float(distance_str[0]) < 3000: return 0 return float(distance_str[0]) / 3000 def match_info(self, driverdep_latA, driverdep_lngA, driverdep_latB, driverdep_lngB, passengerdep_latA, passengerdep_lngA, passengerdep_latB, passengerdep_lngB): origin_time, origin_distance = self.driving_info( driverdep_latA, driverdep_lngA, driverdep_latB, driverdep_lngB) passenger_time, passenger_distance = self.driving_info( passengerdep_latA, passengerdep_lngA, passengerdep_latB, passengerdep_lngB) extra_time1, extra_distance1 = self.driving_info( driverdep_latA, driverdep_lngA, passengerdep_latA, passengerdep_lngA) extra_time2, extra_distance2 = self.driving_info( passengerdep_latB, passengerdep_lngB, driverdep_latB, driverdep_lngB) passenger_distance = self.distance_unit(passenger_distance) origin_distance = self.distance_unit(origin_distance) extra_distance = self.distance_unit( extra_distance2) + self.distance_unit(extra_distance1) #print (origin_distance, passenger_distance, extra_distance) time_list = [origin_time, passenger_time, extra_time1, extra_time2] for x in range(0, 4): new_time = time_list[x].split() if len(new_time) == 4: time_list[x] = float(new_time[0]) * 60 + float(new_time[2]) elif len(new_time) == 2: time_list[x] = float(new_time[0]) match_dict = { 'origin_time': time_list[0], 'passenger_time': time_list[1], 'extra_time': time_list[2] + time_list[3], 'origin_distance': origin_distance, 'passenger_distance': passenger_distance, 'extra_distance': extra_distance } return match_dict
from __future__ import print_function import sys from googleplaces import GooglePlaces YOUR_API_KEY = '' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search( #location='United States', query=sys.argv[1], #'Alcorn State University', radius=20000) #, types=[types.TYPE_FOOD]) print(query_result.raw_response['results'][0]['formatted_address']) print(query_result.raw_response['results'][0]['geometry']['location'])
from googleplaces import GooglePlaces, types, lang YOUR_API_KEY = 'AIzaSyDytLuaLmy000d4VRakszHkhsjY5GKdiHA' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search(query='shops in Mumbai', types=[types.TYPE_LODGING]) for place in query_result.places: # Returned places from a query are place summaries. print place.name print place.geo_location # The following method has to make a further API call. place.get_details() # Referencing any of the attributes below, prior to making a call to # get_details() will raise a googleplaces.GooglePlacesAttributeError. print place.local_phone_number # Adding and deleting a place
from googleplaces import GooglePlaces # https://github.com/slimkrazy/python-google-places import os import csv google_places = GooglePlaces("AIzaSyD4GwWevOZYPFeUhWoT7gRzhZHO2biPAU8") # TYPE_CONVENIENCE_STORE TYPE_FOOD TYPE_SHOPPING_MALL TYPE_STORE entries = [] queries_str = "Costco\nAndronico\'s\nBianchini\'s\nErewhon\nFalletti Foods\nFresh & Easy\nGelsons\n" \ "Mollie Stones\nPetco\nRainbow Grocer\nRalphs\nSafeway\nSmart & Final\nSuper King Markets\n" \ "Target\nTrader Joes\nVons\nWalgreens\nWalmart\nWhole Food Markets" queries = queries_str.split("\n") for i in range(len(queries)): query_result = google_places.text_search(query="California supermarket \"" + queries[i] + "\"", types=["grocery_or_supermarket"]) # query_result = google_places.nearby_search(location='California', keyword='Costco', # radius=50000, # types=["grocery_or_supermarket"]) if query_result.has_attributions: print(query_result.html_attributions) for place in query_result.places: place.get_details() # print (place.details) entry = { "name": place.name, "formatted_address": place.formatted_address, "lat": place.geo_location["lat"], "lng": place.geo_location["lng"], "local_phone_number": place.local_phone_number,
def add_place(): try: # Create a new achievement to associate with the new place new_achievement = Achievement(name=ach_name, description=ach_description, points=ach_points, requirements=ach_requirements) achievement_key = new_achievement.put() achievement = achievement_key.get() achievement_pictures = [] if add_photos: try: # Do a place search to get photos google_places = GooglePlaces(TEST_KEY) query_result = google_places.text_search(place_name) for place in query_result.places: print "Google place: " + str(place.name) thumbnail_size = (128, 128) first = True place.get_details() print "Google place, photos: " + str(len(place.photos)) for photo in place.photos: photo.get(maxheight=2000, maxwidth=2000) photo_data = photo.data mime_type = photo.mimetype thumbnail_data = rescale.rescale(photo_data, *thumbnail_size) thumbnail = images.Image(thumbnail_data) thumbnail.im_feeling_lucky() # TODO Generate BlobStore entity for get_serving_url(Blobstore # Create Picture Entity to get a unique ID picture = Picture(votes=0, mime_type=mime_type) picture_key = picture.put() picture = picture_key.get() picture_id = str(picture_key.id()) picture.created = datetime.now() # Go ahead and add a link from the Achievement Entity to the Picture Entity picture.put() # Write to GCS and create blob_key gcs_filename = '/thebucket/picture/' + picture_id + '/photo' try: with gcs.open(gcs_filename, 'w', content_type=mime_type) as f: f.write(photo.data) blob_key_picture = blobstore.create_gs_key('/gs' + gcs_filename) picture.picture_url = images.get_serving_url(blob_key_picture) gcs_filename = '/thebucket/picture/' + picture_id + '/thumbnail' with gcs.open(gcs_filename, 'w', content_type=mime_type) as f: f.write(thumbnail.execute_transforms()) blob_key_thumbnail = blobstore.create_gs_key('/gs' + gcs_filename) picture.thumbnail_url = images.get_serving_url(blob_key_thumbnail) except BaseException, TransformationError: print str(TransformationError) continue picture.put() # Save the first photo as the achievements thumbnail if first: achievement.thumbnail = picture.thumbnail_url first = False achievement_pictures.append(picture_id) achievement.pictures = achievement_pictures #end for, break because we only want the first place returned break #end for except GooglePlacesError as error_detail: # You've passed in parameter values that the Places API doesn't like.. print error_detail # end if add_photos achievement.put() # create place document and add it to index place_document = search.Document( doc_id=str(achievement_key.id()), fields=[ search.TextField(name='name', value=place_name), search.TextField(name='country', value=place_country), search.TextField(name='state', value=place_state), search.TextField(name='city', value=place_city), search.GeoField(name='location', value=search.GeoPoint(place_lat, place_lon)), search.NumberField(name='radius', value=place_accuracy), search.NumberField(name='altitude', value=place_altitude), search.TextField(name='achievement_id', value=str(achievement_key.id())), search.DateField(name='created', value=datetime.now()), ]) index = search.Index(name="places-index") index.put(place_document) return "Achievement:\n" + str(achievement.to_dict()) + "\nPlace:\n" + str(place_document) except BaseException, ex: logging.exception("Add place exception: %s " % ex) return str(ex)
# request project data and load JSON response = urllib.urlopen(projectURL) project = json.loads(response.read()) institution = project["pi_institution"] print(institution) print("") # Check whether institution is "Department...", "Red McCombs..." etc, do something # TO-DO if institution not in locations_dict: # Query google places text search for institution query_result = google_places.text_search(institution) places = query_result.places location = None # Check if query returned any results if len(places) > 0: # Only one place object should be returned place = places[0] # Unpack longitude and latitude location = {} location["lat"] = str(place.geo_location["lat"]) location["long"] = str(place.geo_location["lng"])
'Mardan', 'Nowshera', 'Peshawar', 'Shangla', 'Swabi', 'Swat', 'Tank', 'Torghar', 'Upper Dir', 'Upper Kohistan' ] YOUR_API_KEY = 'put ur api key here' google_places = GooglePlaces(YOUR_API_KEY) counter = 0 token = "" for d in districts: for b in business: q = b + " in " + d print(q) for r in range(0, 4): if (r == 0): query_result = google_places.text_search(query=q) print(len(query_result.places)) for place in query_result.places: print(counter) counter += 1 place.get_details() df.loc[counter] = [ place.place_id, place.name, place.formatted_address, place.local_phone_number, place.url, place.geo_location['lat'], place.geo_location['lng'], b, d ] else: if (len(query_result.next_page_token) != 0): query_result = google_places.text_search( query=q, pagetoken=query_result.next_page_token)
class GoogleMaps(object): """提供google maps服务""" def __init__(self): self._GOOGLE_MAPS_KEY = "#################" # Key here self._Google_Places = GooglePlaces(self._GOOGLE_MAPS_KEY) self._Google_Geocod = googlemaps.Client(key=self._GOOGLE_MAPS_KEY) def _text_search(self, query, language=None, location=None): """ 根据搜索字符串,请求google API传回推荐的列表 :param query: 搜索字符串 :param language: 语言 :param location: 地区筛选 :return: """ # lat_lng = {"lat": "22.5745761", "lng": "113.9393772"} # 经纬度附近搜索 # text_query_result = self.self._Google_Places.text_search(query='Gong Yuan', lat_lng=lat_lng) # location 为人可认识的名称 # text_query_result = self.self._Google_Places.text_search(query='Tang Lang Shan', location='shenzhen') # 指定语言搜索 text_query_result = self._Google_Places.text_search(query=query, language=language, location=location) return text_query_result.places def _reverse_geocode(self, lat, lng, language=None): """ 根据经纬度请求google API获取坐标信息,返回信息 :param lat: 纬度 :param lng:经度 :param language:语言 :return: """ # 根据经纬度获取地址信息 pincode list_reverse_geocode_result = self._Google_Geocod.reverse_geocode( (lat, lng), language=language) # print json.dumps(list_reverse_geocode_result, indent=4) return list_reverse_geocode_result def _return_reverse_geocode_info(self, lat, lng, language=None): """ 整理信息 :param lat:纬度 :param lng:经度 :param language:语言 :return: """ list_reverse_geocode = self._reverse_geocode(lat, lng, language=language) if list_reverse_geocode: city = '' pincode = '' route = '' neighborhood = '' sublocality = '' administrative_area_level_1 = '' country = '' street_number = '' # 全名地址 formatted_address = list_reverse_geocode[0]['formatted_address'] for address_info in list_reverse_geocode[0]['address_components']: # 城市标识为locality if 'locality' in address_info['types']: city = address_info['long_name'] # 邮政编码标识为postal_code elif 'postal_code' in address_info['types']: pincode = address_info['long_name'] # 街道路 elif 'route' in address_info['types']: route = address_info['long_name'] # 相似地址名 elif 'neighborhood' in address_info['types']: neighborhood = address_info['long_name'] # 地区名 elif 'sublocality' in address_info['types']: sublocality = address_info['long_name'] # 省份 elif 'administrative_area_level_1' in address_info['types']: administrative_area_level_1 = address_info['long_name'] # 国家 elif 'country' in address_info['types']: country = address_info['long_name'] # 门牌号 elif 'street_number' in address_info['types']: street_number = address_info['long_name'] return {'formatted_address': formatted_address} else: return None def get_pincode_city(self, lat, lng, language=None): """ 根据经纬度获取该地区详细信息 :param lat: 纬度 :param lng: 经度 :return: """ reverse_geocode_info = self._return_reverse_geocode_info( lat, lng, language=language) if reverse_geocode_info: return { 'city': reverse_geocode_info['city'], 'pincode': reverse_geocode_info['pincode'] } else: return None def get_address_recommendation(self, query, return_size, point, language=None, location=None): """ 获取输入地址的推荐地址(最多返回5个) :param query: 搜索地址名称 :param return_size: Num of city returned :param language: 语言 :param location: 地区筛选 :return: """ list_return_info = list() list_places_text_search_result = self._text_search(query=query, language=language, location=location) # 默认返回5条数据 # Only greater th an 4.5 if point != 0: print(len(list_places_text_search_result)) del_num = 0 for i in range(len(list_places_text_search_result)): place = list_places_text_search_result[i - del_num] place.get_details() if place.rating <= point: del list_places_text_search_result[i - del_num] del_num += 1 if len(list_places_text_search_result) > return_size: list_places_text_search_result = list_places_text_search_result[: return_size] for place in list_places_text_search_result: result_geocode = self._return_reverse_geocode_info( place.geo_location['lat'], place.geo_location['lng'], language=language) # 数据不为空 if result_geocode: # 地点全路径加上地点名 result_geocode['formatted_address'] = '{} {}'.format( place.name, result_geocode['formatted_address']) result_geocode['place_name'] = place.name ''' # 经纬度 result_geocode['lat'] = '{}'.format(place.geo_location['lat']) result_geocode['lng'] = '{}'.format(place.geo_location['lng']) ''' # detail place.get_details() # website if place.website: result_geocode['website'] = place.website else: result_geocode['website'] = '' # rating result_geocode['rating'] = str(place.rating) # phone number result_geocode['phone number'] = str(place.local_phone_number) # Photos try: place.photos[0].get(maxheight=200, maxwidth=200) result_geocode['Photo_url'] = str(place.photos[0].url) except: result_geocode['Photo_url'] = " " pass # Types try: result_geocode['types'] = place.types[0] except: result_geocode['types'] = " " pass list_return_info.append(result_geocode) return list_return_info def generate_recommendation_list(self, num_of_city, num_of_day, num_of_activity): ls_day = [] rest_of_day = num_of_day for i in range(num_of_city): if i == num_of_city - 1: ls_day.append( self.generate_activity_day(num_of_activity, rest_of_day)) break temp = 1 if rest_of_day == 2 else (rest_of_day // 2 + 1) ls_day.append(self.generate_activity_day(num_of_activity, temp)) rest_of_day -= temp return ls_day def generate_activity_day(self, num_of_activity, num_of_day): ls_day = [] rest_of_day = num_of_day for i in range(num_of_activity): if i == num_of_activity - 1: ls_day.append(rest_of_day) break temp = 1 if rest_of_day == 2 else (rest_of_day // 2 + 1) ls_day.append(temp) rest_of_day -= temp return ls_day def generate_all(self, citys, activities, num_of_day, point=0): if 'South India' in citys and not activities: activities = ['Nature', 'Theatre', 'Shopping'] if not activities: activities = ['attraction'] ret_ls = [] num_of_city = len(citys) num_of_activity = len(activities) print("Day: {}, City: {}, Activities: {}".format( num_of_day, num_of_city, num_of_activity)) activy_day_ls = self.generate_recommendation_list( num_of_city, num_of_day, num_of_activity) for city_index in range(num_of_city): for activy_index in range(num_of_activity): input_query = str(citys[city_index]) + " " + str( activities[activy_index]) print(input_query) activy_day = activy_day_ls[city_index][activy_index] if activy_day <= 0: continue ret_ls.extend( self.get_address_recommendation(query=input_query, return_size=activy_day, point=point, language='en', location='United States')) return ret_ls
from googleplaces import GooglePlaces, types, lang import json from pprint import pprint google_api_key = 'AIzaSyCzoYCtiRMpJKOm1Qi8xWrcds6na1vHv7I' google_places = GooglePlaces(google_api_key) query_result = google_places.text_search(query="a fine dine restaurant", location='surat, gujarat') if query_result.has_attributions: print query_result.html_attributions #pprint (query_result.raw_response) for place in query_result.places: print place.place_id print place.types print place.name place.get_details() print place.vicinity print place.local_phone_number print place.rating #from location
def handle(self, *args, **options): # CREATE CITY google_places = GooglePlaces(settings.GOOGLE_MAPS_KEY) for i in cityNames: query_result = google_places.text_search( query=i, language="en", types="(cities,)", ) createCity(query_result.places[0].place_id) # CREATE USER user_seeder = Seed.seeder() randomCountry = location_models.Country.objects.all() randomCity = location_models.City.objects.all() with open('pinner/users/adjectives.json', mode='rt', encoding='utf-8') as adjectives: with open('pinner/users/nouns.json', mode='rt', encoding='utf-8') as nouns: adjectives = json.load(adjectives) nouns = json.load(nouns) user_seeder.add_entity( user_models.User, 300, { "uuid": lambda x: uuid.uuid4(), "username": lambda x: random.choice(adjectives) + random.choice( nouns).capitalize(), "residence": lambda x: random.choice(randomCountry), "nationality": lambda x: random.choice(randomCountry), "is_staff": False, "is_superuser": False, "current_city": lambda x: random.choice(randomCity), "current_country": None, "current_continent": None, "is_dark_mode": True, "is_hide_photos": False, "is_hide_trips": False, "is_hide_cities": False, "is_hide_countries": False, "is_hide_continents": False, "is_auto_location_report": True, "fbId": None, "appleId": None, "is_verified_phone_number": False, "is_verified_email_address": False, "avatar_url": None, "app_avatar_url": None, "push_token": None, "distance": 0, "website": None, }, ) user_seeder.execute() # CREATE MOVENOTIFICATION move_otification_seeder = Seed.seeder() allUsers = user_models.User.objects.all() randomCity = location_models.City.objects.all() move_otification_seeder.add_entity( notification_models.MoveNotification, 2000, { "actor": lambda x: random.choice(allUsers), "city": lambda x: random.choice(randomCity), "country": None, "continent": None, }, ) move_otification_seeder.execute() # UPDATE USER allUser = user_models.User.objects.all() for user in allUser: distance = 0 user.current_country = user.current_city.country user.current_continent = user.current_city.country.continent trips = notification_models.MoveNotification.objects.filter( actor=user).order_by('-created_at') try: for i, trip in enumerate(trips): try: lon1, lat1, lon2, lat2 = map(radians, [ trips[i].city.longitude, trips[i].city.latitude, trips[i + 1].city.longitude, trips[i + 1].city.latitude ]) dist = 6371 * (acos( sin(lat1) * sin(lat2) + cos(lat1) * cos(lat2) * cos(lon1 - lon2))) distance += dist except (ZeroDivisionError, IndexError) as e: print(e) user.distance = round(distance) user.save() except notification_models.MoveNotification.DoesNotExist: pass # UPDATE MOVENOTIFICATION allMoveNotification = notification_models.MoveNotification.objects.all( ) for i in allMoveNotification: i.country = i.city.country i.continent = i.city.country.continent i.save() self.stdout.write(self.style.SUCCESS(f"Everything seeded"))
class GoogleMaps(object): def __init__(self): self._GOOGLE_MAPS_KEY = "AIzaSyDonfkHvaaMdi5XhAdusk8ObfzCZe3aTJE" self._Google_Places = GooglePlaces(self._GOOGLE_MAPS_KEY) self._Google_Geocod = googlemaps.Client(key=self._GOOGLE_MAPS_KEY) def _text_search(self, query, language=None, location=None): text_query_result = self._Google_Places.text_search(query=query, language=language, location=location) return text_query_result.places def _reverse_geocode(self, lat, lng, language=None): # 根据经纬度获取地址信息 pincode list_reverse_geocode_result = self._Google_Geocod.reverse_geocode( (lat, lng), language=language) # print json.dumps(list_reverse_geocode_result, indent=4) return list_reverse_geocode_result def _return_reverse_geocode_info(self, lat, lng, language=None): list_reverse_geocode = self._reverse_geocode(lat, lng, language=language) if list_reverse_geocode: city = '' pincode = '' route = '' neighborhood = '' sublocality = '' administrative_area_level_1 = '' country = '' street_number = '' # 全名地址 formatted_address = list_reverse_geocode[0]['formatted_address'] for address_info in list_reverse_geocode[0]['address_components']: # 城市标识为locality if 'locality' in address_info['types']: city = address_info['long_name'] # 邮政编码标识为postal_code elif 'postal_code' in address_info['types']: pincode = address_info['long_name'] # 街道路 elif 'route' in address_info['types']: route = address_info['long_name'] # 相似地址名 elif 'neighborhood' in address_info['types']: neighborhood = address_info['long_name'] # 地区名 elif 'sublocality' in address_info['types']: sublocality = address_info['long_name'] # 省份 elif 'administrative_area_level_1' in address_info['types']: administrative_area_level_1 = address_info['long_name'] # 国家 elif 'country' in address_info['types']: country = address_info['long_name'] # 门牌号 elif 'street_number' in address_info['types']: street_number = address_info['long_name'] return { 'city': city, 'pincode': pincode, 'route': route, 'neighborhood': neighborhood, 'sublocality': sublocality, 'administrative_area_level_1': administrative_area_level_1, 'country': country, 'formatted_address': formatted_address, 'street_number': street_number } else: return None def get_pincode_city(self, lat, lng, language=None): reverse_geocode_info = self._return_reverse_geocode_info( lat, lng, language=language) if reverse_geocode_info: return { 'city': reverse_geocode_info['city'], 'pincode': reverse_geocode_info['pincode'] } else: return None def get_address_recommendation(self, query, language=None, location=None): return_size = 5 list_return_info = list() list_places_text_search_result = self._text_search(query=query, language=language, location=location) # 默认返回5条数据 if len(list_places_text_search_result) > return_size: list_places_text_search_result = list_places_text_search_result[: return_size] for place in list_places_text_search_result: result_geocode = self._return_reverse_geocode_info( place.geo_location['lat'], place.geo_location['lng'], language=language) # 数据不为空 if result_geocode: # 地点全路径加上地点名 result_geocode['formatted_address'] = '{} {}'.format( place.name, result_geocode['formatted_address']) result_geocode['place_name'] = place.name # 经纬度 result_geocode['lat'] = '{}'.format(place.geo_location['lat']) result_geocode['lng'] = '{}'.format(place.geo_location['lng']) list_return_info.append(result_geocode) return list_return_info
class GoogleMaps(object): """提供google maps服务""" def __init__(self): self._GOOGLE_MAPS_KEY = "AIzaSyCz4AToUahajo2EmeTBujjoB0eh_rj7Q5U" self._Google_Places = GooglePlaces(self._GOOGLE_MAPS_KEY) self._Google_Geocod = googlemaps.Client(key=self._GOOGLE_MAPS_KEY) def _text_search(self, query, language=None, location=None): """ 根据搜索字符串,请求google API传回推荐的列表 :param query: 搜索字符串 :param language: 语言 :param location: 地区筛选 :return: """ # lat_lng = {"lat": "22.5745761", "lng": "113.9393772"} # 经纬度附近搜索 # text_query_result = self.self._Google_Places.text_search(query='Gong Yuan', lat_lng=lat_lng) # location 为人可认识的名称 # text_query_result = self.self._Google_Places.text_search(query='Tang Lang Shan', location='shenzhen') # 指定语言搜索 text_query_result = self._Google_Places.text_search(query=query, language=language, location=location) return text_query_result.places def _reverse_geocode(self, lat, lng, language=None): """ 根据经纬度请求google API获取坐标信息,返回信息 :param lat: 纬度 :param lng:经度 :param language:语言 :return: """ # 根据经纬度获取地址信息 pincode list_reverse_geocode_result = self._Google_Geocod.reverse_geocode( (lat, lng), language=language) # print json.dumps(list_reverse_geocode_result, indent=4) return list_reverse_geocode_result def _return_reverse_geocode_info(self, lat, lng, language=None): """ 整理信息 :param lat:纬度 :param lng:经度 :param language:语言 :return: """ list_reverse_geocode = self._reverse_geocode(lat, lng, language=language) if list_reverse_geocode: city = '' pincode = '' route = '' neighborhood = '' sublocality = '' administrative_area_level_1 = '' country = '' street_number = '' # 全名地址 formatted_address = list_reverse_geocode[0]['formatted_address'] for address_info in list_reverse_geocode[0]['address_components']: # 城市标识为locality if 'locality' in address_info['types']: city = address_info['long_name'] # 邮政编码标识为postal_code elif 'postal_code' in address_info['types']: pincode = address_info['long_name'] # 街道路 elif 'route' in address_info['types']: route = address_info['long_name'] # 相似地址名 elif 'neighborhood' in address_info['types']: neighborhood = address_info['long_name'] # 地区名 elif 'sublocality' in address_info['types']: sublocality = address_info['long_name'] # 省份 elif 'administrative_area_level_1' in address_info['types']: administrative_area_level_1 = address_info['long_name'] # 国家 elif 'country' in address_info['types']: country = address_info['long_name'] # 门牌号 elif 'street_number' in address_info['types']: street_number = address_info['long_name'] return { 'city': city, 'pincode': pincode, 'route': route, 'neighborhood': neighborhood, 'sublocality': sublocality, 'administrative_area_level_1': administrative_area_level_1, 'country': country, 'formatted_address': formatted_address, 'street_number': street_number } else: return None def get_pincode_city(self, lat, lng, language=None): """ 根据经纬度获取该地区详细信息 :param lat: 纬度 :param lng: 经度 :return: """ reverse_geocode_info = self._return_reverse_geocode_info( lat, lng, language=language) if reverse_geocode_info: return { 'city': reverse_geocode_info['city'], 'pincode': reverse_geocode_info['pincode'] } else: return None def get_address_recommendation(self, query, language=None, location=None): """ 获取输入地址的推荐地址(最多返回5个) :param query: 搜索地址名称 :param language: 语言 :param location: 地区筛选 :return: """ return_size = 5 list_return_info = list() list_places_text_search_result = self._text_search(query=query, language=language, location=location) # 默认返回5条数据 if len(list_places_text_search_result) > return_size: list_places_text_search_result = list_places_text_search_result[: return_size] for place in list_places_text_search_result: result_geocode = self._return_reverse_geocode_info( place.geo_location['lat'], place.geo_location['lng'], language=language) # 数据不为空 if result_geocode: # 地点全路径加上地点名 result_geocode['formatted_address'] = '{} {}'.format( place.name, result_geocode['formatted_address']) result_geocode['place_name'] = place.name # 经纬度 result_geocode['lat'] = '{}'.format(place.geo_location['lat']) result_geocode['lng'] = '{}'.format(place.geo_location['lng']) list_return_info.append(result_geocode) return list_return_info
speech = r.recognize_google(audio) # returns voice recording as unicode characters (use str(speech) to convert to string) except sr.UnknownValueError: print("Google Speech Recognition could not understand audio") except sr.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) # Places pp = pprint.PrettyPrinter(indent=4) YOUR_API_KEY = 'AIzaSyB8Yg8zsqZfUwinu2c_V8PP7mgBNrp0h8A' google_places = GooglePlaces(YOUR_API_KEY) # You may prefer to use the text_search API, instead. query_result = google_places.text_search(query=speech, radius = 1) if query_result.has_attributions: print query_result.html_attributions coordinates = "" # declare string for retaining lat & lon values place = query_result.places[0] # Returned places from a query are place summaries. # pp.pprint(place.name) # pp.pprint(place.geo_location) print str(place.name) for key in place.geo_location: coordinates += str(place.geo_location[key]) # keys are unicode, locations are floats