def CrawlPopularity(request): popdata_library = populartimes.get( "AIzaSyB0RALv_IqPawmS5eeLWfJBVtcAE8vCW98", ["library"], (40.116193536286815, -88.2435300726317), (40.08857770924527, -88.2047958483285)) popdata_cafe = populartimes.get("AIzaSyB0RALv_IqPawmS5eeLWfJBVtcAE8vCW98", ["cafe"], (40.116193536286815, -88.2435300726317), (40.08857770924527, -88.2047958483285)) # for item1 in popdata_library: # facility = populartimes.get_id("AIzaSyB0RALv_IqPawmS5eeLWfJBVtcAE8vCW98",item1['id']) # if 'current_popularity' not in facility: # facility['current_popularity'] = None # print(item1['name'], item1['coordinates']['lng'], item1['coordinates']['lat'], facility['current_popularity']) to_weekday = { 1: "Monday", 2: "Tuesday", 3: "Wednesday", 4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday" } today = to_weekday[datetime.datetime.today().weekday()] with connection.cursor() as cursor: for item1, item2 in zip(popdata_library, popdata_cafe): library = populartimes.get_id( "AIzaSyB0RALv_IqPawmS5eeLWfJBVtcAE8vCW98", item1['id']) cafe = populartimes.get_id( "AIzaSyB0RALv_IqPawmS5eeLWfJBVtcAE8vCW98", item2['id']) if 'current_popularity' not in library: library['current_popularity'] = 0 if 'current_popularity' not in cafe: cafe['current_popularity'] = 0 try: cursor.execute("INSERT INTO Place(name, longitude, latitude, crowdedness, type) VALUE (%s, %s, %s, %s, %s)",\ [str(item1['name']), \ str(item1['coordinates']['lng']), str(item1['coordinates']['lat']), \ str(library['current_popularity']),\ "Library"]) except: pass try: cursor.execute("INSERT INTO Place(name, longitude, latitude, crowdedness, type) VALUE (%s, %s, %s, %s, %s)",\ [str(item2['name']), \ str(item2['coordinates']['lng']), str(item2['coordinates']['lat']), \ str(cafe['current_popularity']), "Cafe"]) except: pass return redirect("user-detail")
def gmapsscraping(): print("BEGIN google maps scraping") creddata = json.load(open('../sendgrid/configs/creds.json')) api_key = creddata['gmaps'] restaurants = populateRestaurants() #run this for loop X times, X being the number of restaurants we're including in our report for i in range(0,len(restaurants)): restaurantName = restaurants[str(i)]['name'] shortName = restaurants[str(i)]['nospace_name'] minLat = restaurants[str(i)]['minlat'] minLon = restaurants[str(i)]['minlon'] maxLat = restaurants[str(i)]['maxlat'] maxLon = restaurants[str(i)]['maxlon'] print("Processing gmaps scraping " + restaurantName + " ...\n") res = populartimes.get(api_key, ['restaurant'], (minLat, minLon), (maxLat, maxLon)) filename ='../scrapy-yelp-tripadvisor/tutorial/spiders/data/json/' + shortName + '_gmaps_' + datetime.date.today().strftime('%Y-%m-%d') + '_map.json' newfile = open(filename, 'w') newfile.write(json.dumps(res, ensure_ascii=False)) newfile.close() print("END gmaps scraping")
def execute_update(): response = populartimes.get( api_key=places_api_key, types=["restaurant"], p1=(49.231913, -123.267898), p2=(49.290547, -123.103937), radius=10000, n_threads=20, all_places=False # only return places w/ popular times ) print(len(response)) print(response) for place in response: place['latitude'] = place['coordinates']['lat'] place['longitude'] = place['coordinates']['lng'] place['poptime_mon'] = place['populartimes'][0]['data'] place['poptime_tue'] = place['populartimes'][1]['data'] place['poptime_wed'] = place['populartimes'][2]['data'] place['poptime_thr'] = place['populartimes'][3]['data'] place['poptime_fri'] = place['populartimes'][4]['data'] place['poptime_sat'] = place['populartimes'][5]['data'] place['poptime_sun'] = place['populartimes'][6]['data'] [place.pop(key) for key in ["populartimes", "time_spent", "time_wait", "coordinates"] if key in place.keys()] place = json.dumps(place).replace("'", "''") print(place) operation = "INSERT INTO nwhax_data.places JSON \'{}\';".format(place) session.execute(operation)
def populartime_position(types, bound_lower, bound_upper): """ :param types: :param bound_lower: :param bound_upper: :return: """ data = populartimes.get('AIzaSyA9HfJMu0p-RYI5uZvF-uaOSsSgPOenAB8', types, bound_lower, bound_upper) time_spent = 0 if len(data) == 0: distribution = 0 else: distribution = [] if len(data) == 1: for i in range(len(data['populartimes'])): for j in range(len(data['populartimes'][i]['data'])): distribution.append(data['populartimes'][i]['data'][j]) if 'time_spent' not in data: time_spent = 0 else: time_spent = data['time_spent'] else: for i in range(len(data[0]['populartimes'])): for j in range(len(data[0]['populartimes'][i]['data'])): distribution.append(data[0]['populartimes'][i]['data'][j]) if 'time_spent' not in data[0]: time_spent = 0 else: time_spent = data[0]['time_spent'] return distribution, time_spent
def poptester(locname, key, type, lower, upper): loc = populartimes.get(key, type, lower, upper) print('There are ' + str(len(loc)) + ' items from your request\n') print('Result below:\n') print(loc) with open(locname + '.txt', 'w') as fnew: for item in loc: fnew.write('%s\n' % item)
def get_locations(lat, lon): dist = 0.0040 min_lat = lat - dist max_lat = lat + dist min_lon = lon - dist max_lon = lon + dist return populartimes.get(environ["APIKEY"], ["cafe"], (min_lat, min_lon), (max_lat, max_lon), 20, 50)
def load_data(file_name, from_file): response = populartimes.get( api_key, ["restaurants", "clubs", "university", "farmacy", "museum"], (33.769960, -84.395080), (33.759930, -84.383950)) #(33.765060, -84.389950), (33.760394, -84.383839)) geojson = format(response) return geojson
def get_radius_locations(mylocation, dist): lat = mylocation["lat"] lon = mylocation["lon"] lat2, lon2 = get_location_bound(lat, lon, dist) print(lat, lon, lat2, lon2) data = populartimes.get(apiKey, ["Restaurant"], (lat, lon), (lat2, lon2)) print(data) d = json.dumps(data, indent=2) print(d)
def predict_stuff(): y = populartimes.get(os.environ.get("KEY"), ["bar"], (48.132986, 11.566126), (48.142199, 11.580047)) print(y) # both = { # "x" : x, # "y" : y # } return jsonify(y)
def search_cafes(request): """Responds to any HTTP request. Args: request (flask.Request): HTTP request object. Returns: The response text or any set of values that can be turned into a Response object using `make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`. """ request_json = request.get_json() (latitude, longitude) = ( (request.args.get('latitude'), request.args.get('longitude')) if request.args and 'latitude' in request.args and 'longitude' in request.args else (request_json['latitude'], request_json['longitude']) if request_json and 'latitude' in request_json and 'longitude' in request_json else (None, None)) if latitude is None or longitude is None: return add_cors_headers( flask.jsonify({ 'status': 'FAILURE', 'search_result': [] })) api_key = os.environ.get('API_KEY', None) if api_key is None: return add_cors_headers( flask.jsonify({ 'status': 'FAILURE', 'search_result': [] })) SEARCHING_RADIUS = 300 PLACE_TYPES = ['cafe'] NUMBER_OF_THREADS = 20 SHOULD_INCLUDE_PLACES_EVEN_WITHOUT_POPULARTIMES = False delimiting_points = calulate_delimiliting_points(latitude, longitude, SEARCHING_RADIUS) delimiting_point1 = delimiting_points[0] delimiting_point2 = delimiting_points[1] search_result = populartimes.get( api_key, PLACE_TYPES, delimiting_point1, delimiting_point2, NUMBER_OF_THREADS, SEARCHING_RADIUS, SHOULD_INCLUDE_PLACES_EVEN_WITHOUT_POPULARTIMES) formatted_result = format_data(latitude, longitude, search_result) result_json = { 'status': 'SUCCESS', 'search_result': formatted_result, 'zz_row_result': search_result # DEV LOG } return add_cors_headers(flask.jsonify(result_json))
def hello_world(): lat1 = 51.45527 long1 = -0.01907 lat2 = 51.46753 long2 = -0.00407 data = populartimes.get(apiKey,["bar"], (lat1, long1), (lat2, long2)) print(data) for location in data: if('current_popularity' in location): print("Location name: " + location['name'] + " is has current popularity of: " + str(location['current_popularity']))
def get_area_popularity(): """Get the popularity of all locations within a 500 meter square from the location passed in the query string parameters""" lat = request.args.get("lat", type=float) lng = request.args.get("lng", type=float) print(lat) print(lng) bottom_left = add_amount_to_coords(lat, lng, -500) top_right = add_amount_to_coords(lat, lng, 500) locations = populartimes.get( os.environ["GMAPS_PLACES_API_KEY"], ["restant"], bottom_left, top_right, ) print(locations) result = [] for location in locations: current_location = { "name": location["name"], "place_id": location["id"] } if "current_popularity" in location: current_location["current_popularity"] = location[ "current_popularity"] else: day_of_week = datetime.strftime(datetime.now(), "%A") hour_of_day = int(datetime.strftime(datetime.now(), "%H")) for day in location["populartimes"]: if day_of_week.lower() == day["name"].lower(): current_location["expected_popularity"] = day["data"][ hour_of_day] break result.append(current_location) return jsonify(result)
def get(self, location, threshold, search_radius): data = populartimes.get( self.api_key, place_types, (location[0] - search_radius, location[1] - search_radius), (location[0] + search_radius, location[1] + search_radius), radius=1000) day = datetime.datetime.today().weekday() hour = datetime.datetime.today().hour result = [] for place in data: popularity = place['populartimes'][day]['data'][hour] if popularity >= threshold: coordinates = place['coordinates'] result.append({ 'coordinates': coordinates, 'radius': popularity }) return result
def get_top_venues(self, address, preferences): global onboard geolocator = Nominatim() location = geolocator.geocode(address, addressdetails=True) radius = preferences['radius'] wait_time = preferences["wait_time"] if not onboard and location is not None: onboard = True coord_one, coord_two = self.get_coordinates(geolocator, location) results = populartimes.get(settings.GOOGLE_PLACES_API_KEY, [types.TYPE_BAR], coord_one, coord_two, 20, radius, False) for result in results: print("Creating " + result["name"]) if "current_popularity" not in result: result["current_popularity"] = 0 if "time_wait" not in result: result["time_wait"] = 0 Venue.objects.create( name=result["name"], address=result["address"], coordinates=result['coordinates'], place_id=result["id"], rating=result["rating"], rating_n=result["rating_n"], current_popularity=result["current_popularity"], wait_time=result["time_wait"], populartimes=result["populartimes"]) venues = Venue.objects.all() venues = filter(lambda x: self.get_wait_time(x) <= wait_time, venues) venues = filter(lambda x: self.distance_to(location, radius, x), venues) venues = sorted(venues, key=lambda i: self.get_popularity(i), reverse=True) venues = sorted(venues, key=lambda i: i.rating, reverse=True) return list(venues)
def getPopularTimes(lat, lng, radius): myKey = "AIzaSyBLMCOvdz6-uGCjEPfYC7TKt0MICGRcK1E" myPosition_x = float(lat) myPosition_y = float(lng) radius = float(radius) * 0.008983 #to convert to km and to scale by lat/lng supermarkets = populartimes.get(myKey, ["grocery_or_supermarket"], (myPosition_x - radius, myPosition_y - radius), (myPosition_x + radius, myPosition_y + radius)) outputs = {} for supermarket in supermarkets: outputs[supermarket["id"]] = {"name":supermarket["name"], "address":supermarket["address"], "lat": supermarket["coordinates"]["lat"], "lng": supermarket["coordinates"]["lng"], "populartimes":supermarket["populartimes"]} #print(supermarkets) output_objs = [] '''#print(outputs.keys()) for key in outputs.keys(): output_str = "{\"" + key + "\"" + ":" + json.dumps(outputs[key]) + "}" output_objs.append(output_str) return "[" + ','.join(output_objs) + "]"''' with open('result.json', 'w') as fp: json.dump(outputs, fp) return "done"
def main(argv): if (len(sys.argv) != 7): print('usage: test.py api venue-type x1 y1 x2 y2') sys.exit(2) api = sys.argv[1] venueType = sys.argv[2] x1 = float(sys.argv[3]) y1 = float(sys.argv[4]) x2 = float(sys.argv[5]) y2 = float(sys.argv[6]) res = populartimes.get(api, [venueType], (x1, y1), (x2, y2)) resStr = json.dumps(res, ensure_ascii=False) f = open('/home/forge/default/public/populartimes-api/output', 'w') f.write(resStr) f.close() print(resStr)
def getResults(LAT, LONG, RADIUS, WEIGHT_DISTANCE, WEIGHT_POPULARITY, type_of_place): # Get Date NOW = datetime.now() DAY_OF_WEEK = WEEKDAYS[datetime.today().weekday()] HOUR_OF_DAY = int(NOW.strftime("%H")) if not type_of_place: type_of_place = ['grocery_or_supermarket'] # Gets set of nearby stores nearby_store_data = populartimes.get(API_KEY, type_of_place, (LAT - RADIUS, LONG - RADIUS), (LAT + RADIUS, LONG + RADIUS)) Place_IDs = [] for place in nearby_store_data: Place_IDs.append(place['id']) processed_data = [] for curr_id in Place_IDs: store_data = populartimes.get_populartimes(API_KEY, curr_id) if 'populartimes' in store_data: if 'current_popularity' in store_data: isClosed = store_data['current_popularity'] == "0" if not isClosed: processed_data.append( store(store_data['name'], store_data['address'], store_data['coordinates']['lat'], store_data['coordinates']['lng'], store_data['id'], store_data['current_popularity'], 0, WEIGHT_DISTANCE, WEIGHT_POPULARITY, LAT, LONG)) else: for date in store_data['populartimes']: if date['name'] == DAY_OF_WEEK: isClosed = str(date['data'][HOUR_OF_DAY]) == "0" if not isClosed: processed_data.append( store(store_data['name'], store_data['address'], store_data['coordinates']['lat'], store_data['coordinates']['lng'], store_data['id'], str(int(date['data'][HOUR_OF_DAY])), 0, WEIGHT_DISTANCE, WEIGHT_POPULARITY, LAT, LONG)) break else: break # fake_store_tester_data_1 = store("Metro", '735 College St, Toronto, ON M6G 1C5, Canada', 43.6541827, -79.4194143, # 'ChIJ7fBhKPE0K4gRLDLhCYYsWVk', "3", 0, WEIGHT_DISTANCE, WEIGHT_POPULARITY, LAT, LONG) # fake_store_tester_data_2 = store("Metro2", '123 Somewhere St, Toronto, ON M6G 1C5, Canada', 43.0541827, -78.4194143, # 'FakeID', "10", 0, WEIGHT_DISTANCE, WEIGHT_POPULARITY, LAT, LONG) # processed_data.append(fake_store_tester_data_1) # processed_data.append(fake_store_tester_data_2) sorted_data_queue = PriorityQueue() for curr_store in processed_data: sorted_data_queue.put(curr_store) sorted_data = [] while sorted_data_queue: if not sorted_data_queue.empty(): temp = sorted_data_queue.get() sorted_data.append(temp) else: break # Convert to dictionary sorted_data_dictionary_form = [] for curr_store in sorted_data: curr_dict = { "name": curr_store.name, "address": curr_store.address, "lat": curr_store.lat, "long": curr_store.long, "id": curr_store.id, "popularity": curr_store.popularity, "score": curr_store.score, } sorted_data_dictionary_form.append(curr_dict) return sorted_data_dictionary_form
dataList = [] dataList.append([ 'name', 'rating', 'id', 'cat1', 'cat2', 'day', 'hour', 'date', 'pop', 'time-spent', 'lat', 'lng' ]) for item in type: dataList = [] dataList.append([ 'name', 'rating', 'id', 'cat1', 'cat2', 'day', 'hour', 'date', 'pop', 'time-spent', 'lat', 'lng' ]) fileName = 'google-data-' + str(item) + '.csv' print(item) popTimes = populartimes.get(key, item, l2, u2) p = 0 popTimesLength = len(popTimes) print(popTimesLength) while p < popTimesLength: bizName = popTimes[p]['name'] bizName.replace(',', '') bizId = popTimes[p]['id'] bizType0 = popTimes[p]['types'][0] bizType1 = popTimes[p]['types'][1] lat = popTimes[p]['coordinates']['lat'] lng = popTimes[p]['coordinates']['lng'] try: rating = popTimes[p]['rating']
def similarLocations(): global userTypes global userRadius global singleUserTypes global userPlaceStorage global coord1 global coord2 global coord3 global coord4 global APIKey global userPlaceID global placeStorage global userLocation global placeID global name global address global types global current_popularity global international_phone_number userPlaceStorage = pt.get_id(APIKey, userPlaceID) #Extra types deletion. We need to remove some categories since they are too prevalent, and would result in thousands of results. userTypes = userPlaceStorage['types'] for a in userTypes: if a == 'point_of_interest': userTypes.remove('point_of_interest') if a == 'store': userTypes.remove('store') if a == 'establishment': userTypes.remove('establishment') if a == 'intersection': userTypes.remove('intersection') singleUserTypes = str(userTypes[0]) if userRadius > 7: userRadius = 7 #If the user sets a radius of more than 7, set the radius to 7 (otherwise there will be too many results.) userLocation = [] userLocation = userPlaceStorage['coordinates'] userLat = userLocation['lat'] userLong = userLocation['lng'] userLocation = [] userLocation.append(userLat) userLocation.append(userLong) coord1 = userLocation[0] - 0.00904371733 * userRadius coord2 = userLocation[ 1] - 0.00904371733 * userRadius #One km is 0.00904371733 degree of latitude or longitude coord3 = userLocation[0] + 0.00904371733 * userRadius coord4 = userLocation[1] + 0.00904371733 * userRadius print(singleUserTypes) print(userTypes) placeStorage = pt.get( APIKey, [singleUserTypes], (coord1, coord2), (coord3, coord4) ) #pt.get a list of businesses with the same user specified type and within a user specified radius from their location. print(placeStorage) index = 0 while index < len(placeStorage): #Runs through entire placeStorage placeID.append( placeStorage[index] ['id']) #Append a ton of information to respective lists name.append(placeStorage[index]['name']) address.append(placeStorage[index]['address']) types.append(placeStorage[index]['types']) if 'current_popularity' in placeStorage[ index]: #If the dictionary has current_popularity current_popularity.append( placeStorage[index]['current_popularity'] ) #Append it to current_popularity the list. else: current_popularity.append(101) #If not, make it 101. if 'international_phone_number' in placeStorage[index]: international_phone_number.append( placeStorage[index]['international_phone_number']) else: international_phone_number.append('No data') index += 1 #Increments the index by 1 to repeat this for the next dictionary. userTypes = [x.replace('_', ' ') for x in userTypes ] #Replace underscores throughout with spaces for beauty
def getPopularTimes(tl, br, q, day): return populartimes.get(secret.apiKey, [q], tl, br)
""" import populartimes import json # You should have a file containing your reddit credentials # This file should never be shared /or pushed to git credentials_file = "../.secrets/credentials.json" with open(credentials_file) as f: params = json.load(f) api_key = params['api_key'] # supported types: https://developers.google.com/maps/documentation/places/web-service/supported_types types = ['restaurant', 'tourist_attraction', 'point_of_interest'] # manually get coordinates: https://www.latlong.net/ # lat/long coords roughly capturing UIUC campus: # p1 = (40.090746, -88.240796) # p2 = (40.116185, -88.219672) # lat/long coords roughly capturing Chicago: p1 = (41.829665, -87.674125) p2 = (41.923483, -87.578274) # include/exclude places without populartimes include_all = False response = populartimes.get(api_key, types, p1, p2, all_places=include_all) print(len(response)) with open('out.json', 'w+') as f: json.dump(response, f, indent=2)
import populartimes populartimes.get("AIzaSyASUnStAUyUBSLjckIAwrFwrg2e4mTnmGs", ["bar"], (40.751852, -74.011069), (40.765180, -73.951159)) # (40.751852, -74.011069) | 40.765180, -73.951159 # Pier 66 Maritime Hospital for Special Surgery, Main Campus
import populartimes populartimes.get("AIzaSyASUnStAUyUBSLjckIAwrFwrg2e4mTnmGs", ["night_club"], (40.743008, -74.011069), (40.751852, -73.963355)) # (40.743008, -74.011069) | (40.751852, -73.963355) # 14th Street Park East 48th Street East River
import sys import populartimes import json north = float(sys.argv[1]) south = float(sys.argv[2]) east = float(sys.argv[3]) west = float(sys.argv[4]) typing = sys.argv[5] data = (populartimes.get(ENV['GOOGLE_API_KEY'], [typing], (north, east), (south, west), all_places=False, n_threads=4)) print(json.dumps(data, separators=(',', ':'))) #print (populartimes.get_id(ENV['GOOGLE_API_KEY'], "ChIJGdCptHhxhlQR5OKcIP64od4"))
def main(argv): #try: # opts, args = getopt.getopt(argv,"hl:b:r:",["longitute=","latitude=","radius="]) #except getopt.GetoptError: # print ('run.py -i <longitude> -o <outputfile>') # sys.exit(2) #for opt, arg in opts: # if opt == '-h': # print ('run.py -l <longitude> -b <latitude> -r <radius>') # sys.exit() # elif opt in ("-l", "--longitude"): # longitude = float(arg) # elif opt in ("-b", "--latitude"): # latitude = float(arg) # elif opt in ("-r", "--radius"): # radius = float(arg) #print ('longitude file is ', longitude) #print ('latitude file is ', latitude) #print ('radius file is ', radius) latitude = float(argv[0]) longitude = float(argv[1]) radius = float(argv[2]) #try: # Larissas api_key, feel free to change json2_file = open("api_key.json") json2_str = json2_file.read() json2_data = json.loads(json2_str) api_key = json2_data[0]["api_key"] # print(api_key) # types of locations that should be considered. # others are 'supermarket', 'food', check here: types = ["grocery_or_supermarket"] # default values for boundrys ( +/- 0.01) bound_lower = (latitude-0.01, longitude-0.01) bound_upper = (latitude+0.01, longitude+0.01) n_threads = 20 # default all_places = False results = populartimes.get(api_key, types, bound_lower, bound_upper, n_threads, radius, all_places) # create DataFrame to split Address in street and city df = pd.DataFrame(results) df.to_csv(r'df1.csv', index=False) # if ['current_popularity'] not in df.columns(): if 'current_popularity' not in df.index: df['current_popularity'] = 1000 df = df.fillna(1000) if 'address' in df.columns: df['street'] = df['address'].str.split(', ', n=1, expand=True)[0] df['city'] = df['address'].str.split(', ', n=1, expand=True)[1] else: print(r'[]') exit(2) if 'time_spent' in df.columns: df['time_spent'] = df.time_spent.map(lambda x: x[0]) else: print(r'[]') exit(2) # extract important info columns = ['name', 'id', 'street', 'city', 'current_popularity','time_spent'] df = df[columns] # convert to json res_json =df.to_json(orient='records') # check for consistency df.to_csv(r'df2.csv', index=False) print(str(res_json)) sys.stdout.flush()
import populartimes token = "AIzaSyALhAZt_ytM7tkOl-XKN_KXlIajgEXttNk" # print(populartimes.get_id(token, "ChIJ01CaE2PfnUcRUpb8Ylg-UXo")) stuff = populartimes.get(token, ["restaurant"], (-33.860, 151.210), (-33.790, 151.270)) print(stuff) # get coordinates and place type # https://developers.google.com/places/supported_types
import populartimes import sys import json api_key = sys.argv[1] types = sys.argv[2].split('|') p1 = sys.argv[3].split(',') p1_f = [float(p1[0]), float(p1[1])] p1_t = tuple(p1_f) p2 = sys.argv[4].split(',') p2_f = [float(p2[0]), float(p2[1])] p2_t = tuple(p2_f) n_threads = int(sys.argv[5]) radius = int(sys.argv[6]) all_places = bool(sys.argv[7]) # data = populartimes.get(api_key, types, p1_t, p2_t, n_threads, radius, all_places); data = populartimes.get(api_key, types, p1_t, p2_t) print(json.dumps(data)) # print(types)
import populartimes import secret data = populartimes.get(secret.APIKey, ["park"], (51.3494488, -0.0960801), (51.3689835, -0.0617154), all_places=False) ##print(populartimes.get(secret.APIKey, ["park"], (51.3494488,-0.0960801), (51.4251894,0.0476962), all_places = False)) for item in data: print(item['name'])
for park in parks['features']: if (park["properties"]["free"]): newplace = { "gmapid": '0', "name": park['properties']["name"] + " Parking", "lat": round(park["geometry"]["coordinates"][1], 6), "lng": round(park["geometry"]["coordinates"][0], 6), "currentpopular": 100 - int(park["properties"]["free"]) * 100 / int(park["properties"]["total"]) } mycol.insert_one(newplace) places = populartimes.get("AIzaSyDPAw8Ry_libv-n-dYZpyczu5F73pXsS34", [], (49.596801, 6.105913), (49.639198, 6.163469), 10, 200, False) for place in places: newplace = { "gmapid": place["id"], "name": place["name"], "lat": round(place["coordinates"]["lat"], 6), "lng": round(place["coordinates"]["lng"], 6), "currentpopular": place["populartimes"][6]["data"][19] } mycol.insert_one(newplace) places = populartimes.get("AIzaSyDPAw8Ry_libv-n-dYZpyczu5F73pXsS34", ["park"], (49.596801, 6.105913), (49.639198, 6.163469), 10, 2000, False) for place in places:
def detail(): form = DetailForm(request.form) if request.method == 'POST' and form.validate(): # Import User Input user_address = form.user_address.data store_type = form.store_type.data radius = form.radius.data radius = int(radius) # Find the google place from the user_address input user_address_res = requests.get(url + 'query=' + user_address + '&key=' + MyAPI_key) x = user_address_res.json() user_location = x["results"][0]["geometry"]["location"] user_latitude = user_location["lat"] user_longitude = user_location["lng"] # Define search area around the user location delta = radius*alpha p1 = (user_latitude-delta, user_longitude-delta) p2 = (user_latitude+delta, user_longitude+delta) if store_type == 'supermarket': results = populartimes.get(MyAPI_key, ["grocery_or_supermarket"], p1, p2, radius=radius, all_places=False, n_threads=1) if store_type == 'pharmacy': results = populartimes.get(MyAPI_key, ["pharmacy"], p1, p2, radius=radius, all_places=False, n_threads=10) # Find out the current time at the user's location (can only be found by a place details request) user_location_id = x["results"][0]["reference"] url_details = "https://maps.googleapis.com/maps/api/place/details/json?" user_location_details_res = requests.get(url_details+"key="+MyAPI_key+"&place_id=" + user_location_id) y = user_location_details_res.json() utc_offset = y["result"]["utc_offset"] time_now = datetime.utcnow()+timedelta(hours=utc_offset/60) # Create a list of stores with their activity data (current if available, otherwise average at current time) # Closed stores (activity=0) are omitted store_list = [] for item in results: if "current_popularity" in item: store_list.append([item["current_popularity"], item["name"], item["id"]]) else: temp = item["populartimes"][time_now.weekday()]["data"][time_now.hour] if temp != 0: store_list.append([temp, item["name"], item["id"]]) # If no Stores are found give out an error if len(store_list) == 0: # return 'there has been an error: No data available for this choice' return redirect(url_for('error')) # Select the store with the least activity and get its ID and name df = pd.DataFrame(store_list) store_place_id = df.iloc[df[0].idxmin(), 2] store_name = df.iloc[df[0].idxmin(), 1] # Create google maps link based of store_place_id store_gmap_url = "https://www.google.com/maps/place/?q=place_id:" + store_place_id return render_template('stop.html', value=store_name, key=store_gmap_url) else: return render_template('details.html', form=form)