Пример #1
0
def findARestaurant(mealType, location):
    # 1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    lat = getGeocodeLocation(location)[0]
    lon = getGeocodeLocation(location)[1]
    # 2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    # HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?
    # client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = (('https://api.foursquare.com/v2/venues/explore?'
            'client_id={0}'
            '&client_secret={1}'
            '&v=20170801'
            '&ll={2},{3}'
            '&query={4}'
            '&limit=1').format(foursquare_client_id, foursquare_client_secret,
                               lat, lon, mealType))

    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # Grab the first restaurant
    restaurantName = result['response']['groups'][0]['items'][0]['venue'][
        'name']
    # Grab restaurant address
    restaurantAddress = result['response']['groups'][0]['items'][0]['venue'][
        'location']['formattedAddress'][0]
    try:
        restaurantAddress1 = result['response']['groups'][0]['items'][0][
            'venue']['location']['formattedAddress'][1]
    except Exception, e:
        restaurantAddress1 = ''
def findARestaurant(mealType, location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    result = getGeocodeLocation(location)
    latitude = result[0]
    longitude = result[1]
    print "latitude: %d, longitude: %d" % (latitude, longitude)

    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = 'https://api.foursquare.com/v2/venues/explore'

    params = dict(
        client_id=foursquare_client_id,
        client_secret=foursquare_client_secret,
        v='20180323',
        # ll='40.7243,-74.0018',
        ll='{},{}'.format(latitude, longitude),
        query=mealType,
        limit=1)

    resp = requests.get(url=url, params=params)
    data = json.loads(resp.text)

    #3. Grab the first restaurant
    first_restaurant = data['response']['groups'][0]['items'][0]['venue'][
        'name']
    print "first_restaurant: %s" % first_restaurant
    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture

    #5. Grab the first image
    #6. If no image is available, insert default a image url
    #7. Return a dictionary containing the restaurant name, address, and image url

    return 200
Пример #3
0
def findARestaurant(mealType, location):
    '''
    The function takes in the returned variables from getGeocodeLocation
    and inputs it into the url variable. It also inputs the client_id,
    client_secret and mealType to successfully query the list of venues,
    serialized into JSON. From there, we want to find the first restaurant
    in the search query. In doing so, we parse the venue_id, restaurant_name,
    and restaurant_address. Next, we plug it into a restaurant dictionary
    and return the results to the user.
    '''
    latitude, longitude = getGeocodeLocation(location)
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude,
           mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # Retrieve the first restaurant from the search query.
    restaurant = result['response']['venues'][0]
    venue_id = restaurant['id']
    restaurant_name = restaurant['name']
    restaurant_address = restaurant['location']['address']
    restaurant_dict = {
        "id": venue_id,
        "name": restaurant_name,
        "address": restaurant_address
    }
    print restaurant_dict
def findARestaurant(mealType, location):
    # 1. Use getGeocodeLocation to get the latitude and longitude coordinates o
    # f the location string.
    firstRestaurant = []
    (lat, lng) = getGeocodeLocation(location)
    # 2.  Use foursquare API to find a nearby restaurant with the latitude,
    # longitude, and mealType strings.
    url = ("https://api.foursquare.com/v2/venues/search?v=20160108"
           "&client_id=" + foursquare_client_id +
           "&client_secret=" + foursquare_client_secret +
           "&ll=" + str(lat) + "," + str(lng) +
           "&query=" + mealType +
           "&intent=browse&radius=800"
           )

    h = httplib2.Http()
    response, content = h.request(url, 'GET')
    results = json.loads(content)
    # 3. Grab the first restaurant
    restaurants = results['response']['venues']
    restaurantName = ""
    restaurantAddress = ""
    if len(restaurants):
        firstRestaurant = restaurants[0]
        restaurantName = firstRestaurant['name']
        restaurantAddress = firstRestaurant['location']['formattedAddress']
    # 4. Get a  300x300 picture of the restaurant using the venue_id (you can
    # change this by altering the 300x300 value in the URL or replacing it with
    # 'orginal' to get the original picture
    restaurantDetail = []
    photourl = ""
    if len(firstRestaurant) > 0:
        url2 = ("https://api.foursquare.com/v2/venues/" +
                firstRestaurant['id'] +
                "?v=20160108" +
                "&client_id=" + foursquare_client_id +
                "&client_secret=" + foursquare_client_secret
                )
        h = httplib2.Http()
        response, content = h.request(url2, 'GET')
        result = json.loads(content)
        restaurantDetail = result['response']['venue']
        photos = restaurantDetail['photos']['groups']
        # 5. Grab the first image
        # 6. If no image is available, insert default a image url
        if restaurantDetail['photos']['count'] == 0:
            photo = []
            photourl = 'http://bit.ly/1NvadKw'
        else:
            photo = photos[0]['items'][0]
            photourl = photo['prefix'] + '300x300' + photo['suffix']

        # 7. Return a dictionary containing the restaurant name, address, image url
        restaurantDict = {'name': restaurantName,
                          'address': restaurantAddress,
                          'image': photourl
                          }
        return restaurantDict

    return 'No Restaurants Found'
Пример #5
0
def findARestaurant(mealType, location):
    latitude, longitude = getGeocodeLocation(location)
    venues = findNearbyVenueByMealType(latitude, longitude, mealType)
    if venues['response']['venues']:
        restaurant = venues['response']['venues'][0]
        photos = getVenuePhotos(restaurant['id'])
        image = 'http://i.imgur.com/HbnOnmFl.jpg'
        if photos and photos['response']['photos']['count'] > 0:
            first_photo = photos['response']['photos']['items'][0]
            prefix = first_photo['prefix']
            suffix = first_photo['suffix']
            image = prefix + '300x300' + suffix
        name = restaurant['name']
        print 'Restaurant Name: ' + name
        formattedAddress = restaurant['location']['formattedAddress']
        address = ''
        for item in formattedAddress:
            address += item + ' '
        print 'Restaurant Address: ' + address
        print 'Image: ' + image
        result = {'name': name, 'address': address, 'image': image}
        print result
        print '\n'
        return result
    else:
        print 'No restaurants found for %s' % location
        return 'No restaurants found'
def findARestaurant(mealType, location):
    latitude, longitude = getGeocodeLocation(location)
    url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20180420&ll=%s,%s&query=%s' 
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude, mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
    
    if result['response']['venues']:
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id'] 
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address
        
        url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20180420&client_secret=%s' % ((venue_id, foursquare_client_id, foursquare_client_secret)))
        result = json.loads(h.request(url, 'GET')[1])

        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            imageURL = "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cheeseburger.jpg"
        restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
        print "Restaurant Name: %s" % restaurantInfo['name']
        print "Restaurant Address: %s" % restaurantInfo['address']
        print "Image: %s \n" % restaurantInfo['image']
        return restaurantInfo
    else:
        print "No Restaurants Found for %s" % location
        return "No Restaurants Found"
Пример #7
0
def findARestaurant(mealType,location):
	#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
	geo=getGeocodeLocation(location)
	#2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
	#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
	client_id="OKU5DPCCSVTEIHLZQBXOLCOLINZF2JCMYPDYJHUXIKAYCKDX"
	client_secret="53I453NZJEBEVSCXUIMYYXGBBDXDFFCUYHYPQVFKA5M5XS43"
	url=('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20160412&ll=%s,%s&query=%s'%(client_id,client_secret,geo[0],geo[1],mealType))
	h=httplib2.Http()
	resultFound=json.loads(h.request(url,'GET')[1])
	if resultFound['response']['venues']:
	#3. Grab the first restaurant
		restaurant=resultFound['response']['venues'][0]
		venue_id=restaurant['id']
		restaurant_name=restaurant['name']
		restaurant_address = restaurant['location']['formattedAddress']
		url=('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20160412'%(venue_id,client_id,client_secret))
		result=json.loads(h.request(url,'GET')[1])
		address=""
		for i in restaurant_address:
			address +=i+" "
		restaurant_address=address
	#4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
		if result['response']['photos']['items']:
			firstpicture=result['response']['photos']['items'][0]
			prefix=firstpicture['prefix']
			suffix=firstpicture['suffix']
			imageURL=prefix+"300x300"+suffix
		else:
			imageURL = "https://www.google.com"

		restaurantInfo={'name':restaurant_name,'address':restaurant_address,'image':imageURL}
		return restaurantInfo
	else:
		return "NO Restaurant Found!"
Пример #8
0
def MakeMealRequest(mealType,meal_time,Location):
    user_id = g.user.id
    (longitude,latitude) = getGeocodeLocation(Location)
    request = Request(user_id = user_id, location_string = Location, latitude = latitude, longitude = longitude, meal_time= meal_time, filled = False)
    session.add(request)
    session.commit()
    return "Request was stored"
Пример #9
0
def findARestaurant(mealType, location):
    coord = getGeocodeLocation(location)
    coordString = '{},{}'.format(coord['lat'], coord['lng'])
    restaurant = getRestaurant(mealType, coordString)
    picture = getVenuePicture(restaurant['id'])
    try:
        if 'name' in restaurant:
            restaurant_name = restaurant['name']
            if 'address' in restaurant:
                restaurant_address = restaurant['location']['address']
            elif len(restaurant['location']['formattedAddress']) > 0:
                restaurant_address = restaurant['location'][
                    'formattedAddress'][0]
            else:
                restaurant_address = 'Restaurant Address unavailable.'
            restaurantInfo = {
                'name': restaurant_name,
                'address': restaurant_address,
                'image': picture
            }
            return restaurantInfo
        else:
            return 'Unable to find a restaurant.'
    except Exception as e:
        return 'Error while processing your request.'
Пример #10
0
def findARestaurant(mealType, location):
    geoloc = getGeocodeLocation(location)
    ll = '%.2f' % geoloc[0] + ',' + '%.2f' % geoloc[1]
    url = 'https://api.foursquare.com/v2/venues/search?client_id='
    url += '%s&client_secret=%s&v=20130815&ll=%s&radius=100000&intent=browse&limit=1&query=%s' % (
        foursquare_client_id, foursquare_client_secret, ll, mealType)

    h = httplib2.Http()
    response, content = h.request(url, 'GET')
    result = json.loads(content)
    if result['response']['venues']:
        venue = result['response']['venues'][0]
        name = venue['name']
        ven_id = venue['id']
        img = getImage(ven_id)
        formaddress = venue['location']['formattedAddress']
        address = ''
        for x in formaddress:
            address += x
            address += ' '
        print 'Name: ' + name
        print 'Address: ' + address
        print 'Image URL: ' + img
        rest_data = {'name': name, 'address': address, 'image': img}
        return rest_data
    else:
        print 'No Restuarant Found'
        return 'No Restuarant Found'
Пример #11
0
def Makerequest(id):
    user = session.query(User).filter_by(id=id).first()
    if request.method=='POST':
        location=request.form['location']
        if location=="" or request.form['meal_type']==""or request.form['date']=="" or request.form['time']=="":
           flash('this two input should not be empty')
           return render_template('RequestPage.html',user=user)
        latitude,longitude=getGeocodeLocation(location)
        if latitude=="zero":
           flash('Sorry,can not find your location')
           return render_template('RequestPage.html',user=user)
        restaurant_info=findARestaurant(request.form['meal_type'],location)
        if restaurant_info=="No Restaurants Found":
           flash('Sorry,can not find the target restaurant according your meal type')
           return render_template('RequestPage.html',user=user)
        meal_time=request.form['date']+request.form['time']
        Re=Request(user_id=id)
        Re.meal_type=request.form['meal_type']
        Re.latitude=latitude
        Re.longitude=longitude
        Re.location_string=location
        session.add(Re)
        session.commit()
        return render_template('RequestPage.html',user=user)
    else:
        return render_template('RequestPage.html',user=user)
Пример #12
0
def findARestaurant(mealType, location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.

    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi

    #3. Grab the first restaurant
    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
    #5. Grab the first image
    #6. If no image is available, insert default a image url
    #7. Return a dictionary containing the restaurant name, address, and image url
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    latitude, longitude = getGeocodeLocation(location)
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude,
           mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    if result['response']['venues']:
        #3.  Grab the first restaurant
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id']
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address
        #4.  Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        url = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s'
            % ((venue_id, foursquare_client_id, foursquare_client_secret)))
        result = json.loads(h.request(url, 'GET')[1])
        #5.  Grab the first image
        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            #6.  if no image available, insert default image url
            imageURL = "http://www.koekjeswereld.nl/wp-content/uploads/2015/04/OTooles-burger-300x300.jpg"
        #7.  return a dictionary containing the restaurant name, address, and image url
        restaurantInfo = {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': imageURL
        }
        print "Restaurant Name: %s" % restaurantInfo['name']
        print "Restaurant Address: %s" % restaurantInfo['address']
        print "Image: %s \n" % restaurantInfo['image']
        return restaurantInfo
    else:
        print "No Restaurants Found for %s" % location
        return "No Restaurants Found"
Пример #13
0
def findARestaurant(mealType, location):
    # 1. Use getGeocodeLocation to get the latitude and longitude coordinates
    # of the location string.
    latitude, longitude = getGeocodeLocation(location)
    # 2. Use foursquare API to find a nearby restaurant with the latitude,
    # longitude, and mealType strings
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude,
           mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # return result
    if result['response']['venues']:
        # return "YES"
        # return result['response']['venues'][0]
        # 3. Grab the first Restaurant
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id']
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        # return restaurant_address
        address = ''
        for i in restaurant_address:
            address += i

        restaurant_address = address
        # return restaurant_address
        # 4. Get a  300x300 picture of the restaurant using the venue_id (you
        # can change this by altering the 300x300 value in the URL or replacing
        # it with 'orginal' to get the original picture
        url = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s'
            % ((venue_id, foursquare_client_id, foursquare_client_secret)))
        result = json.loads(h.request(url, 'GET')[1])

        # 5.  Grab the first image
        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            # 6.  if no image available, insert default image url
            imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"

        # 7.  return a dictionary containing the restaurant name, address, and
        # image url
        restaurant_info = {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': imageURL
        }
        return restaurant_info
    else:
        print "No Restaurants Found for %s" % location
        return "No Restaurants Found"
