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 main(): woosmap_converted_asset = [] with codecs.open(SEARCH_DATA_PATH, 'rb', encoding='utf8') as search_data_file: search_data = json.loads(search_data_file.read()) google_places = GooglePlaces(GOOGLE_API_KEY) for place_id in search_data['places_ids']: try: place = google_places.get_place(place_id) converted_asset = google_places_to_woosmap(place.details) if bool(converted_asset): print("... {place_name} ...converted to Wosmap OK".format(place_name=place.name.encode('utf-8'))) woosmap_converted_asset.append(converted_asset) except (GooglePlacesError, GooglePlacesAttributeError) as error_detail: print('Google Returned an Error : {0} for Place ID : {1}'.format(error_detail, place_id)) pass except Exception as exception: print('Exception Returned {0} for Place ID : {1}'.format(exception, place_id)) time.sleep(1) pass export_to_woosmap_json(woosmap_converted_asset) print('{0} google places extracted for {1} places_ids found '.format(len(woosmap_converted_asset), len(search_data['places_ids'])))
def google_places(): api_key = 'add api key' geo = pd.read_csv('updated_master3.csv') google_places = GooglePlaces(api_key) for idx in geo.index: if ((type(geo.phone_num[idx]) != str) and (type(geo.YelpID[idx]) != str)): print geo.name[idx] lat = geo.lat[idx] lon = geo.lon[idx] result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx]) #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), types=[types.TYPE_FOOD]) #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx], types=[types.TYPE_FOOD]) if len(result.places) == 1: x = result.places[0] x.get_details() geo.set_value(idx, 'phone_num', x.local_phone_number) print "updated %s" % geo.name[idx] elif len(result.places) > 1: for place in result.places: if (float(place.geo_location['lat']) == lat and float(place.geo_location['lng']) == lon): x = place x.get_details() geo.set_value(idx, 'phone_num', x.local_phone_number) print "updated %s" % geo.name[idx] else: print "for %s, length is %d" % (geo.name[idx], len(result.places)) geo.phone_num.replace(regex=True, to_replace='\(|\)|-| ', value='', inplace=True) geo.to_csv('updated_master4.csv', index=False)
def handle(self, *args, **options): # setup del archivo de salida suc_dir = os.path.join(settings.DATASETS_ROOT, 'sucursales') if not os.path.exists(suc_dir): os.makedirs(suc_dir) FILENAME = 'google_place_%s.csv' % datetime.now().strftime("%Y-%m-%d-%H%M%S") FILENAME = os.path.join(suc_dir, FILENAME) writer = unicodecsv.DictWriter(open(FILENAME, 'wb'), SUCURSAL_COLS) writer.writeheader() # crear manager de la api google_places = GooglePlaces(settings.GOOGLE_PLACES_API_KEY) IDS_CONOCIDOS = [] for ciudad in City.objects.filter(population__gte=DESDE).order_by('-population'): location = unicode(ciudad).encode('utf8') query_result = google_places.nearby_search(name='supermercado', language=lang.SPANISH, location=location, types=[types.TYPE_GROCERY_OR_SUPERMARKET], # NOQA radius=2000) for place in query_result.places: if place.id in IDS_CONOCIDOS: print("%s ya cargado" % place.name) continue IDS_CONOCIDOS.append(place.id) supermercado = self.limpiar(place, ciudad) print(supermercado) writer.writerow(supermercado)
def get_nearby_achievements(location, radius=None): """ @param location a dictionary containing "lng" and "lat" entries @param radius radius of google places search @return list of Achievement objects as json Does a google Places nearby_search lookup, Retrieves all Datastore Places entries s.t. place_id is in search results Retrieves all Datastore Achievements s.t. achievement_id is in a Places achievements list return set of Achievements as a json objects """ google_places = GooglePlaces(API_KEY) location = {"lng": location['lon'], "lat": location['lat']} query_results = google_places.nearby_search(lat_lng=location, rankby=ranking.DISTANCE, keyword='[Achievement]') result = {} achievements = [] for place in query_results.places: query = Place.gql("WHERE id = '" + str(place.id) + "'") place_object = query.get() if place_object != None: for achievement_id in place_object.achievements: achievement_obj = Achievement.get_by_id(int(achievement_id)) achievements.append(achievement_obj.to_dict()) result["status_code"] = 200 else: result["status_code"] = 404 result["achievements"] = achievements return json.dumps(result)
def get_context_data(self, **kwargs): context = super(AddPlacesToDatabaseView, self).get_context_data(**kwargs) google_places = GooglePlaces(settings.GOOGLE_API_KEY) query_result = google_places.nearby_search( location='Philadelphia, PA', keyword='Pool', radius=20000) for place in query_result.places: next_result = google_places.nearby_search( location=place.vicinity, keyword='Pool', radius=20000) for place2 in next_result.places: pool2 = Pool.objects.create() pool2.name = place2.name pool2.address = place2.vicinity +" , USA" #Add this to make it work with our map db (?not sure if we need this) pool2.geolocation.lat = place2.geo_location['lat'] pool2.geolocation.lon= place2.geo_location['lng'] #I have no idea what I am doing! --MG if place2.rating is None: pool2.rating = 0.0 else: pool2.rating = float(place2.rating) pool2.save() pool = Pool.objects.create() pool.name = place.name pool.address = place.vicinity +" , USA" #Add this to make it work with our map db (?not sure if we need this) pool.geolocation.lat = place.geo_location['lat'] pool.geolocation.lon= place.geo_location['lng'] #I have no idea what I am doing! --MG if place.rating is None: pool.rating = 0.0 else: pool.rating = float(place.rating) pool.save() context['places_count'] = len(query_result.places) return context
class GOPprovider(basicProvider, goLocation): """ This class is used to: 1. Make the connection to the Google Places API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album """ def __init__(self): """ Initiate the connector """ YOUR_API_KEY = "AIzaSyDoZ455JKv5GS2DgmK1jQc7R8Oj5JVjEnI" self.connector = GooglePlaces(YOUR_API_KEY) def get_nearby_places(self, data): """ EXTRA!!! Find nearby places """ raw_datas = self.connector.nearby_search( location="London, England", keyword="Fish and Chips", radius=20000, types=[types.TYPE_FOOD] ) fields = [ "id", "type", "service", "url", "user.id", "user.username", "website", "name", "details.formatted_address", "details.formatted_address.number", "geo_location.lat", "geo_location.lng", "created_time", "types", ] alternatives = ["", "place", "openi", "", "", "", "", "", "", "", "", "", "", ""] response = {"meta": {"total_count": "blah", "next": "bla"}, "data": []} for raw_data in raw_datas.places: data = self.get_fields(raw_data, fields, alternatives) response["data"].append(self.format_place_response(data)) return response def add_a_place(self, data): """ EXTRA!!! Add a new place """ # Returns a detailed instance of googleplaces.Place raw_data = self.connector.add_place( name=data["name"], lat_lng={"lat": data["lat"], "lng": data["lng"]}, accuracy=data["accuracy"], types=data["type"], language=data["lang"], ) response = {"added_place_reference": raw_data.reference, "added_place_id": raw_data.id} return response def delete_a_place(self, data): """ DELETE API_PATH/[PLACE_ID] """ # Returns a detailed instance of googleplaces.Place raw_data = self.connector.delete_place(data["reference"]) return {"status": "OK"}
def getNearbyWaypoints(latitude, longitude): google_places = GooglePlaces(config.Config.googlePlacesAPIKey) query_result = google_places.nearby_search( lat_lng={'lat': latitude, 'lng': longitude}, rankby='distance', types = [types.TYPE_FOOD, types.TYPE_BAR, types.TYPE_RESTAURANT]) return query_result
def _find_places(request, place_type): g_places = GooglePlaces(API_KEY) request_fields = ['lat_lng', 'radius'] api_req = {k: request[k] for k in request_fields} query_result = g_places.nearby_search(types=place_type, **api_req) places = map(_filter_place_data, query_result.places) return {'places': places}
def get_context_data(self, **kwargs): context = super(PlacesView, self).get_context_data(**kwargs) google_places = GooglePlaces(settings.GOOGLE_API_KEY) query_result = google_places.nearby_search( location='Philadelphia, PA', keyword='Pool', radius=20000) context['places'] = query_result return context
def get_google_places(building_name): """Use the Google Places API from the python-google-places library to extract a place object, given a building name.""" google_places = GooglePlaces(GOOGLE_PLACES_API_KEY) query_result = google_places.nearby_search( location='San Francisco, California', keyword=building_name) places = query_result.places return places
def content(request, type, location): key = 'AIzaSyDVa_QhQkZb8eGLwMmDrhvpjB745f5dakM' '''try: places=Place.objects.filter(city=location) context = { 'location': location, 'places': places, 'type': type, } except: ''' google_places = GooglePlaces(key) query_result = google_places.nearby_search(location=location, radius=20000, types=type) for place in query_result.places: # 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. place_model = Place(place_name=place.name, geo_location=place.geo_location, place_id=place.place_id, address="", details=place.details, city=location, local_phone_number=str(place.local_phone_number), international_phone_number=str(place.international_phone_number), website=place.website, icon=place.icon ) place_model.save() current_place = Place.objects.get(id=place_model.id) for photo in place.photos: photo.get(maxheight=500, maxwidth=500) photo_model = Photo(photo_name=photo.filename, place=current_place, url=photo.url, mimetype=photo.mimetype ) photo_model.save() context = { 'location': location, 'places': query_result.places, 'type': type, } return render(request, 'places/content.html', context)
def get_restaurant(place_name, include_city): restaurant_result = {} google_places = GooglePlaces('AIzaSyAJyCCeJNiaky6gVuZ2G1-0-hK0MaJJr3o') query_result = google_places.nearby_search(location=place_name, radius=1000, types=[types.TYPE_FOOD]) restaurant = random.choice(query_result.places) restaurant.get_details() restaurant_result['name'] = restaurant.name if include_city: restaurant_result['addr'] = restaurant.formatted_address.replace(", United States", "") else: restaurant_result['addr'] = restaurant.formatted_address[:restaurant.formatted_address.index(",")] return restaurant_result
class GOPprovider(basicProvider, goActivity, goLocation, goMedia, goProductsServices, goProfiles): ''' This class is used to: 1. Make the connection to the Google Places API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album ''' def __init__(self): ''' Initiate the connector ''' YOUR_API_KEY = 'AIzaSyDoZ455JKv5GS2DgmK1jQc7R8Oj5JVjEnI' self.connector = GooglePlaces(YOUR_API_KEY) def get_nearby_places(self, data): """ EXTRA!!! Find nearby places """ raw_datas = self.connector.nearby_search(location='London, England', keyword='Fish and Chips', radius=20000, types=[types.TYPE_FOOD]) fields = ['id', 'type', 'service', 'url', 'user.id', 'user.username', 'website', 'name', 'details.formatted_address', 'details.formatted_address.number', 'geo_location.lat', 'geo_location.lng', 'created_time', 'types'] alternatives = ['', 'place', 'openi', '', '', '', '', '', '', '', '', '', '', ''] response = { 'meta': { 'total_count': 'blah', 'next': 'bla' }, 'data': [] } for raw_data in raw_datas.places: data = self.get_fields(raw_data, fields, alternatives) response['data'].append(self.format_place_response(data)) return response def add_a_place(self, data): """ EXTRA!!! Add a new place """ # Returns a detailed instance of googleplaces.Place raw_data = self.connector.add_place(name=data['name'], lat_lng={'lat': data['lat'], 'lng': data['lng']}, accuracy=data['accuracy'], types=data['type'], language=data['lang']) response = { 'added_place_reference': raw_data.reference, 'added_place_id': raw_data.id } return response def delete_a_place(self, data): """ DELETE API_PATH/[PLACE_ID] """ # Returns a detailed instance of googleplaces.Place raw_data = self.connector.delete_place(data['reference']) return { 'status': 'OK' }
def nearby_search(keywords, location): cache_key = str((keywords, location)) results = cache.get(cache_key) if results is not None: return results print "Google Places API Hit" google_places = GooglePlaces(settings.GOOGLE_PLACES_API_KEY) api_results = google_places.nearby_search( radius=25000, location=location, keyword=keywords ) results = map(lambda p: p.name, api_results.places) cache.set(cache_key, results) return results
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 run(self): while True: Site_Address = self.queue.get() #print Site_Address API_KEY = 'xxx' google_places = GooglePlaces(API_KEY) quey_result = google_places.nearby_search(location='Singapore',keyword=Site_Address,radius = 30000) for place in quey_result.places: place.get_details() out_put = Site_Address+';'+place.name+';'+str(place.geo_location['lat'])+';'+str(place.geo_location['lng'])+';'+place.formatted_address threadlock.acquire() print out_put threadlock.release() self.queue.task_done()
def hello(): ## for parameters passed like name and location /?name=abc&location=abc if request.args.get('name'): name = request.args.get('name') if request.args.get('location'): location = request.args.get('location') google_places = GooglePlaces(YOUR_API_KEY) query_result = google_places.nearby_search(name='Kwality Restaurant', location='karol bagh , delhi',keyword='chicken', radius=20000, types=[types.TYPE_FOOD]) data = [] for place in query_result.places: print(place.name) print(place.geo_location) print(place.place_id) return str(place.name)+str(place.geo_location)+str(place.place_id)
def __init__(self, api_key): self.google_places = GooglePlaces(api_key) self.name = None self.geo_location = None self.user_results = dict() pass
def main(): if not has_internet(): print "You must be connected to the Internet." return 1 if len(sys.argv) != 4: print "usage: ./google_places.py <location> <keyword> <radius in mi>" print " ex: ./google_places.py \"Somerville, MA\" \"Indian\" 1" return 1 google_places = GooglePlaces(YOUR_API_KEY) # # Convert location to lat/long # #lat_long = google_places.geocode_location("Brighton, MA", sensor=False) #for k in lat_long: # print(k) #exit() # You may prefer to use the text_search API, instead. query_result = google_places.nearby_search( location=sys.argv[1], keyword=sys.argv[2], radius=(float(sys.argv[3])*1609.34), types=[types.TYPE_FOOD]) 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 "Lat/Lng [%s, %s]" % (place.geo_location['lat'], place.geo_location['lng']) #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.formatted_address print place.local_phone_number print place.international_phone_number print "Website: %s" % place.website print "URL: %s" % place.url print ""
def add_location_to_restaurants(): from .models import Restaurant from googleplaces import GooglePlaces, types, lang, GooglePlacesError gplaces = GooglePlaces(GOOGLE_PLACES_API_KEY) #find all the restaurants that don't have location codes. nonlocated_restaurants = Restaurant.objects.filter( Q(latitude__isnull=True) | Q(longitude__isnull=True) ) #iterates through; doesn't need to be a Bulk insert as background task run overnight for restaurant in nonlocated_restaurants: try: current_place = gplaces.get_place(restaurant.location_code) restaurant.latitude = current_place.geo_location['lat'] restaurant.longitude = current_place.geo_location['lng'] restaurant.save() except GooglePlacesError: print "Errored out on ", restaurant, " location code was: ", restaurant.location_code return "Completed"
def test_google_api(): f = open("places_api_key.txt", "r") api_key = f.read() google_places = GooglePlaces(api_key) query_result = google_places.nearby_search( lat_lng={'lat': 48.407326, 'lng': -123.329773}, radius=5000, types=[types.TYPE_RESTAURANT] or [types.TYPE_CAFE] or [type.TYPE_BAR] or [type.TYPE_CASINO]) if query_result.has_attributions: print(query_result.html_attributions) for place in query_result.places: place.get_details() # print(dir(place)) print(place.rating) print(place.name)
def nearby_pharmacy(my_input) : YOUR_API_KEY = 'AIzaSyDuy19nMwHBvLvgkg9upGZkex9jqriWkQ0' google_places = GooglePlaces(YOUR_API_KEY) query_result = google_places.nearby_search( location=my_input, keyword='pharmacy', radius=2000, types=[types.TYPE_PHARMACY]) strr = " " flag = 0 for place in query_result.places: place.get_details() strr = strr + "\n Name :" + (str(place.name).upper()) + "\n Address:" + str(place.formatted_address) + "\n Phone Number :" + (str(place.international_phone_number).upper()) + "\n Map Url :" + str(place.url) + "\n Web Link :" + str(place.website) + "\n Ratings:" + str(place.rating)+"\n"+("_"*50)+"\n" flag = flag+1 if flag == 5: break return strr
def places(msg): try: google_places = GooglePlaces(API_KEY) geolocator = Nominatim() loc = geolocator.geocode(msg, timeout=50000) lat1 = loc.latitude lon1 = loc.longitude query_result = google_places.nearby_search(lat_lng={ 'lat': lat1, 'lng': lon1 }, types=[types.TYPE_HOSPITAL]) var50 = [] for place in query_result.places: var50.append(place.name) return ("Hospitals in your city are:\n" + str(var50)) except: return "Sorry,unable to process your request"
def initGooglePlacesApiParams(): with open('../config.json') as json_data: d = json.load(json_data) json_data.close() print(d) API_KEY = d["API_KEY_GOOGLE"] print "apikey:"+ API_KEY global google_places google_places = GooglePlaces(API_KEY)#, types, API_KEY return
def get(address): key = 'AIzaSyC5R4DhcOBRYguyefShsK8IwGpgEPbv3qY' google_places = GooglePlaces(key) # You may prefer to use the text_search API, instead. query_result = google_places.nearby_search( # location='London, England', keyword='Fish and Chips', location=address, keyword='', radius=1610, types=[ types.TYPE_AMUSEMENT_PARK, types.TYPE_AQUARIUM, types.TYPE_ART_GALLERY, types.TYPE_MUSEUM, types.TYPE_ZOO, types.TYPE_POINT_OF_INTEREST ]) type(query_result) return json.dumps(query_result, ensure_ascii=False)
def getDirections(current_location, transportation_mode, shop_preference): """Return a list of directions that the user should take to get from their current location to the ClickTime office while stopping for donuts and coffee along the way.""" # Init API Clients google_places = GooglePlaces(GOOGLE_API_KEY) google_maps = Client(key=GOOGLE_API_KEY) # Get the coordinates of the nearest donut shop to the ClickTime office. query_result = google_places.nearby_search( lat_lng=CLICKTIME_LOCATION, name='donut', types='food', rankby=shop_preference) donut_shop_name = query_result.places[0].name donut_shop_location = query_result.places[0].geo_location # Get directions from current location to donut shop. # Had issues with waypoints so I broke the route into # two different pieces. directions_api_result = google_maps.directions( current_location, donut_shop_location, mode=transportation_mode) directions = [] for step in directions_api_result[0]['legs'][0]['steps']: directions.append(step['html_instructions']) directions.append('<font color="green">Arrived at ' + donut_shop_name + '!</font>') # Get directions from the donut shop to the ClickTime office. directions_api_result = google_maps.directions( donut_shop_location, CLICKTIME_LOCATION, mode=transportation_mode) for step in directions_api_result[0]['legs'][0]['steps']: directions.append(step['html_instructions']) directions.append('<font color="green">Arrived at ClickTime!</font>') return directions
def google_places(): api_key = 'add api key' geo = pd.read_csv('updated_master3.csv') google_places = GooglePlaces(api_key) for idx in geo.index: if ((type(geo.phone_num[idx]) != str) and (type(geo.YelpID[idx]) != str)): print geo.name[idx] lat = geo.lat[idx] lon = geo.lon[idx] result = google_places.nearby_search( lat_lng={ 'lat': lat, 'lng': lon }, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx]) #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), types=[types.TYPE_FOOD]) #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx], types=[types.TYPE_FOOD]) if len(result.places) == 1: x = result.places[0] x.get_details() geo.set_value(idx, 'phone_num', x.local_phone_number) print "updated %s" % geo.name[idx] elif len(result.places) > 1: for place in result.places: if (float(place.geo_location['lat']) == lat and float(place.geo_location['lng']) == lon): x = place x.get_details() geo.set_value(idx, 'phone_num', x.local_phone_number) print "updated %s" % geo.name[idx] else: print "for %s, length is %d" % (geo.name[idx], len(result.places)) geo.phone_num.replace(regex=True, to_replace='\(|\)|-| ', value='', inplace=True) geo.to_csv('updated_master4.csv', index=False)
def google_API(): apiKey = "AIzaSyAbMwmG09ccahMdSZacASf5fb1lHaLs0Iw" google_places = GooglePlaces(apiKey) query_result = google_places.nearby_search( location='509 North Rd, Ormond VIC 3204, Australia', keyword='Ormond IGA', radius=200, types=[types.TYPE_FOOD]) if query_result.has_attributions: print(query_result.html_attributions) # Returned places from a query are place summaries. place = query_result.places[0] print(place.name) html_str = "" i = 0 for photo in place.photos: if (i == 0): # 'maxheight' or 'maxwidth' is required photo.get(maxheight=500, maxwidth=500) # MIME-type, e.g. 'image/jpeg' html_str += ''' <img src = %s height = %d width = %d> ''' % (photo.url, 500, 500) i += 1 else: break html_file = open("templates/_google_trial.html", "w") html_file.write(html_str) html_file.close() title = "Google API" template_vars = {"title": title} return render_template("_google_trial.html", vars=template_vars)
def main(): logger = initialize_logging() browser = SessionHandler() try: YOUR_API_KEY = 'AIzaSyB8zZ9ljXNaVHg35-fbUNkX1MHB0qws-XU' google_places = GooglePlaces(YOUR_API_KEY) for location in ['Springfield, MO']: search_for_restaurants(google_places, location, browser, logger) finally: browser.session.quit()
def VisitedPlaces(self, lat, lng): placesVisited = [] google_places = GooglePlaces(API_KEY) location = {'lat': lat, 'lng': lng} query_result = google_places.nearby_search(lat_lng=location, radius=RADIUS) placesIds = [] for place in query_result.places: # Returned places from a query are place summaries. placesIds.append(place.place_id) for placeid in placesIds: place_query_result = google_places.get_place(placeid) placeVisited = { # 'formatted_address': place_query_result.formatted_address, 'place_types': place_query_result.types } placesVisited.append(placeVisited) # Iterate through our list of placetypes of interest for search_place_type in PlaceTypeList: # Iterate through our list of places visited #print search_place_type for place_visited in placesVisited: # Iterate through the list of places types for the current place visited #print place_visited for returned_place_type in place_visited['place_types']: # Check if the returned place type is one that we are searching for #print returned_place_type if returned_place_type == search_place_type: #print 'match found' # Get the return score from the dictionary returned_score = dic_place_types_scores[ search_place_type] # Return the score return returned_score return ZERO
def main(): logger = initialize_logging() browser = SessionHandler() try: YOUR_API_KEY = 'AIzaSyBi7krdji6Ys6sSNSdw2z5FeyCfR1iNimA' google_places = GooglePlaces(YOUR_API_KEY) for location in ['Boston, MA', 'Kansas City, MO', 'Springfield, MO']: search_for_restaurants(google_places, location, browser, logger) finally: browser.session.quit()
def groceries(): #BROOKLYN={'lat': 40.645244, 'lng': -73.9449975} BROOKLYN={'lat': 40.692, 'lng': -73.983} google_places = GooglePlaces(read_api_key()) # You may prefer to use the text_search API, instead. query_result = google_places.radar_search( keyword='', lat_lng=BROOKLYN ,# keyword='Fish and Chips', radius=1850, types=[types.TYPE_GROCERY_OR_SUPERMARKET]) pts = [] for place in query_result.places: #print place.geo_location pts.append((place.geo_location['lng'], place.geo_location['lat'])) return pts
def post(self): city = self.request.get('city') category = self.request.get('category') ##Image Search## google_places = GooglePlaces(GOOGLE_API_KEY) query_results = google_places.nearby_search(location=city, keyword=category, radius=20000) if query_results.has_attributions: print query_results.html_attributions locname = [] loclat = [] loclong = [] marker = "" for place in query_results.places: try: n = str(place.name) location = place.geo_location lat = location["lat"] lng = location["lng"] locname.append(n) loclat.append(lat) loclong.append(lng) except: print " " for i in range(len(locname)): marker += locname[i] marker += ": " marker += str(loclat[i]) marker += ", " marker += str(loclong[i]) marker += "; " self.session["mark"] = marker self.session["city"] = city self.redirect('/')
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 nearby(): # Use your own API key for making api request calls API_KEY = 'your API Key' # Initialising the GooglePlaces constructor google_places = GooglePlaces(API_KEY) # fix location # latitude = 27.568891 # longitude = 76.640637 location = gps.location() latitude = location[0] longitude = location[1] # call the function nearby search with the parameters as longitude, latitude, radius # and type of place which needs to be searched of nearby_hospital = google_places.nearby_search( lat_lng ={'lat': latitude, 'lng': longitude}, types =[types.TYPE_HOSPITAL]) nearby_police = google_places.nearby_search( lat_lng ={'lat': latitude, 'lng': longitude}, types =[types.TYPE_POLICE]) for i, j in zip(nearby_hospital.places, nearby_police.places): print (i.name) print("Latitude =",i.geo_location['lat']) print("Longitude =",i.geo_location['lng']) i.get_details() print("Phone no. =", i.international_phone_number) con.append(i.international_phone_number) print() print (j.name) print("Latitude =",j.geo_location['lat']) print("Longitude =",j.geo_location['lng']) j.get_details() print("Phone no. =", j.international_phone_number) con.append(j.international_phone_number) print() break sms.sms(latitude,longitude)
def get_places(lng, lat, query): google_places = GooglePlaces(API_KEY) query_result = google_places.nearby_search( lat_lng={ 'lat': lat, 'lng': lng }, keyword=query, radius=10000, rankby='distance' ) return [{ 'name': place.name, 'lng': float(place.geo_location['lng']), 'lat': float(place.geo_location['lat']), 'id': place.place_id } for place in query_result.places]
def fetch_places(coordinates): google_places = GooglePlaces(CONFIG.STREET_VIEW_API_KEY) query_result = google_places.nearby_search( lat_lng={ "lat": coordinates.lat, "lng": coordinates.lon }, keyword="landmark", radius=20000, types=[types.TYPE_TOURIST_ATTRACTION], ) place_count = 0 for place in query_result.places: if place_count is 0: place.get_details() place_count = place_count + 1 return place.formatted_address
def __init__(self, grid, API_KEY, r=None, place_type=[types.TYPE_RESTAURANT], searcher='radar'): self.api = GooglePlaces(API_KEY) self.grid = grid self.r = int(0.564 * haversine(0, 0, 0, grid.step)) if r == None else r self.searcher = self.api.radar_search if searcher == 'radar' else self.api.nearby_search self.place_type = place_type
def _get_google_map_search_results(term, zip_code, count=5, radius=20000): google_places = GooglePlaces(settings.GOOGLE_MAPS_API_KEY) place_results = google_places.nearby_search( location=zip_code, keyword=term, radius=20000, types=[] ) map(lambda x: x.get_details(), place_results.places[:count]) json_results = [{ "name": tpr.name, "address": tpr.formatted_address, "website": tpr.website, "phone_number": tpr.local_phone_number, "url": tpr.url, "id": tpr.id, "place_id": tpr.place_id } for tpr in place_results.places[:count]] return json_results
def get_nearest_places(lat, lng, radius, auth_key): google_places = GooglePlaces(auth_key) query_result = google_places.nearby_search(radius=int(radius), types=[types.TYPE_RESTAURANT], lat_lng={ 'lat': lat, 'lng': lng }) places_to_ret = [] for place in query_result.places: places_to_ret.append({ 'name': str(place.name), 'geo_location': { 'latitude': str(place.geo_location['lat']), 'longitude': str(place.geo_location['lng']) }, 'id': str(place.place_id) }) return places_to_ret
def init(lat, lng, speed): place_ref = GooglePlaces(API_KEY) geog_zone = { 'keyword' : ['school', 'hospital'], 'loc_type' : [[types.TYPE_SCHOOL], [types.TYPE_HOSPITAL]], 'speed_lim' : ['25', 'nil'], 'other_lim' : ['nil', 'no_horn'] } os.system('clear') place_latlong = { 'lat': lat, 'lng': lng } for num in range(len(geog_zone['keyword'])): #nearby search based on current location query_result = place_ref.nearby_search( lat_lng = place_latlong, keyword= geog_zone['keyword'][num], radius=500, types = geog_zone['loc_type'][num]) if query_result.has_attributions: print query_result.html_attributions if len(query_result.places) > 0: if geog_zone['keyword'][num] == 'school': if speed > geog_zone['speed_lim'][num]: os.system('play sounds/warning.wav') os.system('play sounds/school.wav') os.system('play sounds/speed.wav') elif geog_zone['keyword'][num] == 'hospital': os.system('play sounds/warning.wav') os.system('play sounds/hos.wav') os.system('play sounds/horn.wav') """
def hospitalset(): # Check if user is loggedin if 'loggedin' in session: cursor = mysql.get_db().cursor() cursor.execute('SELECT * FROM doctors WHERE ID = %s', [session['id']]) account = cursor.fetchone() # enter your api key here API_KEY = 'your google api key' str1 = str(account[9]).split(",") l="" for i in range(0,len(str1)): l=l+str1[i]+"+" send_url = 'https://maps.googleapis.com/maps/api/geocode/json?address='+l+'&key='+API_KEY r = requests.get(send_url) j = json.loads(r.text) lat = j['results'][0]['geometry']['location']['lat'] lon = j['results'][0]['geometry']['location']['lng'] # Initialising the GooglePlaces constructor google_places = GooglePlaces(API_KEY) query_result = google_places.nearby_search( lat_lng ={'lat': lat, 'lng': lon}, radius = 5000, types =[types.TYPE_HOSPITAL]) places = [] # Iterate over the search results for place in query_result.places: places.append(place.name) if(request.method == 'POST'): hname = request.form['hname'] cursor = mysql.get_db().cursor() cursor.execute('UPDATE doctors SET Hospital_Name= %s WHERE ID= %s', [hname,session['id']]) return render_template('dashboard.html', account=account) return render_template('hospitalset.html', places=places, account=account) # User is not loggedin redirect to login page return redirect(url_for('login'))
def location_scrap(business_name, loc): #establishes connection to google's servers based on a valid auth key google_places = GooglePlaces(app.config['GOOGLE_KEY']) # You may prefer to use the text_search API, instead. query_result = google_places.nearby_search(location=loc, keyword=business_name, radius=20000, types=[types.TYPE_FOOD]) # 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 data = [] #this list will hold a bunch of dictionaries for place in query_result.places: place.get_details() # Returned places from a query are place summaries. review_data = {} for review in place.details['reviews']: N = 180 date_N_days_ago = datetime.now() - timedelta(days=N) review_time = datetime.fromtimestamp(int(review['time'])) if date_N_days_ago < review_time: #these are the information we will be taking from place.details object temp_data = { "text": review["text"], "rating": str(review["rating"]), "time": review["time"] } review_data.update(temp_data) #there are remaining data (out of the loop) which still #needs to be added to the dictionary review_data review_data['location'] = loc.lower() review_data['business'] = place.name.lower() review_data['avg_rating'] = str(place.rating) #now, the dictionary is filled, #before the review_data is reset, append it to the list data data.append(review_data) #print(data) return data
def place(locVal, keyVal): from googleplaces import GooglePlaces, types, lang google_places = GooglePlaces('AIzaSyCGnrUPzm-6IehnzxsuxEGy8IgD5M1gGe8') ##Reference to the google library for place search result = google_places.nearby_search(location=locVal, keyword=keyVal, radius=20000, types=[types.TYPE_FOOD]) # Written code if result.has_attributions: print(result.html_attributions) place = result.places[0] photo = place.photos[0] photo.get(maxheight=500, maxwidth=500) returnlist = [place.name, place.geo_location, place.place_id, photo.url] return returnlist
def find_nearest_hospital(API, starting_loc): print('Searching for nearest hospital...') finder = GooglePlaces(api_key=API) geolocator = GoogleV3(api_key=API) hospital = '' starting_loc = geolocator.geocode(starting_loc) loc_1_lat = starting_loc.latitude loc_1_long = starting_loc.longitude location_1 = (loc_1_lat, loc_1_long) result = finder.nearby_search(lat_lng={ 'lat': loc_1_lat, 'lng': loc_1_long }, radius=5000, types=[types.TYPE_HOSPITAL]) r = result.places[0] hospital = [r.name, r.geo_location['lat'], r.geo_location['lng']] return hospital
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 search_google_pkg(api_key, keyword, location, radius=8000, types=[types.TYPE_FOOD]): """Query the Google Search API by a search keyword and location (through googleplaces package). Args: api_key location (str): The search location passed to the API. keyword Returns: places: The JSON response from the request. """ # Google places module google_places = GooglePlaces(api_key) # Options: text_search or nearby_search query_result = google_places.nearby_search(location=location, keyword=keyword, radius=radius, types=types) if query_result.has_attributions: print(query_result.html_attributions) # No attributions here g_places = list(query_result.places) places = [] for g_place in g_places: place = {} place['name'] = g_place.name place['geo_location'] = g_place.geo_location place['place_id'] = g_place.place_id g_place.get_details() place['details'] = g_place.details places.append(place) return places '''GOOGLE Place Attributes ----------------- #
def cold_storages(request): API_KEY = "AIzaSyAIQUn1veJPYzWb-wAwu33-xOvCd05ZXHM" latlng = getLocation() lat1 = float(latlng[0]) lng1 = float(latlng[1]) google_places = GooglePlaces(API_KEY) gmaps = googlemaps.Client(key=API_KEY) google_places = GooglePlaces(API_KEY) query_result = gmaps.places_nearby( location='30.354907299999997,76.3677192', keyword='Coldstorage', radius=150000, ) place_info = [] lat_i = [] lng_i = [] name_array = [] for place in query_result['results']: place_info.append((place['name'], place['rating'])) lat_i.append((place['geometry']['location']['lat'])) lng_i.append((place['geometry']['location']['lng'])) name_array.append(place['name']) # lat_info = simplejson.dumps(lat_i) # lng_info = simplejson.dumps(lng_i) context = { "API_KEY": API_KEY, "place_info": place_info, "lat_info": lat_i, "lng_info": lng_i, "names": name_array, } return render(request, 'services/coldStorage.html', context)
def __init__(self, api_key): self.api = GooglePlaces(api_key) self.event_time = 30 self.place_categories = [ 'Food', 'Attractions', 'Chill', 'Treat Yourself', 'Adult' ] self.place_types = { 0: [types.TYPE_RESTAURANT, types.TYPE_CAFE, types.TYPE_BAKERY], 1: [ types.TYPE_MUSEUM, types.TYPE_ZOO, types.TYPE_BOWLING_ALLEY, types.TYPE_AMUSEMENT_PARK, types.TYPE_AQUARIUM, types.TYPE_MOVIE_THEATER ], 2: [ types.TYPE_BOOK_STORE, types.TYPE_LIBRARY, types.TYPE_ART_GALLERY, types.TYPE_PARK, types.TYPE_PET_STORE, types.TYPE_SHOPPING_MALL ], 3: [types.TYPE_SPA, types.TYPE_HAIR_CARE, types.TYPE_BEAUTY_SALON], 4: [types.TYPE_BAR, types.TYPE_NIGHT_CLUB, types.TYPE_CASINO] } self.times = {0: 45, 1: 90, 2: 60, 3: 40, 4: 150}
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 results(): if request.method == 'POST': city = request.form['city'] type = request.form['type'] GOOGLE_API_KEY = "AIzaSyBCsZBILrxQqRNd2Aji_abzot_15Rm9dIY" google_instance = GooglePlaces(GOOGLE_API_KEY) query_result = google_instance.nearby_search( location=city, keyword=type, radius=20000, types=[types.TYPE_FOOD]) if query_result.has_attributions: print (query_result.html_attributions) query_result.places[0].get_details() address = query_result.places[0].formatted_address return render_template("results.html", name = query_result.places[0].name, name2 = address) else: return "Try again from the homepage"
def findPlaces(coord, time): time = time * 100 day = 'Monday' coor = {'lat': coord[1], 'lng': coord[0]} #takes in coor as a dict with 2 fields, 'lat' and 'lng', time as an int in 24 hour time, and day as a string time = int(time) # just in case week = { 'Sunday': 0, 'Monday': 1, 'Tuesday': 2, 'Wednesday': 3, 'Thursday': 4, 'Friday': 5, 'Saturday': 6 } week_key = week[day] # converts to value used by google API output API_Key = 'AIzaSyAhBLfamR61QMJyemNPMyI2CY1Jzy2OJVo' # should sub out google_places = GooglePlaces(API_Key) if 0600 < time < 2000: query_result = google_places.nearby_search( lat_lng=coor, radius=100, types=[types.TYPE_RESTAURANT]) # only looks for restaurants
class GoogleFood(object): """A class that makes JSON and dictionaries of various Google places food results.""" # # TODO: Apparently getters are not pythonic. Figure out how to do this with a @propery. # def get_result(self): #print self.query_results return self.query_results def __init__(self): self.api_key = constants.GOOGLE_PLACES_API_KEY_TAYLORHANDREWS self.api_client = GooglePlaces(self.api_key) self.query_result = None def to_string(self): s += "API Key: %s\n" % self.api_key return s def create_list(self, location_in, keywords_in, radius_mi_in): i = 0 query_list = {} query_result = self.api_client.nearby_search(location=location_in, keyword=keywords_in, radius=radius_mi_in* constants.METERS_PER_MILE, types=[types.TYPE_FOOD]) # # TODO: This print can probably go at some point. If it turns out to be needed it should # be stored in another object or logged. # if query_result.has_attributions: print query_result.html_attributions for place in query_result.places: place_dict = {} place_dict['name'] = place.name place_dict['lat_lng'] = place.geo_location place_dict['place_id'] = place.place_id # # 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. # place.get_details() place_dict['formatted_address'] = place.formatted_address place_dict['local_phone_number'] = place.local_phone_number place_dict['international_phone_number'] = place.international_phone_number place_dict['website'] = place.website place_dict['url'] = place.url query_list[i] = place_dict i = i + 1 self.query_results = query_list return True
def map(lat1,long1): API_KEY = 'xxxxxx' #google cloud api key for maps google_places = GooglePlaces(API_KEY) query_result = google_places.nearby_search( lat_lng ={'lat':lat1 , 'lng':long1 }, radius = 500, types =[types.TYPE_HOSPITAL]) if query_result.has_attributions: print (query_result.html_attributions) dict1={} for place in query_result.places: s="" if 'Hospital'.lower() in place.name.lower() and 'diagnostics'.lower() not in place.name.lower() and 'dental'.lower() not in place.name.lower() and 'eye'.lower() not in place.name.lower(): s=place.name distance=haversine_distance(place.geo_location['lat'],place.geo_location['lng'],lat1,long1) dict1[s]=distance print(dict1) val = dict1.values() minval = min(val) for i in dict1: if dict1[i]== minval: j=i database_fetch(j,lat1,long1)
def handle_message_req(request, Users): payload = request.get_data() print(payload) for sender, message in messaging_events(payload): print("Incoming from %s: %s" % (sender, message)) user = next((u1 for u1 in Users if u1.get_id() == sender), None) if user is None: user = User(sender) Users.append(user) mark_seen(user, PAT) typing_on(user, PAT) if (isinstance(message, Location)): GoogleMapsHandler.handle_location(PAT, user, message) elif ("pic" in message.lower() or "send" in message.lower() or "get" in message.lower()): print("Initialized Reddit API Client") reddit = praw.Reddit(client_id=s.CLIENT_ID, client_secret=s.CLIENT_SECRET, password=s.PASSWORD, user_agent=s.USER_AGENT, username=s.USERNAME) send_message_reddit(PAT, user, message, reddit) elif ("look" in message.lower() and user.get_location() is not None): print("Initialized Google Maps API Client") google_places = GooglePlaces(s.GAPI) GoogleMapsHandler.handle_geosearch(PAT, user, message, google_places) elif ("look" in message.lower() and user.get_location() is None): GoogleMapsHandler.ask_for_location(user, PAT) else: print("Not Sure how to respond.") data = to_json({ "recipient": { "id": user.get_id() }, "message": { "attachment": { "type": "template", "payload": { "template_type": "button", "text": "Hi. Here are some of the things I can do for you!", "buttons": Buttons.button_list } } } }) messagerequestpost(PAT, data) return Users
def nearbyDoctors(location): google_places = GooglePlaces(google_key) query_result = google_places.nearby_search(location=location, keyword='psychiatrist') counter = 1 doctors = [] for place in query_result.places: if "Dr" == place.name[0:2]: place.get_details() try: phone = place.local_phone_number except AttributeError: continue doctors += [ str(counter) + ". Name: " + place.name, "Address: " + place.formatted_address, "Phone: " + phone ] counter += 1 if counter == 6: break return "\n".join( doctors ) + "\nAccess on Google Maps: https://www.google.com/maps?q=nearby+psychiatrists"
def run(self): self.line = dict((k, v) for k, v in self.line.items()) config = ConfigParser() config.read(CONFIG_FILE) client = GooglePlaces(config.get('google', 'api_key')) if len(set(self.line.keys()) - set(self.columns)) > 2: self.columns = self.columns_2009 res = client.nearby_search(lat_lng={ 'lat': self.line[self.columns[15]], 'lng': self.line[self.columns[14]] }) self.add_addy_info(res, 'pickup') res = client.nearby_search(lat_lng={ 'lat': self.line[self.columns[17]], 'lng': self.line[self.columns[16]] }) self.add_addy_info(res, 'dropoff') with self.output().open('w') as line_output: line_with_tabs = '\t'.join([ self.line.get(key) if self.line.get(key) else '' for key in self.columns ]) line_output.write(line_with_tabs)
def get_places_nearby_keyword(self, keyword): google_places = GooglePlaces(self.key) query_result = google_places.nearby_search(lat_lng=self.location, keyword=keyword, radius=20000, types=[types.TYPE_FOOD]) 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) place.get_details() print(place.local_phone_number) print('Website:', place.website) print('Open in Google Maps:', place.url) # Show photos of place # for photo in place.photos: # # 'maxheight' or 'maxwidth' is required # photo.get(maxheight=500, maxwidth=500) # # MIME-type, e.g. 'image/jpeg' # photo.mimetype # # Image URL # photo.url # # Original filename (optional) # photo.filename # # Raw image data # photo.data if query_result.has_next_page_token: query_result_next_page = google_places.nearby_search( pagetoken=query_result.next_page_token)
def query_gmaps(api_key=API_KEY, search_key=SEARCH_KEY, location_key=LOCATION_KEY): ''' function which performs the query of stores ''' saved_shops = [] google_places = GooglePlaces(api_key) # Maybe can be preferred to use the text_search API, instead. query_result = google_places.nearby_search( location=location_key, keyword=search_key, radius=20000, rankby="distance") #,pagetoken='nextPageToken') ## pagetoken=x --> Returns the next 20 results from a previously run search. ## Setting a pagetoken parameter will execute a search with the same parameters ## used previously — all parameters other than pagetoken will be ignored. if query_result.has_attributions: print(query_result.html_attributions) saved_shops = saver_queries(saved_shops, query_result) # Are there any additional pages of results? print(len(saved_shops)) temporary_search = query_result max_iter = 0 while temporary_search.has_next_page_token & max_iter < 1: max_iter += 1 try: query_result_next_page = google_places.nearby_search( pagetoken=temporary_search.next_page_token) saved_shops = saver_queries(saved_shops, query_result_next_page) temporary_search = query_result_next_page except: pass return saved_shops