def findARestaurant(mealType, location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    lat, lng = getGeocodeLocation(location)

    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    foursquare_token = "TOKEN_ID"  # see example in FS docs, not to be used in production code
    foursquare_v = "V_ID"  # sample issued as YYYYMMDD date, not to be used in production code
    foursquare_ll = "%s,%s" % (lat, lng)
    foursquare_url = "https://api.foursquare.com/v2/venues/explore?oauth_token=%s&v=%s&query=%s&ll=%s" % (
        foursquare_token, foursquare_v, mealType, foursquare_ll)
    h = httplib2.Http()
    response, body = h.request(foursquare_url, "GET")
    data = json.loads(body)

    if not data['response']['groups']:
        return None

    #3. Grab the first restaurant
    restaurant_name = data['response']['groups'][0]['items'][0]['venue'][
        'name']
    restaurant_id = data['response']['groups'][0]['items'][0]['venue']['id']
    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
    img_dimensions = (300, 300)

    # not stated in instructor comments but in quiz answer - format the address
    address = ""
    for line in data['response']['groups'][0]['items'][0]['venue']['location'][
            'formattedAddress']:
        address += ", %s" % line

    #5. Grab the first image
    try:
        img_url = "https://api.foursquare.com/v2/venues/%s/photos?oauth_token=%s&v=%s" % (
            restaurant_id, foursquare_token, foursquare_v)
        img_data = json.loads(h.request(
            img_url, "GET")[1])  # JSONify the body, returned at index 1
        # FS API
        img_src = img_data['response']['photos']['items'][0][
            'prefix'] + "%sx%s" % (img_dimensions[0], img_dimensions[
                1]) + img_data['response']['photos']['items'][0]['suffix']

    #6. If no image is available, insert default a image url
    except:
        img_src = "https://placebear.com/%s/%s" % (img_dimensions[0],
                                                   img_dimensions[1])

    #7. Return a dictionary containing the restaurant name, address, and image url
    restaurant = {
        'name': restaurant_name,
        'id': restaurant_id,
        'address': address,
        'img': img_src
    }
    print(restaurant)
    return restaurant
Пример #15
0
def findARestaurant(mealType, location):
    ll = getGeocodeLocation(location)
    url = 'https://api.foursquare.com/v2/venues/search?'
    params = {
        'client_id': foursquare_client_id,
        'client_secret': foursquare_client_secret,
        'v': 20180323,
        'll': '{},{}'.format(ll[0], ll[1]),
        'radius': 2000,
        'intent': 'browse',
        'query': mealType,
        'limit': 1
    }
    url += urlencode(params)

    h = httplib2.Http()
    data = json.loads(h.request(url, 'GET')[1])
    # print(data)

    venues = data['response']['venues']
    if len(venues) == 0:
        print('No {} in {}'.format(mealType, location))
        print()
        return

    name = data['response']['venues'][0]['name']
    address = data['response']['venues'][0]['location']['address']
    venue_id = data['response']['venues'][0]['id']

    url = 'https://api.foursquare.com/v2/venues/{}/photos?'.format(venue_id)
    params = {
        'client_id': foursquare_client_id,
        'client_secret': foursquare_client_secret,
        'v': 20180323,
        'group': 'venue',
        'limit': 1
    }
    url += urlencode(params)

    h = httplib2.Http()
    data = json.loads(h.request(url, 'GET')[1])
    # print(data)

    count = data['response']['photos']['count']
    if count == 0:
        image = 'http://default'
    else:
        image = data['response']['photos']['items'][0]['prefix']
        image += '300x300'
        image += data['response']['photos']['items'][0]['suffix']
        image = image.replace('\/', '/')

    print(name)
    print(address)
    print(image)
    print()
Пример #16
0
def findARestaurant(mealType, location):
	#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
	google_latitude, google_longitude = getGeocodeLocation(location)
	foursquare_coordinate = (round(google_latitude, 2), round(google_longitude, 2))
	# For debugging, print coordinate to terminal
	# print foursquare_coordinate[0], foursquare_coordinate[1]

	#2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
	#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
	url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20180903&intent=browse&ll=%s,%s&radius=5000&query=%s' % (foursquare_client_id, foursquare_client_secret, foursquare_coordinate[0], foursquare_coordinate[1], mealType))
	h = httplib2.Http()
	# can print [0], but must jsonify [1], otherwise error!
	result = json.loads(h.request(url, 'GET')[1])
	# print result

	# To make sure at least one restaurant is found
	if result['response']['venues']:
		#3. Grab the first restaurant
		first_restaurant = result['response']['venues'][0]
		venue_id = first_restaurant['id']
		restaurant_name = first_restaurant['name']
		restaurant_address = first_restaurant['location']['formattedAddress']
		# Convert the current restaurant_address (a list) to a string
		updated_address = ""
		for partial_address in restaurant_address:
			updated_address += partial_address + ", "
		# Remove the last comma and space (", ") in the updated_address
		updated_address = updated_address[:-2]
		restaurant_address = updated_address

		#4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
		photo_url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20180903' % (venue_id, foursquare_client_id, foursquare_client_secret))
		photo_result = json.loads(h.request(photo_url, 'GET')[1])

		#5. Grab the first image
		if photo_result['response']['photos']['items']:
			restaurant_first_picture = photo_result['response']['photos']['items'][0]
			prefix = restaurant_first_picture['prefix']
			suffix = restaurant_first_picture['suffix']
			restaurant_picture_url = prefix + "300x300" + suffix

		#6. If no image is available, insert default a image url
		else:
			restaurant_picture_url = 'https://upload.wikimedia.org/wikipedia/commons/6/6d/Good_Food_Display_-_NCI_Visuals_Online.jpg'

		#7. Return a dictionary containing the restaurant name, address, and image url
		restaurant_info = {'name': restaurant_name, 'address': restaurant_address, 'image': restaurant_picture_url}
		print "Restaurant Name: %s" % restaurant_info['name']
		print "Restaurant Address: %s" % restaurant_info['address']
		print "Restaurant Image: %s \n" % restaurant_info['image']
		return restaurant_info

	else:
		print "Sorry! No Restaurants found near %s" % location
		return "No Restaurants Found!"
Пример #17
0
def findARestaurant(mealType, location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    coordinates = getGeocodeLocation(location)
    coordinates = ','.join(map(str, coordinates))
    # print coordinates
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20180814&ll=%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, coordinates,
           mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    # print result
    if result['response']['venues']:
        #3. Grab the first restaurant
        restaurantName = result['response']['venues'][0]['name']
        restaurantAddress = result['response']['venues'][0]['location'][
            'formattedAddress']
        address = ""
        for i in restaurantAddress:
            address += i + " "
        restaurantAddress = address
        # print restaurantAddress
        #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        restaurantVenueID = result['response']['venues'][0]['id']
        picURL = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20180814'
            % (restaurantVenueID, foursquare_client_id,
               foursquare_client_secret))
        result = json.loads(h.request(picURL, 'GET')[1])
        # print restaurantVenueID
        #5. Grab the first image
        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            #6.  if no image available, insert default image url
            imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
        #7.  return a dictionary containing the restaurant name, address, and image url
        restaurantInfo = {
            'name': restaurantName,
            'address': restaurantAddress,
            'image': imageURL
        }
        print "Restaurant Name: %s" % restaurantInfo['name']
        print "Restaurant Address: %s" % restaurantInfo['address']
        print "Image: %s \n" % restaurantInfo['image']
        return restaurantInfo
    else:
        print "No Restaurants Found for %s" % location
        return "No Restaurants Found"
def findARestaurant(mealType,location):
    coordinates = getGeocodeLocation(location)
    lat = coordinates[0]
    lng = coordinates[1]
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    #https://api.foursquare.com/v2/venues/search?v=20161016&ll=38.897478%2C%20-77.000147&query=donuts&intent=browse&radius=10&client_id=F1OAP3TOGKR1HGKPVHV44NOZXRY0XSIA45MCUEWRZ13EJW43&client_secret=MQFJB1QUTLDXAW3PSYUCSEUAJ2GVIXJDSBZNTBURJFQWCPHM
    url = ('https://api.foursquare.com/v2/venues/search?v=20161016&ll={}%2C%{}&query={}&intent=browse&radius=555&client_id={}&client_secret={}'.format(lat, lng, mealType, foursquare_client_id, foursquare_client_secret))
    h = httplib2.Http()
    response, content = h.request(url, 'GET')
    result = json.loads(content)
    print(result)
Пример #19
0
def findARestaurant(mealType,location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi

    #3. Grab the first restaurant
    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
    #5. Grab the first image
    #6. If no image is available, insert default a image url
    #7. Return a dictionary containing the restaurant name, address, and image url

    lat, lng = getGeocodeLocation(location)
    url = 'https://api.foursquare.com/v2/venues/search'
    params = dict(
        client_id=foursquare_client_id,
        client_secret=foursquare_client_secret,
        v=datetime.datetime.now().strftime("%Y%m%d"),
        ll=str(lat)+","+str(lng),
        query=mealType,
        limit=1
        )
    resp = requests.get(url=url, params=params)
    venue = json.loads(resp.text)['response']['venues'][0]
    
    venue_id = venue['id']
    pictureUrl = ('https://api.foursquare.com/v2/venues/%s/photos'
                  % venue_id)
    pic_params = dict(
        venue_id=venue_id,
        client_id=foursquare_client_id,
        client_secret=foursquare_client_secret,
        v=datetime.datetime.now().strftime("%Y%m%d"),
        limit=1
        )
    pic_resp = requests.get(url=pictureUrl, params=pic_params)
    picture = json.loads(pic_resp.text)['response']['photos']['items']
    
    if ( picture ):
        pic_link = picture[0]['prefix'] + "300x300" + picture[0]['suffix']
    else:
        pic_link = 'http://via.placeholder.com/300x300?text=placeholder'

    address = ""
    for s in venue['location']['formattedAddress']:
        address += s + " "
    info = {
        'name': venue['name'],
        'address': address,
        'image_url': pic_link
        }
    print("Restaurant Name: %s\nRestaurant Address: %s\nImage: %s\n" %(info['name'], info['address'], info['image_url']) )
    return info
def findARestaurant(mealType, location):
    # 1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    latitude, longitude = getGeocodeLocation(location)

    # 2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    # HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&ll={},{}&query={}&v=20180522'.format(
        foursquare_client_id, foursquare_client_secret, latitude, longitude,
        mealType)

    h = httplib2.Http()
    response, content = h.request(url)
    result = json.loads(content)

    if result['response']['venues']:
        # 3. Grab the first restaurant
        first_restaurant = result.get('response').get('venues')[0]

        # 4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture

        url = 'https://api.foursquare.com/v2/venues/{}/photos?client_id={}&client_secret={}&v=20180522'.format(
            first_restaurant.get('id'), foursquare_client_id,
            foursquare_client_secret)
        result = json.loads(h.request(url)[1])
        # 5. Grab the first image
        if result['response']['photos']['items']:
            first_picture = result['response']['photos']['items'][0]
            prefix = first_picture['prefix']
            suffix = first_picture['suffix']
            imageURL = prefix + "300x300" + suffix
        # 6. If no image is available, insert default a image url
        else:
            imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"

        # 7. Return a dictionary containing the restaurant name, address, and image url
        restaurant_address = ""
        for i in first_restaurant['location']['formattedAddress']:
            restaurant_address += i + " "

        restaurant_info = {
            'name': first_restaurant['name'],
            'address': restaurant_address,
            'image': imageURL
        }

        print("Restaurant name : {}".format(restaurant_info['name']))
        print("Restaurant address : {}".format(restaurant_address))
        print("Image : {}".format(restaurant_info['image']))
        return restaurant_info
    else:
        print("No restaurants for {}".format(location))
        return "No restaurants found"
Пример #21
0
def findARestaurant(mealType,location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    (lat,lon) = getGeocodeLocation(location)
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url_fsquare = ('https://api.foursquare.com/v2/venues/search?client_id={CL_ID}&client_secret={CL_SEC}&ll={LAT},{LON}&query={QUERY}&v=20160414&m=foursquare'.format(
        QUERY=mealType,
        CL_ID=foursquare_client_id,
        CL_SEC=foursquare_client_secret,
        LAT=lat,
        LON=lon))
    # print url_fsquare
    h = httplib2.Http()
    #3. Grab the first restaurant
    result = json.loads(h.request(url_fsquare,'GET')[1])


    if result['response']['venues']:
        #3.  Grab the first restaurant
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id'] 
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address
            #4.  Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        url = ('https://api.foursquare.com/v2/venues/{V_ID}/photos?client_id={CL_ID}&v=20160414&m=foursquare&client_secret={CL_SEC}'.format(
                        V_ID=venue_id,
                        CL_ID=foursquare_client_id,
                        CL_SEC=foursquare_client_secret))
        result = json.loads(h.request(url, 'GET')[1])
        #5.  Grab the first image

        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            #6.  if no image available, insert default image url
            imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"

        restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
        print "Restaurant Name: %s" % restaurantInfo['name']
        print "Restaurant Address: %s" % restaurantInfo['address']
        print "Image: %s \n" % restaurantInfo['image']
        return restaurantInfo
    else:
        print "No Restaurants Found for %s" % location
        return "No Restaurants Found"
Пример #22
0
def findARestaurant(mealType,location):
	#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
	latitude, longitude = getGeocodeLocation(location)
	#2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
	#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
	url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' % (foursquare_client_id, foursquare_client_secret,latitude,longitude,mealType))
	h = httplib2.Http()
	result = json.loads(h.request(url,'GET')[1])
	if __name__ == '__main__':
	if result['response']['venues']:
		#3.  Grab the first restaurant
		restaurant = result['response']['venues'][0]
		venue_id = restaurant['id'] 
		restaurant_name = restaurant['name']
		restaurant_address = restaurant['location']['formattedAddress']
		address = ""
		for i in restaurant_address:
			address += i + " "
		restaurant_address = address
		#4.  Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
		url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
		result = json.loads(h.request(url, 'GET')[1])
		#5.  Grab the first image
		if result['response']['photos']['items']:
			firstpic = result['response']['phoif __name__ == '__main__':tos']['items'][0]
			prefix = firstpic['prefix']
			suffix = firstpic['suffix']
			imageURL = prefix + "300x300" + suffix
		else:
			#6.  if no image available, insert default image url
			imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
		#7.  return a dictionary containing the restaurant name, address, and image url
		restaurantInfo = {'name':restaurant_name, 'address':restaurant_address, 'image':imageURL}
		print "Restaurant Name: %s" % restaurantInfo['name']
		print "Restaurant Address: %s" % restaurantInfo['address']
		print "Image: %s \n" % restaurantInfo['image']
		return restaurantInfo
	else:
		print "No Restaurants Found for %s" % location
		return "No Restaurants Found"

if __name__ == '__main__':
	findARestaurant("Pizza", "Tokyo, Japan")
	findARestaurant("Tacos", "Jakarta, Indonesia")
	findARestaurant("Tapas", "Maputo, Mozambique")
	findARestaurant("Falafel", "Cairo, Egypt")
	findARestaurant("Spaghetti", "New Delhi, India")
	findARestaurant("Cappuccino", "Geneva, Switzerland")
	findARestaurant("Sushi", "Los Angeles, California")
	findARestaurant("Steak", "La Paz, Bolivia")
	findARestaurant("Gyros", "Sydney, Australia")
def findARestaurant(location, mealType):
    location = input("Type the location!")
    mealType = input("Type the meal!")

    latitude, longitude = getGeocodeLocation(location)
    longlat = str(longitude) + ',' + str(latitude)

    params = dict(client_id=foursquare_client_id,
                  client_secret=foursquare_client_secret,
                  v='20180327',
                  ll=longlat,
                  query=mealType,
                  limit=1)

    resp = requests.get(url=url, params=params)
    data = json.loads(resp.text)
    rest_data = data['response']['groups']
    restaurant = data['response']['groups'][0]['items'][0]['venue']
    if restaurant:
        restaurant_id = restaurant['id']
        restaurant_name = restaurant['name']
        unformatted_add = restaurant['location']['formattedAddress']
        restaurant_address = ""
        for item in unformatted_add:
            restaurant_address += item
            restaurant_address += " "

    # getting the picture url
    h = httplib2.Http()
    # building the url
    picture_url = (
        'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s'
        % ((restaurant_id, foursquare_client_id, foursquare_client_secret)))
    # request the picture data in a json format
    result = json.loads(h.request(picture_url, 'GET')[1])
    photo_data = result['response']['photos']['items'][0]
    # if there is a photo
    if photo_data:
        prefix = photo_data['prefix']
        suffix = photo_data['suffix']
        photo_url = prefix + '300x300' + suffix
    # if there is no photo
    else:
        photo_url = "https://cdn.pixabay.com/photo/2016/11/18/14/05/brick-wall-1834784_1280.jpg"
    restaurant_info = {
        'name': restaurant_name,
        'address': restaurant_address,
        'picture': photo_url
    }
    print(restaurant_info)
Пример #24
0
def findARestaurant(mealType, location):
    # Step 1: Use getGeocodeLocation to get the latitude and longitude coordinates of the location inputString
    latitude, longitude = getGeocodeLocation(location)

    # Step 2: Use Foursquare API to find a nearby restaurant with the latitude, longitude and mealType strings
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20151229&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude,
           mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # Step 3: Grab the first restaurant
    if result['response']['venues']:
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id']
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address

        # Step 4: Get a 300x300 picture of the restaurant using venue_id
        url = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20151229&client_secret=%s'
            % (venue_id, foursquare_client_id, foursquare_client_secret))
        result = json.loads(h.request(url, 'GET')[1])

        # Step 5: Grab the first image
        if result['response']['photos']['items']:
            pic = result['response']['photos']['items'][0]
            prefix = pic['prefix']
            suffix = pic['suffix']
            picurl = prefix + "300x300" + suffix

    # Step 6: If no image is available, insert default image URL
        else:
            picurl = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"

    # Stpe 7: Return a dict containing the restaurant information
        restaurant_info = {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': picurl
        }
        return restaurant_info

    else:
        print "No restaurant found for %s" % (location)
Пример #25
0
def findARestaurant(mealType, location):

    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    coordinates = getGeocodeLocation(location)

    lat = str(coordinates[0])
    lon = str(coordinates[1])

    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, lat, lon, mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    #3. Grab the first restaurant
    restaurant = result['response']['venues'][0]
    # print restaurant['location']['formattedAddress'][0]

    restaurant_id = restaurant['id']

    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
    photo_url = (
        'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20130815'
        % (restaurant_id, foursquare_client_id, foursquare_client_secret))
    photos = json.loads(h.request(photo_url, 'GET')[1])

    #5. Grab the first image
    #6. If no image is available, insert default a image url

    count = photos['response']['photos']['count']

    if count == 0:
        photo = 'http://www.pizzahut-tt.com/wp-content/uploads/2013/06/pizza-hut-trinidad-and-tobago-pepperoni-lovers-pizza.png'
    else:
        photo = photos['response']['photos']['items'][0][
            'prefix'] + "300x500" + photos['response']['photos']['items'][0][
                'suffix']

    result_dict = {}
    result_dict['name'] = restaurant['name']
    result_dict['address'] = restaurant['location']['formattedAddress'][0]
    result_dict['photo'] = photo

    #7. Return a dictionary containing the restaurant name, address, and image url
    print result_dict['name']
    print result_dict['address']
    print result_dict['photo']
    return result_dict
Пример #26
0
def findARestaurant(mealType, location):
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    latitude, longitude = getGeocodeLocation(location)
    url = (
        'https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20180824&ll=%s,%s&query=%s'
        % (foursquare_client_id, foursquare_client_secret, latitude, longitude,
           mealType))
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    h = httplib2.Http()
    response, content = h.request(url, 'GET')
    result = json.loads(content)
    #3. Grab the first restaurant
    if result['response']['venues']:
        restaurant = result['response']['venues'][0]
        venue_id = restaurant['id']
        restaurant_name = restaurant['name']
        restaurant_address = restaurant['location']['formattedAddress']
        address = ''
        for i in restaurant_address:
            address = address + i + ' '
        restaurant_address = address

        #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        imageurl = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20180824'
            % (venue_id, foursquare_client_id, foursquare_client_secret))
        imgresponse, imgcontent = h.request(imageurl, 'GET')
        imgresult = json.loads(imgcontent)
        #5. Grab the first image
        if imgresult['response']['photos']['items']:
            firstimg = imgresult['response']['photos']['items'][0]
            prefix = firstimg['prefix']
            suffix = firstimg['suffix']
            imgurl = prefix + '300*300' + suffix
        else:
            #6. If no image is available, insert default a image url
            imgurl = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
        restaurant_info = {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': imgurl
        }
        # print 'Restaurant Name: %s' % restaurant_info['name']
        # print 'Restaurant Address: %s' % restaurant_info['address']
        # print 'Image: \n %s \n' % restaurant_info['image']
        return restaurant_info
    else:
        return "No Restaurants Found"
Пример #27
0
def findARestaurant(mealType, location):
    # 1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    lat, lng = getGeocodeLocation(location)

    # 2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    # HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = (
        "https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&ll=%s,%s&query=%s&limit=1&v=20170130"
        % (foursquare_client_id, foursquare_client_secret, lat, lng, mealType))

    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])

    # 3. Grab the first restaurant
    restaurant = result['response']['venues'][0]

    if restaurant:

        restaurant_name = restaurant['name']
        restaurant_address = ' '.join(
            restaurant['location']['formattedAddress'])

        venue_id = restaurant['id']

        # 4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
        url = url = (
            "https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&limit=1&v=20170130"
            % (venue_id, foursquare_client_id, foursquare_client_secret))
        h = httplib2.Http()
        result = json.loads(h.request(url, 'GET')[1])

        # 5. Grab the first image
        if result['response']['photos']['items']:
            image = result['response']['photos']['items'][0]
            image_url = image['prefix'] + '300x300' + image['suffix']
        else:
            # 6. If no image is available, insert default a image url
            image_url = 'http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct'

        # 7. Return a dictionary containing the restaurant name, address, and image url
        return {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': image_url
        }

    else:
        print 'No restaurant found for %s' % location
        return None
Пример #28
0
def venues(stringlocation, mealtype=None, limit=6):
    if mealtype is None:
        mealtype = random.choice(query_mealtype)
    ll = getGeocodeLocation(stringlocation, None)
    ownvenue = client.venues.search(params={
        'limit': limit,
        'll': ll,
        'query': mealtype
    })
    p = ownvenue['venues']
    result = []
    for n in p:
        this = {}
        hours = client.venues.hours(n['id'])
        hours = hours['hours']
        photo = client.venues.photos(n['id'], params={'limit': 3})
        photo = photo['photos']
        this['name'] = n['name']
        try:
            this['url'] = n['url']
        except:
            'No have url'
        try:
            this['location'] = n['location']['formattedAddress'][0]
        except:
            'No have location'
        try:
            this['menu_url'] = n['menu']['url']
        except:
            'No have Menu'
        try:
            for h in hours['timeframes']:
                this['days'] = h['days']
                this['open'] = h['open']
        except:
            'No Have Timeframes'

        try:
            for p in photo['items']:
                prefix = p['prefix']
                suffix = p['suffix']
                imageURL = prefix + "300x300" + suffix
                this['picture'] = imageURL
        except:
            'No have image'

        result.append(this)
    return result
Пример #29
0
def specificRequestMeal(request_id):
    mealRequest = session.query(RequestMeal).filter_by(id=request_id).first()

    if request.method == 'GET':
        return jsonify(
            {
                'user_id': mealRequest.user_id,
                'meal_type': mealRequest.meal_type,
                'location_string': mealRequest.location_string,
                'latitude': mealRequest.latitude,
                'longditude': mealRequest.longditude,
                'meal_time': mealRequest.meal_time,
                'filled': filled
            }, 201)

    elif request.method == 'PUT':
        meal_type = request.json.get("meal_type")
        location_string = request.json.get("location_string")
        meal_time = request.json.get("meal_time")

        if meal_type:
            mealRequest.meal_type = meal_type
        if location_string:
            mealRequest.location_string = location_string
            latitude, longditude = getGeocodeLocation(location_string)
            mealRequest.latitude = latitude
            mealRequest.longditude = longditude
        if meal_time:
            mealRequest.meal_time = meal_time

        session.commit()

        return jsonify(
            {
                'user_id': mealRequest.user_id,
                'meal_type': mealRequest.meal_type,
                'location_string': mealRequest.location_string,
                'latitude': mealRequest.latitude,
                'longditude': mealRequest.longditude,
                'meal_time': mealRequest.meal_time,
                'filled': filled
            }, 201)

    elif request.method == 'DELETE':
        session.delete(mealRequest)
        session.commit()

        return 'The request deleted'
Пример #30
0
def Makerequest(id):
    user = session.query(User).filter_by(id=id).first()
    if request.method == 'POST':
        location = request.form['location']
        latitude, longitude = getGeocodeLocation(location)
        meal_time = request.form['location']
        Re = Request(user_id=id)
        Re.meal_type = request.form['meal_type']
        Re.latitude = latitude
        Re.longitude = longitude
        Re.location_string = location
        session.add(Re)
        session.commit()
        return render_template('RequestPage.html', user=user)
    else:
        return render_template('RequestPage.html', user=user)
Пример #31
0
def weather():
    try:
        ucity = request.form['userCity']
        latitude, longitude = getGeocodeLocation(ucity)
        r = requests.get('https://api.darksky.net/forecast/%s/%s,%s' % (darkapi, latitude, longitude))
        json_object = r.json()
        temp_k = json_object['currently']['temperature']
        temp_f = int(temp_k)
        city = str(ucity)
        sky = str(json_object['currently']['summary'])
        forecast = str(json_object['hourly']['summary'])
        rainchance = int(json_object['currently']['precipProbability'])

        return render_template('weather.html', temp=temp_f, city=city, sky=sky, forecast=forecast, rainchance=rainchance)
    except:
        return render_template('error.html')
Пример #32
0
def findARestaurant(mealType,location):
  
	#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
	lat, lng = getGeocodeLocation(location)
  #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
	#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sush
	url = 'https://api.foursquare.com/v2/venues/search?client_id={}&client_secret={}&v=20180323&ll={},{}&query={}'.format(foursquare_client_id, foursquare_client_secret, lat, lng, mealType)
  
	h = httplib2.Http()

	result = json.loads(h.request(url,'GET')[1])
	
	#3. Grab the first restaurant
	restaurant = result['response']['venues'][0]
	#4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
	url = 'https://api.foursquare.com/v2/venues/{}/photos?client_id={}&client_secret={}&v=20180323'.format(restaurant['id'], foursquare_client_id, foursquare_client_secret)
	
	result = json.loads(h.request(url,'GET')[1])
	
	#5. Grab the first image

	#6. If no image is available, insert default a image url

	if result['response']['photos']['count'] == 0:
		url = 'http://lorempixel.com/300/300'    		
	else:
		photo = result['response']['photos']['items'][0]		
		url = str(photo['prefix'])+'original'+str(photo['suffix'])
    
	name = restaurant['name']
	address = ''
	if 'address' in restaurant['location'].keys():
		address = restaurant['location']['address']
	elif 'cc' in restaurant['location'].keys():
    		address = restaurant['location']['cc']

	#7. Return a dictionary containing the restaurant name, address, and image url	
	print('Restaurant Name: {}'.format(name))
	print('Restaurant Address: {}'.format(address))
	print('Restaurant Photo: {}'.format(url))
	print()

	return {
		'name': name,
		'address': address,
		'image_url': url
	}
Пример #33
0
def findARestaurant(mealType, location):
    coordinates = getGeocodeLocation(location)
    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.

    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = "https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20171110&ll=%s,%s&query=%s" % (
        foursquare_client_id, foursquare_client_secret, coordinates[0],
        coordinates[1], mealType)
    h = httplib2.Http()
    result = json.loads(h.request(url, 'GET')[1])
    return result
    if result['response']['venues']:
        firstRestaurant = result['response']['venues'][0]
        venue_id = firstRestaurant['id']
        restaurant_name = firstRestaurant['name']
        restaurant_address = firstRestaurant['location']['formattedAddress']
        address = ""
        for i in restaurant_address:
            address += i + " "
        restaurant_address = address

        url = (
            'https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20171110&client_secret=%s'
            % (venue_id, foursquare_client_id, foursquare_client_secret))
        result = json.loads(h.request(url, 'GET')[1])
        if result['response']['photos']['items']:
            firstpic = result['response']['photos']['items'][0]
            prefix = firstpic['prefix']
            suffix = firstpic['suffix']
            imageURL = prefix + "300x300" + suffix
        else:
            imageURL = 'http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct'

        restaurantInfo = {
            'name': restaurant_name,
            'address': restaurant_address,
            'image': imageURL
        }
        print "Restaurant Name: %s" % restaurantInfo['name']
        print "Restaurant Address: %s" % restaurantInfo['address']
        print "Image: %s \n" % restaurantInfo['image']
        return restaurantInfo
    else:
        print "No %s Restaurants found for %s" % (mealType, location)
        return "No Restaurants Found"
Пример #34
0
def findARestaurant(mealType,location):

    #1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
    coordinates = getGeocodeLocation(location);

    lat = str(coordinates[0])
    lon = str(coordinates[1])
        
    #2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
    #HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
    url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s'% (foursquare_client_id, foursquare_client_secret, lat, lon, mealType))
    h = httplib2.Http()
    result = json.loads(h.request(url,'GET')[1])
        
    #3. Grab the first restaurant
    restaurant = result['response']['venues'][0]
    # print restaurant['location']['formattedAddress'][0]

    restaurant_id = restaurant['id']

    #4. Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
    photo_url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&client_secret=%s&v=20130815' % (restaurant_id, foursquare_client_id, foursquare_client_secret))
    photos = json.loads(h.request(photo_url,'GET')[1])

    #5. Grab the first image
    #6. If no image is available, insert default a image url

    count = photos['response']['photos']['count']

    if count == 0:
        photo = 'http://www.pizzahut-tt.com/wp-content/uploads/2013/06/pizza-hut-trinidad-and-tobago-pepperoni-lovers-pizza.png'
    else:
        photo = photos['response']['photos']['items'][0]['prefix']+"300x500"+photos['response']['photos']['items'][0]['suffix']

    result_dict = {}
    result_dict['name'] = restaurant['name']
    result_dict['address'] = restaurant['location']['formattedAddress'][0]
    result_dict['photo'] = photo
    
    #7. Return a dictionary containing the restaurant name, address, and image url  
    print result_dict['name']
    print result_dict['address']
    print result_dict['photo']
    return result_dict
Пример #35
0
def findARestaurant(mealType,location):
	#1. Use getGeocodeLocation to get the latitude and longitude coordinates of the location string.
	latitude, longitude = getGeocodeLocation(location)
	
	#2.  Use foursquare API to find a nearby restaurant with the latitude, longitude, and mealType strings.
	#HINT: format for url will be something like https://api.foursquare.com/v2/venues/search?client_id=CLIENT_ID&client_secret=CLIENT_SECRET&v=20130815&ll=40.7,-74&query=sushi
	url = ('https://api.foursquare.com/v2/venues/search?client_id=%s&client_secret=%s&v=20130815&ll=%s,%s&query=%s' %
			(foursquare_client_id,foursquare_client_secret,latitude,longitude,mealType))
	h = httplib2.Http()
	response, content = h.request(url,'GET')
	result = json.loads(content)

	if result['response']['venues']:
		#3. Grab the first restaurant
		firstRestaurant = result['response']['venues'][0]['name']
		venue_id = result['response']['venues'][0]['id']
		address_formatted = result['response']['venues'][0]['location']['formattedAddress']
		address = ''
		for i in address_formatted:
			address += i+" "
		#4.  Get a  300x300 picture of the restaurant using the venue_id (you can change this by altering the 300x300 value in the URL or replacing it with 'orginal' to get the original picture
		url = ('https://api.foursquare.com/v2/venues/%s/photos?client_id=%s&v=20150603&client_secret=%s' % ((venue_id,foursquare_client_id,foursquare_client_secret)))
		result = json.loads(h.request(url, 'GET')[1])
		#5.  Grab the first image
		if result['response']['photos']['items']:
			firstpic = result['response']['photos']['items'][0]
			prefix = firstpic['prefix']
			suffix = firstpic['suffix']
			imageURL = prefix + "300x300" + suffix
		else:
			#6.  if no image available, insert default image url
			imageURL = "http://pixabay.com/get/8926af5eb597ca51ca4c/1433440765/cheeseburger-34314_1280.png?direct"
		#7. Return a dictionary containing the restaurant name, address, and image url
		restaurantInfo = {'name':firstRestaurant, 'address':address, 'image':imageURL}
		print "Restaurant Name: %s" % restaurantInfo['name']
		print "Restaurant Address: %s" % restaurantInfo['address']
		print "Image: %s \n" % restaurantInfo['image']
		return restaurantInfo
	else:
		print "No Restaurants Found for %s" % location
		return "No Restaurants Found"