示例#1
0
def search_places(lat, lng, place_type):
    API_KEY = 'AIzaSyAUlp6OXdNnSlpO56yVru2gt3_6FbW8QS4'
    google_places = GooglePlaces(API_KEY)

    active_latlng = (lat, lng)
    query_result = google_places.nearby_search(lat_lng={'lat': lat, 'lng': lng}, rankby='distance', types=[place_type])

    time.sleep(1.8)

    if query_result.has_next_page_token:
        query_result2 = google_places.nearby_search(lat_lng={'lat': lat, 'lng': lng}, rankby='distance',
                                                    types=[place_type], pagetoken=query_result.next_page_token)

        lista_places = query_result.places + query_result2.places
        time.sleep(1.8)

        if query_result2.has_next_page_token:
            query_result3 = google_places.nearby_search(lat_lng={'lat': lat, 'lng': lng}, rankby='distance',
                                                        types=[place_type], pagetoken=query_result2.next_page_token)

            lista_places = lista_places + query_result3.places
            resultado = compute_results(lista_places, active_latlng)
        else:
            resultado = compute_results(lista_places, active_latlng)

    else:
        lista_places = query_result.places
        resultado = compute_results(lista_places, active_latlng)

    return resultado
示例#2
0
 def get_context_data(self, **kwargs):
     context = super(AddPlacesToDatabaseView, self).get_context_data(**kwargs)
     google_places = GooglePlaces(settings.GOOGLE_API_KEY)
     query_result = google_places.nearby_search(
     location='Philadelphia, PA', keyword='Pool',
     radius=20000)
     for place in query_result.places:
         next_result = google_places.nearby_search(
             location=place.vicinity, keyword='Pool',
             radius=20000)
         for place2 in next_result.places:
             pool2  = Pool.objects.create()
             pool2.name = place2.name
             pool2.address = place2.vicinity +" , USA" #Add this to make it work with our map db (?not sure if we need this)
             pool2.geolocation.lat = place2.geo_location['lat']
             pool2.geolocation.lon= place2.geo_location['lng']
             #I have no idea what I am doing! --MG
             if place2.rating is None:
                 pool2.rating = 0.0
             else:
                 pool2.rating = float(place2.rating)
             pool2.save()
         pool = Pool.objects.create()
         pool.name = place.name
         pool.address = place.vicinity +" , USA" #Add this to make it work with our map db (?not sure if we need this)
         pool.geolocation.lat = place.geo_location['lat']
         pool.geolocation.lon= place.geo_location['lng']
         #I have no idea what I am doing! --MG
         if place.rating is None:
             pool.rating = 0.0
         else:
             pool.rating = float(place.rating)
         pool.save()
     context['places_count'] = len(query_result.places)
     return context
def findClients(wanted_location, keywords, max_radius) -> Dict:
    clients = {}
    API_KEY = ''
    google_places = GooglePlaces(API_KEY)

    query_result = google_places.nearby_search(location=wanted_location,
                                               keyword=keywords,
                                               radius=max_radius,
                                               types=[types.TYPE_FOOD])

    for place in query_result.places:
        place.get_details()

        if not place.website:  #Checks if place does NOT have a website
            clients[place.name] = place.local_phone_number
            #Dict key = place name, val = place number

        # Are there any additional pages of results?
    if query_result.has_next_page_token:
        query_result_next_page = google_places.nearby_search(
            pagetoken=query_result.next_page_token)

    #This returns all locations as the values to locations, and all numbers as the values to numbers
    #I wanted it to return the key value pairs separately
    num_locations = len(clients.keys())

    returning = " We found " + str(
        num_locations
    ) + " locations without a website/\nLocations:{} | Phone Numbers:{}".format(
        clients.keys(), clients.values())

    #for client in clients:
    #    b = "Location:{} | Phone Number:{}".format(client,clients[client])

    return clients
示例#4
0
def myplan2():

    if "loggedIn" not in session.keys():
        return redirect(url_for(index))

    if not session["loggedIn"]:
        return redirect(url_for('index'))

    users = []
    postlist = []
    connection = dbconnect()
    values = [session['group_id']]
    fetch = connection.execute('SELECT * FROM posts where group_id=%s ORDER BY time ASC', values)
    for row in fetch:
        users.append(row['username'])
        postlist.append(row['post'])
    dbclose(connection)

    details = []
    if request.method == "POST":
        if request.form['submit'] == 'submit':
            location = request.form['place']
            keyword = request.form['search_string']
            type = request.form['type']
            radius = 4000
            API_KEY = 'PASTE YOUR GOOGLE PLACES API_KEY HERE'
            details = []
            google_places = GooglePlaces(API_KEY)
            page_token = ''
            query_result = google_places.nearby_search(
                location=location, keyword=keyword,
                radius=radius, pagetoken=page_token, type=[type])

            for place in query_result.places:
                place.get_details()
                if place.international_phone_number:
                    #print (
                     #place.name + ' ' + place.vicinity + '   rating :' + str(
                         #place.rating) + '  ' + place.international_phone_number)
                    details.insert(0, {'name': place.name, 'address': place.vicinity, 'rating': str(place.rating),
                                   'phone': place.international_phone_number, 'url': place.url})

            while query_result.has_next_page_token:
                 query_result = google_places.nearby_search(
                    location=location, keyword=keyword,
                    radius=radius, pagetoken=page_token, type=[type])

                 if query_result.has_next_page_token:
                         page_token = query_result.next_page_token
                 for place in query_result.places:
                    place.get_details()
                    if place.international_phone_number:
                        #print (place.name + ' ' + place.vicinity + '   rating :' + str(
                        #   place.rating) + '  ' + place.international_phone_number)
                        details.insert(0, {'name': place.name, 'address': place.vicinity, 'rating': str(place.rating),
                            'phone': place.international_phone_number, 'url': place.url})

    temp = zip(users, postlist)
    return render_template('myplan.html', username=session['shortname'], details=details, temp=temp)
示例#5
0
def poll_restaurants_nearbye():
    from googleplaces import GooglePlaces, types, lang
    import pandas as pd
    import requests
    import time
    # Api Keys
    api_keys = pd.read_csv("C:/Users/J/api_keys.csv")
    google_geo_api_key = api_keys['key_value'][api_keys.key_name ==
                                               'google_places_api_key'].item()
    google_places_api_key = api_keys['key_value'][api_keys.key_name ==
                                                  'google_geo_api_key'].item()
    # Getting search criteria
    add = input("What is your full address (exlude apt)? ")
    add_f = add.replace(' ', '+')
    lat_long_info = requests.get(
        'https://maps.googleapis.com/maps/api/geocode/json?address=' + add_f +
        '&key=' + google_geo_api_key)
    results = lat_long_info.json()['results']
    lat, lon = results[0]['geometry']['location']['lat'], results[0][
        'geometry']['location']['lng']
    google_places = GooglePlaces(google_places_api_key)
    result = google_places.nearby_search(pagetoken=None,
                                         location=add,
                                         lat_lng={
                                             'lat': lat,
                                             'lng': lon
                                         },
                                         radius=100,
                                         keyword='restaurant',
                                         rankby='distance',
                                         type=['restaurant'])
    rests = list(map(lambda x: x.name, result.places))
    while result.has_next_page_token:
        time.sleep(10)
        result = google_places.nearby_search(
            pagetoken=result.next_page_token,
            lat_lng={
                'lat': lat,
                'lng': lon
            },
        )
        rests2 = list(map(lambda x: x.name, result.places))
    # Match with restaurants inside dataset - but then will have to
    rests = rests + rests2
    kept_rests = process_liked_restaurants(rests)

    # Polling on likes / dislikes this week
    incl_rests = []
    for place in kept_rests:
        ans = int(
            input("Would you like to eat at " + place + " this week? (1/0)"))
        if ans == 1:
            incl_rests.append(place)
        else:
            pass

    return incl_rests
示例#6
0
def main():
    YOUR_API_KEY = 'AIzaSyDEOeghQshWQbRq24wFMv6erVBBBqbi_X0'
    google_places = GooglePlaces(YOUR_API_KEY)
    print "hi"
    print(hi)

    # You may prefer to use the text_search API, instead.
    query_result = google_places.nearby_search(
        location='Schenectady, New York',
        keyword='Food',
        radius=150,
        types=[types.TYPE_FOOD])
    # If types param contains only 1 item the request to Google Places API
    # will be send as type param to fullfil:
    # http://googlegeodevelopers.blogspot.com.au/2016/02/changes-and-quality-improvements-in_16.html

    if query_result.has_attributions:
        print(query_result.html_attributions)

    for place in query_result.places:
        # Returned places from a query are place summaries.
        print(place.name)
        #print(place.geo_location)
        #print(place.place_id)

        # The following method has to make a further API call.
        #place.get_details()
        # Referencing any of the attributes below, prior to making a call to
        # get_details() will raise a googleplaces.GooglePlacesAttributeError.
        #print(place.details) # A dict matching the JSON response from Google.
        #print(place.local_phone_number)
        #print(place.international_phone_number)
        #print(place.website)
        #print(place.url)

        # Getting place photos

        for photo in place.photos:
            # 'maxheight' or 'maxwidth' is required
            photo.get(maxheight=500, maxwidth=500)
            # MIME-type, e.g. 'image/jpeg'
            photo.mimetype
            # Image URL
            photo.url
            # Original filename (optional)
            photo.filename
            # Raw image data
            photo.data

    # Are there any additional pages of results?
    if query_result.has_next_page_token:
        query_result_next_page = google_places.nearby_search(
            pagetoken=query_result.next_page_token)
    '''
def google_places():
    api_key = 'add api key'
    geo = pd.read_csv('updated_master3.csv')
    google_places = GooglePlaces(api_key)

    for idx in geo.index:
        if ((type(geo.phone_num[idx]) != str) and (type(geo.YelpID[idx]) != str)):
            print geo.name[idx]
            lat = geo.lat[idx]
            lon = geo.lon[idx]
            result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx])
            #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), types=[types.TYPE_FOOD])
            #result = google_places.nearby_search(lat_lng={'lat': lat, 'lng':lon}, rankby='distance', name=geo.name[idx].decode('utf-8'), keyword=geo.address[idx], types=[types.TYPE_FOOD])
            if len(result.places) == 1:
                x = result.places[0]
                x.get_details()
                geo.set_value(idx, 'phone_num', x.local_phone_number)
                print "updated %s" % geo.name[idx]
            elif len(result.places) > 1:
                for place in result.places:
                    if (float(place.geo_location['lat']) == lat and float(place.geo_location['lng']) == lon):
                        x = place
                        x.get_details()
                        geo.set_value(idx, 'phone_num', x.local_phone_number)
                        print "updated %s" % geo.name[idx]
            else:
                print "for %s, length is %d" % (geo.name[idx], len(result.places))

    geo.phone_num.replace(regex=True, to_replace='\(|\)|-| ', value='', inplace=True)
    geo.to_csv('updated_master4.csv', index=False)
def location:
    YOUR_API_KEY = 'AIzaSyDYR6I8sEYHyY4-pZsEnzlmB8zb3SdlgEA'
    google_places = GooglePlaces(YOUR_API_KEY)


    #ip_add = subprocess.check_output(['hostname', '-I'])
    #ip_add = ip_add.strip()
    ip_add = "103.229.19.21"

    path = './GeoLiteCity.dat'
    gic = pygeoip.GeoIP(path)
    abc = gic.record_by_addr(ip_add)
    lat = abc['latitude']
    lng = abc['longitude']

    lt_lng = {'lat':lat,'lng':lng}
    i = 0
    #query_result = google_places.nearby_search(keyword='gas_station',lat_lng=lt_lng,radius=2000, types=[types.TYPE_FOOD])
    query_result = google_places.nearby_search(lat_lng=lt_lng, keyword='Petrol',radius=2000,rankby='distance')
    for place in query_result.places:
        print place.name
        place.get_details()
        d=place.details
        vic = d['vicinity']
        print vic
        print place.local_phone_number
        print ""
        if i == 0:
            i = 1
            dic = {'name':place.name,'vicinity':vic,'Phone':place.local_phone_number}
    return dic
示例#9
0
 def search(self, search_term, latlng, r, key, size, color):
     bbox = get_bbox(latlng, r)
     google_places = GooglePlaces(key)
     query_result = google_places.nearby_search(
         lat_lng={
             'lat': latlng[0],
             'lng': latlng[1]
         },
         radius=r * 1000,
         name=search_term,
         types=[types.TYPE_POINT_OF_INTEREST])
     category = search_term
     category2 = search_term
     res = [{
         "category": category,
         "category2": category2,
         "address": j.name,
         "lat": float(j.geo_location['lat']),
         "lng": float(j.geo_location['lng']),
         "legendgroup": category,
         "name": category,
         "address_short": j.name,
         "size": size,
         "color": color
     } for j in query_result.places]
     return res
def listOfHospitals(location):
    API_KEY = 'AIzaSyCpqFrt7N_WWxSAOUVz-hm77R_ozQCXwgs'
    google_places = GooglePlaces(API_KEY)
    try:
        query_result = google_places.nearby_search(
            # lat_lng ={'lat': 46.1667, 'lng': -1.15},
            lat_lng={
                'lat': location.latitude,
                'lng': location.longitude
            },
            radius=5000,
            # types =[types.TYPE_HOSPITAL] or
            # [types.TYPE_CAFE] or [type.TYPE_BAR]
            # or [type.TYPE_CASINO])
            types=[types.TYPE_HOSPITAL])
    except AttributeError as e:
        traceback.print_exc()
        return False

    if query_result.has_attributions:
        print(query_result.html_attributions)

        # Iterate over the search results
    i = 1
    listHospitals = []
    print("List of nearby hospitals: \n")
    for place in query_result.places:
        if i == 6:
            break
        # print(type(place))
        # place.get_details()
        listHospitals.append(str(i) + ". " + place.name)
        i = i + 1
    return listHospitals
示例#11
0
    def find_interesting_places(self, latitude, longitude, api_key,
                                geofence_radius):
        """
        Obtain the list of interesting places near a coordinate

        :param float latitude: Latitude of the place
        :param float longitude: Longitude of the place
        :param string api_key: API key of google places
        :param float geofence_radius: Radius within which we search for
        interesting places.
        :return: List of 1 or 0. 1, if we find the corresponding interesting
        place otherwise 0.
        """
        google_places = GooglePlaces(api_key)
        places_type_list = [
            self.RESTAURANT, self.SCHOOL, self.PLACE_OF_WORSHIP,
            self.ENTERTAINMENT, self.STORE, self.SPORTS
        ]
        return_list = []
        for places_list in places_type_list:
            place_list_length = 0
            for a_place in places_list:
                query_res = google_places.nearby_search(lat_lng={
                    'lat': latitude,
                    'lng': longitude
                },
                                                        keyword=a_place,
                                                        radius=geofence_radius)
                for place in query_res.places:
                    place_list_length += 1
            if place_list_length:
                return_list.append(1)
            else:
                return_list.append(0)
        return return_list
def get_nearby_achievements(location, radius=None):
    """ @param location a dictionary containing "lng" and "lat" entries
        @param radius radius of google places search
        @return list of Achievement objects as json
        Does a google Places nearby_search lookup,
        Retrieves all Datastore Places entries s.t. place_id is in search results
        Retrieves all Datastore Achievements s.t. achievement_id is in a Places achievements list
        return set of Achievements as a json objects
    """
    google_places = GooglePlaces(API_KEY)
    location = {"lng": location['lon'], "lat": location['lat']}
    query_results = google_places.nearby_search(lat_lng=location, rankby=ranking.DISTANCE, keyword='[Achievement]')

    result = {}
    achievements = []
    for place in query_results.places:
        query = Place.gql("WHERE id = '" + str(place.id) + "'")
        place_object = query.get()
        if place_object != None:
            for achievement_id in place_object.achievements:
                achievement_obj = Achievement.get_by_id(int(achievement_id))
                achievements.append(achievement_obj.to_dict())
            result["status_code"] = 200
        else:
            result["status_code"] = 404
    result["achievements"] = achievements
    return json.dumps(result)
示例#13
0
    def geolocation(self):
        self.maplist = []
        self.buttonHeightCounter = .05
        API_KEY = 'AIzaSyBPGAbevdKkeXaZT0ZsR0qbO30Bpqqm0Mc'

        google_places = GooglePlaces(API_KEY)

        self.query_result = google_places.nearby_search(
            location=self.entry.get(),
            radius=700,
            types=[types.TYPE_RESTAURANT])
        self.current_places = self.query_result

        if self.query_result.has_attributions:
            print(self.query_result.html_attributions)

        for place in self.query_result.places:
            place.get_details()

            markers = "&markers=size:big|label:S|color:red|" + str(
                place.details['geometry']['location']['lat']) + "," + str(
                    place.details['geometry']['location']['lng']) + "|"
            self.maplist.append(markers)
            print(place.name)
            self.button_list.append(
                Button(self,
                       text=place.name,
                       command=lambda pname=place.name: self.on_click(pname),
                       width=25))
            self.button_list[-1].place(relx=.70,
                                       rely=self.buttonHeightCounter,
                                       anchor="c")
            self.buttonHeightCounter += .035
            print(place.formatted_address + "\n")

        google_maps = GoogleMaps(
            api_key='AIzaSyDlJqxwlOWWAPwf54ivrpAZw4R1Yb5j6Yk')

        location = google_maps.search(
            location=self.entry.get())  # sends search to Google Maps.

        my_location = location.first()  # returns only first location.

        #MARKER = '&markers=color:blue' + '%' + str(7) + 'Clabel:S%' + str(7) + 'C' + str(my_location.lat) + ',' + str(my_location.lng)
        #MARKER = "&markers=size:big|label:S|color:blue|" + str(my_location.lat) + "," + str(my_location.lng) + "|" + \

        MARKER = self.maplist[1] + self.maplist[2] + self.maplist[3]

        self.zoomlevel = ZOOM

        maptype_index = 0
        self.radiovar.set(maptype_index)

        self.goompy = GooMPy(WIDTH, HEIGHT, my_location.lat, my_location.lng,
                             ZOOM, MAPTYPE, MARKER)

        self.restart()
        print(self.query_result)
        print(str(my_location.lat))
        print(str(my_location.lng))
示例#14
0
def makeWebhookResult(req):
    YOUR_API_KEY = 'AIzaSyAxA1j8Wea5db9mC00E4vCcZWSrVuwolGQ'
    google_places = GooglePlaces(YOUR_API_KEY)
    
    if req.get("result").get("action") != "shipping.cost":
        return {}
    result = req.get("result")
    parameters = result.get("parameters")
    zone = parameters.get("bank-name")
    address = parameters.get("address")
    #try:
        #query_result = google_places.text_search("Restaurant in New York", lat_lng ={'lat':40.730610, 'lng':-73.935242}, location='New York, USA', radius=2000, types=[types.TYPE_FOOD])
        #for place in query_result.places:
         #   para=place.url
    query_result = google_places.nearby_search(location=address, lat_lng ={'lat':51.509865, 'lng':-0.118092}, keyword=zone,radius=20000, types=[types.TYPE_BANK])
    for place in query_result.places:
        para=place.url
    #except:
     #   para = 'empty'
        
    speech = "The cost of shipping to " + zone + " is " + address + para
    

    print("Response:")
    print(speech)

    return {
        "speech": speech,
        "displayText": "shipping",
        #"data": {},
        # "contextOut": [],
        #"source": "apiai-onlinestore-shipping"
    }
示例#15
0
def hospital(token):
    tkn = pybase64.b64decode(token)
    r = tkn.decode('utf-8')
    str1 = r.split("(~)")
    username = str1[0]
    password = str1[1]
    cursor = mysql.get_db().cursor()
    cursor.execute('SELECT * FROM users WHERE Username = %s', [username])
    account = cursor.fetchone()
    API_KEY = 'your google api key'
    str1 = str(account[5]).split(",")
    l = ""
    for i in range(0, len(str1)):
        l = l + str1[i] + "+"
    send_url = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + l + '&key=' + API_KEY
    r = requests.get(send_url)
    j = json.loads(r.text)
    lat = j['results'][0]['geometry']['location']['lat']
    lon = j['results'][0]['geometry']['location']['lng']

    # Initialising the GooglePlaces constructor
    google_places = GooglePlaces(API_KEY)

    query_result = google_places.nearby_search(lat_lng={
        'lat': lat,
        'lng': lon
    },
                                               radius=5000,
                                               types=[types.TYPE_HOSPITAL])

    places = []
    # Iterate over the search results
    for place in query_result.places:
        places.append(place.name)
    return jsonify({'Hospitals': places})
示例#16
0
class NearbySearchGoogle(object):
    def __init__(self):
        self.google_places = GooglePlaces(GOOGLE_API_KEY)

    def find_nearby_places(self, search_keyword, address):
        nearby_places = []
        lat, lng = address_to_latlng(address)
        query_result = self.google_places.nearby_search(
            lat_lng={
                'lat': lat,
                'lng': lng,
            },
            keyword=search_keyword,
            radius=20000,
        )

        for place in query_result.places:
            place.get_details()
            data = {
                'name': place.name,
                'id': place.place_id,
                'phone': place.local_phone_number,
                'url': place.website,
                'rating': place.details.get('rating', None),
                'price_level': place.details.get('price_level', None),
            }
            nearby_places.append(data)

        return nearby_places
示例#17
0
 def get(self, request, id=None):
     API_KEY = 'AIzaSyA7BvQg4U2dF-z9seDJZLtR-1zEzLQAq0I'
     google_places = GooglePlaces(API_KEY)
     query_result = google_places.nearby_search(lat_lng={
         'lat': 49.83,
         'lng': 24.02
     },
                                                radius=10000,
                                                types=['Hotel'])
     places = query_result.places
     cordinates = []
     for place in places:
         if place.place_id == id:
             cordinates = [
                 place.geo_location["lat"], place.geo_location["lng"]
             ]
             return render(request, 'search/get_hotels.html', {
                 'places': places,
                 'cordinates': cordinates,
                 'selected': place
             })
     return render(request, 'search/get_hotels.html', {
         'places': places,
         'cordinates': cordinates,
         'selected': None
     })
示例#18
0
def imageSearch(coords):
    radius = 25
    counter = 0

   # gmaps = googlemaps.Client(key=API_KEY)
    gplaces = GooglePlaces(API_KEY)

    paths = []

    for coord in coords:
        place = format_loc(coord)
        nearby = gplaces.nearby_search(  # call to Google Places API
                    lat_lng=place,
                    radius=radius,  # radius is in m
                    )

        if len(nearby.places) != 0:
            for loc in nearby.places:
                if len(loc.photos) != 0:
                    photo = loc.photos[0]
                    photo.get(maxheight=5000, maxwidth=5000)
                    fname = 'static/images/result' + str(counter)+ '.jpg'
                    f = open(fname, 'wb')
                    f.write(photo.data)
                    f.close()
                    paths.append(fname)
                    counter += 1
                    break

    return paths
示例#19
0
def place():
    API_KEY = 'AIzaSyAgG3HIwJ6GMRgwDbrfaVSpp73cvPZ4Z50'
    google_places = GooglePlaces(API_KEY) 

    query_result = google_places.nearby_search( 
            # lat_lng ={'lat': 46.1667, 'lng': -1.15}, 
            lat_lng ={'lat': 20.354165, 'lng': 85.815463}, 
            radius = 5000, 
            # types =[types.TYPE_HOSPITAL] or 
            # [types.TYPE_CAFE] or [type.TYPE_BAR] 
            # or [type.TYPE_CASINO]) 
            types =[types.TYPE_HOSPITAL]) 

    if query_result.has_attributions: 
        print (query_result.html_attributions) 
        print('##############')

    # print(query_result.places)
    hospital_lists = []
    Latitude_list = []
    Longitude_list = []
    placess = json.dumps(str(query_result.places))
    for place in query_result.places: 
        Hospital = str(place.name)
        Latitude = str(place.geo_location['lat'])
        Longitude = str(place.geo_location['lng'])
        # plc = place_lists(Hospital,Latitude,Longitude)
        hospital_lists.append(Hospital)
        Latitude_list.append(Latitude)
        Longitude_list.append(Longitude)
        # return jsonify(nearHospital)
    # print(hospital_lists)
    # print(Latitude_list)
    # print(Longitude_list)
    return {"Hospitals":json.dumps(hospital_lists), "Latitude_list":json.dumps(Latitude_list),"Longitude_list":json.dumps(Longitude_list) }
示例#20
0
def main(configpath):
    # TODO today I'm just throwing this together for the CCL team... one big dumb function ... TODO refactor a lot

    with open(configpath, 'r') as f:
        config = yaml.load(f)
    logging.config.dictConfig(config['logging'])
    logger = logging.getLogger() # TODO should this be (__name__) or just (), I always forget

    # TODO refactor a fn to do "get-and-redact then assert all nodes of api_keys config are redacted"
    api_key_google_places = config['api_keys']['google_places']
    config['api_keys']['google_places'] = "<REDACTED>"
    api_key_boundaries = config['api_keys']['boundaries_chicago']
    config['api_keys']['boundaries_chicago'] = "<REDACTED>"

    for key, value in config['data_static'].items():
        config['data_static'][key] = os.path.expanduser(os.path.expandvars(value))

    logger.debug("config - evaluated, but API keys hidden: \n%s", json.dumps(config, indent=2))

    # google_places = GooglePlacesWithMemoization(api_key_google_places)
    google_places = GooglePlaces(api_key_google_places)

    start = time.time()
    result = google_places.nearby_search(location="12th Ward, Chicago, IL", radius=10)
    end = time.time()
    duration = end - start
    logger.info("Got %s and it took this much time: %s", result, duration)
示例#21
0
def GetHospitalLocation():
    # Initialising the GooglePlaces constructor
    google_places = GooglePlaces(API_KEY)
    list1 = GetUserGeoLocation()
    # call the function nearby search with
    # the parameters as longitude, latitude,
    # radius and type of place which needs to be searched of
    # type HOSPITAL
    query_result = google_places.nearby_search(lat_lng={
        'lat': list1[0],
        'lng': list1[1]
    },
                                               radius=2000,
                                               types=[types.TYPE_HOSPITAL])

    # If any attributions related
    # with search results print them
    if query_result.has_attributions:
        print(query_result.html_attributions)

    latlng = []
    for place in query_result.places:
        latlng.append([
            str(place.name),
            float(place.geo_location['lat']),
            float(place.geo_location['lng'])
        ])
    return latlng
示例#22
0
def geocode(df, api_key=YOUR_API_KEY):
    """Add Geocoded columns to df

    Keyword Args:
    df: Dataframe which must have an "address" column with a clean address
    api_key: Google Places API Key
    """
    google_places = GooglePlaces(api_key)
    matches = []

    # This counter is just for debugging purposes since I don't want to hit the API threshold
    i = 0
    for place in df.address:
        print(place)
        print(i)
        query_result = google_places.nearby_search(
            location=place,
            radius=100
        )
        print(query_result.places)
        matches.append(query_result.places)
        i = i + 1
        if i == 10:
            break

    for i in range(len(matches), len(df)):
        matches.append(None)
    df['matches'] = matches

    return df
示例#23
0
    def handle(self, *args, **options):
        # setup del archivo de salida

        suc_dir = os.path.join(settings.DATASETS_ROOT, 'sucursales')
        if not os.path.exists(suc_dir):
            os.makedirs(suc_dir)

        FILENAME = 'google_place_%s.csv' % datetime.now().strftime("%Y-%m-%d-%H%M%S")
        FILENAME = os.path.join(suc_dir, FILENAME)

        writer = unicodecsv.DictWriter(open(FILENAME, 'wb'), SUCURSAL_COLS)
        writer.writeheader()

        # crear manager de la api
        google_places = GooglePlaces(settings.GOOGLE_PLACES_API_KEY)

        IDS_CONOCIDOS = []

        for ciudad in City.objects.filter(population__gte=DESDE).order_by('-population'):
            location = unicode(ciudad).encode('utf8')
            query_result = google_places.nearby_search(name='supermercado',
                                                       language=lang.SPANISH,
                                                       location=location,
                                                       types=[types.TYPE_GROCERY_OR_SUPERMARKET],  # NOQA
                                                       radius=2000)

            for place in query_result.places:
                if place.id in IDS_CONOCIDOS:
                    print("%s ya cargado" % place.name)
                    continue
                IDS_CONOCIDOS.append(place.id)
                supermercado = self.limpiar(place, ciudad)
                print(supermercado)
                writer.writerow(supermercado)
def generateRoutes(chains,lat,lon, apiKey):
    #chains = ["mcdonalds", "burger king","cinemas"]

    pos =[]

    for i, chain in enumerate(chains):

        google_places = GooglePlaces(apiKey)

        query_result = google_places.nearby_search(
                lat_lng={'lat': lat, 'lng': lon},
                radius=5000,
                keyword= chain)

        places = query_result.places

        for place in places:
            place = str(place)
            latPos = place.find("lat=")
            lonPos = place.find("lng=")

            lat = np.float64(place[latPos+4:latPos+11])
            lon = np.float64(place[lonPos+4:lonPos+11])
            #gmap.scatter([lat], [lon], color=colors2[i], edge_width=10)
            pos.append([lat,lon])

    return pos
示例#25
0
def getPlacesData():
    #https://github.com/slimkrazy/python-google-places
    YOUR_API_KEY = secrets.apiKeys['api']

    google_places = GooglePlaces(YOUR_API_KEY)

    # You may prefer to use the text_search API, instead.
    query_result = google_places.nearby_search(
        lat_lng={
            'lat': '51.0523034',
            "lng": '-114.0767356'
        },
        keyword='dentist',
        radius=100)  #, types=[types.TYPE_FOOD])

    if query_result.has_attributions:
        print(query_result.html_attributions)

    for place in query_result.places:
        # Returned places from a query are place summaries.
        print('****************************')
        print(place.name)
        print(place.geo_location)
        print(place.place_id)

        # The following method has to make a further API call.
        place.get_details()
        # Referencing any of the attributes below, prior to making a call to
        # get_details() will raise a googleplaces.GooglePlacesAttributeError.
        print(place.details)  # A dict matching the JSON response from Google.
        print(place.local_phone_number)
        print(place.international_phone_number)
        print(place.website)
        print(place.url)
示例#26
0
文件: Place.py 项目: paxtonhead/B
class Place:
    def __init__(self, k):
        self.key = k
        self.coor = {}
        self.search = None
        self.search_result = None

    def getMidPoint2(self, location1, location2):

        geolocator = Nominatim()

        geo_location1 = geolocator.geocode(location1)
        geo_location2 = geolocator.geocode(location2)

        smallerLat = min(geo_location1.latitude, geo_location2.latitude)
        mlat = (abs(geo_location1.latitude - geo_location2.latitude) /
                2) + smallerLat

        smallerLon = min(geo_location1.longitude, geo_location2.longitude)
        mlon = (abs(geo_location1.longitude - geo_location2.longitude) /
                2) + smallerLon

        self.coor = {'lat': mlat, 'lng': mlon}
        return self.coor

    def searchGoogle(self, r=1000):
        self.search = GooglePlaces(self.key)
        self.search_result = self.search.nearby_search(
            lat_lng=self.coor, radius=r, types=[types.TYPE_RESTAURANT])

    def printSearchInfo(self):
        for place in self.search_result.places:
            # Returned places from a query are place summaries.
            print(place.name)
示例#27
0
def updatePlaces(request):
    API_KEY = 'AIzaSyA6JPiMICcP2AcON17VNiIMHDeL8o6fnz0'

    try:
        requestPlaceType = request.POST['type']
        currentLat = float(request.POST['lat'])
        currentLng = float(request.POST['lng'])

        names = []
        lat = []
        lng = []
        address = []
        google_places = GooglePlaces(API_KEY)

        if requestPlaceType == 'default':
            return

        query_result = google_places.nearby_search(
            lat_lng={'lat': currentLat, 'lng': currentLng}, keyword="Barbers",
            radius=3000, types=[getPlace(requestPlaceType)])

        for place in query_result.places:
            print(place.name)
            place.get_details()
            names.append(place.name)
            lat.append(float(place.geo_location['lat']))
            lng.append(float(place.geo_location['lng']))
            address.append(place.formatted_address)

        return JsonResponse({'names': names, 'lat': lat, 'lng': lng, 'address': address}, status=200, safe=False)
    except Exception as e:
        print(e)
        return JsonResponse({"message": str(e)}, status=400)
示例#28
0
def gasStationInfo(lat, long, start_radius=25, radius_limit=None):
    google_places = GooglePlaces(os.environ['api_google_key'])
    res_list = []
    if radius_limit is None:
        limit = 100
    else:
        limit = radius_limit
    while start_radius <= limit:
        start_radius += 25
        query_result = google_places.nearby_search(
            location='Dnipro, Ukraine', lat_lng={'lat': lat, 'lng': long},
            radius=start_radius, types=[types.TYPE_GAS_STATION], language=lang.UKRANIAN)

        for place in query_result.places:
            place.get_details()
            res_list.append({
                'name': place.name,
                'adress': place.formatted_address,
                'geo_location': place.geo_location,
                'place_id': place.place_id,
                'website': place.website,
                'local_phone_number': place.local_phone_number,
                'international_phone_number': place.international_phone_number,
                'rating': place.rating
            })
            if radius_limit is None:
                return res_list
    return res_list
示例#29
0
def doctor_find(my_input):
    YOUR_API_KEY = 'AIzaSyDuy19nMwHBvLvgkg9upGZkex9jqriWkQ0'

    google_places = GooglePlaces(YOUR_API_KEY)

    query_result = google_places.nearby_search(location=my_input,
                                               keyword='doctor',
                                               radius=2000,
                                               types=[types.TYPE_DOCTOR])

    strr = " "
    flag = 0
    for place in query_result.places:
        place.get_details()
        strr = strr + "\n Name :" + (str(
            place.name).upper()) + "\n Address:" + str(
                place.formatted_address) + "\n Phone Number :" + (
                    str(place.international_phone_number).upper()
                ) + "\n Map Url :" + str(place.url) + "\n Web Link :" + str(
                    place.website) + "\n Ratings:" + str(
                        place.rating) + "\n" + ("_" * 50) + "\n"

        flag = flag + 1
        if flag == 5:
            break

    return strr
示例#30
0
def nearMe():
    API_KEY = 'AIzaSyCJM2_o-SpAVPLrLXKL2-6JNeQRTbdUuno'
    google_places = GooglePlaces(API_KEY)
    
    my_location = geocoder.ip('me')
    lat, lng = my_location.latlng

    query_result = google_places.nearby_search( 
        lat_lng ={'lat': lat, 'lng': lng}, 
        radius = 5000, 
        types =[types.TYPE_HOSPITAL])

    name = []
    coord = []
    coords_1 = (lat, lng)
    # Iterate over the search results 
    for place in query_result.places:
        coords_2 = ( float(place.geo_location['lat']), float(place.geo_location['lng']))
        coord.append([ float(place.geo_location['lat']), float(place.geo_location['lng']) ])
        x = round(geopy.distance.distance(coords_1, coords_2).km, 5)
        if x >= 1:
            dis = " Distance: " + str(x) + "km"
        else:
            dis = " Distance: " + str(round(x*1000, 2)) + "m"
        
        name.append(place.name + dis)

    df_text = name
    
    locations = coord
    map2 = folium.Map(location=my_location.latlng, tiles='CartoDB dark_matter', zoom_start=12)

    marker_cluster = MarkerCluster().add_to(map2)

    title_html = '''
                 <h3 align="center" style="font-size:20px"><b>Hospitals And Medical Stores Near You</b></h3>
                 '''
    map2.get_root().html.add_child(folium.Element(title_html))

    folium.Marker(
                location=my_location.latlng, 
                popup='Your Location',
                icon=folium.Icon(color='darkblue', icon_color='white', icon='male', angle=0, prefix='fa')
            ).add_to(map2)

    folium.Circle(
        location=[lat, lng],
        radius=5000,
        color='#3186cc',
        fill=True,
        fill_color='#3186cc'
    ).add_to(map2)

    for point in range(0, len(locations)):
            folium.Marker(locations[point], 
                          popup = folium.Popup(df_text[point]),
	                     ).add_to(marker_cluster)
    map2.save('templates/nearMe.html')
    
    return render_template('nearMe2.html')
示例#31
0
def findNearestHospital():
    try:
        hosp_places=list()
        if request.method == 'GET':
            API_KEY = request.args.get("api_key")
            
            longitude = request.args.get('longitude')
            print(longitude)
            latitude = request.args.get('latitude')
            radius = request.args.get('radius')
            google_places = GooglePlaces(API_KEY)
            query_result = google_places.nearby_search( 
                # lat_lng ={'lat': 46.1667, 'lng': -1.15}, 
                lat_lng ={'lat': latitude, 'lng': longitude}, 
                radius = radius, 
                # types =[types.TYPE_HOSPITAL] or 
                # [types.TYPE_CAFE] or [type.TYPE_BAR] 
                # or [type.TYPE_CASINO]) 
                types =[types.TYPE_HOSPITAL])
            for place in query_result.places:
                hosp_places.append(jsonify(hospital_name=place.name,
                                           Latitude=place.geo_location['lat'],
                                           Longitude=place.place.geo_location['lng']))
                           
    except Exception as e:
        return jsonify(error="Error with API key, Please check if API key is valid and You must enable Billing on the Google Cloud Project at https://console.cloud.google.com/project/_/billing/enable Learn more at https://developers.google.com/maps/gmp-get-started")

    return jsonify(hosp_places)
示例#32
0
    def get(self, request, *args, **kwargs):
        if request.method == 'GET':
            google_places = GooglePlaces(API_KEY)
            query_result = google_places.nearby_search(
                location='banglore',
                keyword='RESTAURANT',
                radius=20000,
                types=[types.TYPE_RESTAURANT],
                lat_lng={
                    'lat': '12.975686',
                    'lng': '77.578426'
                })

            if query_result.has_attributions:
                print(query_result.html_attributions)

            place_names = []
            r_ratings = []
            r_types = []
            r_vicinity = []

            for place in query_result.places:  # fetch relevent data
                place_names.append(place.name)
                r_ratings.append(place.rating)
                r_types.append(place.types)
                r_vicinity.append(place.vicinity)

            final_result = []  # all the mapped data

            for i in zip(place_names, r_ratings, r_types,
                         r_vicinity):  #map all information with relevent data
                final_result.append(i)

        return Response(final_result)
def gps_to_place_list(Lat, Lng):
    # Set up google places API
    google_places = GooglePlaces(API_KEY)
    # Search for place
    query_result = google_places.nearby_search(lat_lng={
        'lat': Lat,
        'lng': Lng
    },
                                               radius=100,
                                               type='point_of_interest')

    # If found result within radius
    data = []
    if query_result.places:

        for place in query_result.places:

            name = place.name
            format_lat = float(place.geo_location['lat'])
            format_lng = float(place.geo_location['lng'])
            # place.get_details()
            # address = place.formatted_address
            data.append({'name': name, 'lat': format_lat, 'lng': format_lng})

    return data
示例#34
0
class GOPprovider(basicProvider, goLocation):
    """ This class is used to:
        1. Make the connection to the Google Places API
        2. Get user's Photos
        3. Get OPENi album Photos
        4. Post Photos to OPENi album
    """

    def __init__(self):
        """ Initiate the connector """
        YOUR_API_KEY = "AIzaSyDoZ455JKv5GS2DgmK1jQc7R8Oj5JVjEnI"
        self.connector = GooglePlaces(YOUR_API_KEY)

    def get_nearby_places(self, data):
        """ EXTRA!!! Find nearby places """
        raw_datas = self.connector.nearby_search(
            location="London, England", keyword="Fish and Chips", radius=20000, types=[types.TYPE_FOOD]
        )
        fields = [
            "id",
            "type",
            "service",
            "url",
            "user.id",
            "user.username",
            "website",
            "name",
            "details.formatted_address",
            "details.formatted_address.number",
            "geo_location.lat",
            "geo_location.lng",
            "created_time",
            "types",
        ]
        alternatives = ["", "place", "openi", "", "", "", "", "", "", "", "", "", "", ""]
        response = {"meta": {"total_count": "blah", "next": "bla"}, "data": []}
        for raw_data in raw_datas.places:
            data = self.get_fields(raw_data, fields, alternatives)
            response["data"].append(self.format_place_response(data))
        return response

    def add_a_place(self, data):
        """ EXTRA!!! Add a new place """
        # Returns a detailed instance of googleplaces.Place
        raw_data = self.connector.add_place(
            name=data["name"],
            lat_lng={"lat": data["lat"], "lng": data["lng"]},
            accuracy=data["accuracy"],
            types=data["type"],
            language=data["lang"],
        )
        response = {"added_place_reference": raw_data.reference, "added_place_id": raw_data.id}
        return response

    def delete_a_place(self, data):
        """ DELETE API_PATH/[PLACE_ID] """
        # Returns a detailed instance of googleplaces.Place
        raw_data = self.connector.delete_place(data["reference"])
        return {"status": "OK"}
示例#35
0
def _find_places(request, place_type):
    g_places = GooglePlaces(API_KEY)
    request_fields = ['lat_lng', 'radius']
    api_req = {k: request[k] for k in request_fields}

    query_result = g_places.nearby_search(types=place_type, **api_req)
    places = map(_filter_place_data, query_result.places)
    return {'places': places}
示例#36
0
def getNearbyWaypoints(latitude, longitude):
    google_places = GooglePlaces(config.Config.googlePlacesAPIKey)
    query_result = google_places.nearby_search(
        lat_lng={'lat': latitude, 'lng': longitude},  
        rankby='distance',
        types = [types.TYPE_FOOD, types.TYPE_BAR, 
                 types.TYPE_RESTAURANT])
    return query_result
示例#37
0
    def get_context_data(self, **kwargs):
        context = super(PlacesView, self).get_context_data(**kwargs)
        google_places = GooglePlaces(settings.GOOGLE_API_KEY)
        query_result = google_places.nearby_search(
        location='Philadelphia, PA', keyword='Pool',
        radius=20000)

        context['places'] = query_result
        return context
示例#38
0
def content(request, type, location):
    key = 'AIzaSyDVa_QhQkZb8eGLwMmDrhvpjB745f5dakM'

    '''try: 
        places=Place.objects.filter(city=location)
        context = {
            'location': location,
            'places': places,
            'type': type,
        }
    except:        '''
    google_places = GooglePlaces(key)

    query_result = google_places.nearby_search(location=location, radius=20000,
                                               types=type)

    for place in query_result.places:
        # The following method has to make a further API call.
        place.get_details()
        # Referencing any of the attributes below, prior to making a call to
        # get_details() will raise a googleplaces.GooglePlacesAttributeError.

        place_model = Place(place_name=place.name,
                            geo_location=place.geo_location,
                            place_id=place.place_id,
                            address="",
                            details=place.details,
                            city=location,
                            local_phone_number=str(place.local_phone_number),
                            international_phone_number=str(place.international_phone_number),
                            website=place.website,
                            icon=place.icon
                            )
        place_model.save()

        current_place = Place.objects.get(id=place_model.id)

        for photo in place.photos:
            photo.get(maxheight=500, maxwidth=500)

            photo_model = Photo(photo_name=photo.filename,
                                place=current_place,
                                url=photo.url,
                                mimetype=photo.mimetype
                                )
            photo_model.save()

    context = {
        'location': location,
        'places': query_result.places,
        'type': type,
    }

    return render(request, 'places/content.html', context)
示例#39
0
def get_google_places(building_name):
    """Use the Google Places API from the python-google-places library to extract a place object, given a building name."""

    google_places = GooglePlaces(GOOGLE_PLACES_API_KEY)

    query_result = google_places.nearby_search(
        location='San Francisco, California', keyword=building_name)

    places = query_result.places

    return places
示例#40
0
def get_restaurant(place_name, include_city):
	restaurant_result = {}
	google_places = GooglePlaces('AIzaSyAJyCCeJNiaky6gVuZ2G1-0-hK0MaJJr3o')
	query_result = google_places.nearby_search(location=place_name, radius=1000, types=[types.TYPE_FOOD])
	restaurant = random.choice(query_result.places)
	restaurant.get_details()
	restaurant_result['name'] = restaurant.name
	if include_city:
		restaurant_result['addr'] = restaurant.formatted_address.replace(", United States", "")
	else:
		restaurant_result['addr'] = restaurant.formatted_address[:restaurant.formatted_address.index(",")]
	return restaurant_result
示例#41
0
class GoogleFood(object):
    """A class that makes JSON and dictionaries of various Google places food results."""
    #
    # TODO: Apparently getters are not pythonic. Figure out how to do this with a @propery.
    #
    def get_result(self):
        #print self.query_results
        return self.query_results
    def __init__(self):
        self.api_key = constants.GOOGLE_PLACES_API_KEY_TAYLORHANDREWS
        self.api_client = GooglePlaces(self.api_key)
        self.query_result = None
    def to_string(self):
        s += "API Key: %s\n" % self.api_key
        return s
    def create_list(self, location_in, keywords_in, radius_mi_in):
        i = 0
        query_list = {}
        query_result = self.api_client.nearby_search(location=location_in,
                                                     keyword=keywords_in,
                                                     radius=radius_mi_in*
                                                     constants.METERS_PER_MILE,
                                                     types=[types.TYPE_FOOD])
        #
        # TODO: This print can probably go at some point. If it turns out to be needed it should
        #       be stored in another object or logged.
        #
        if query_result.has_attributions:
          print query_result.html_attributions

        for place in query_result.places:
            place_dict = {}
            place_dict['name'] = place.name
            place_dict['lat_lng'] = place.geo_location
            place_dict['place_id'] = place.place_id
            #
            # The following method has to make a further API call.
            #
            # Referencing any of the attributes below, prior to making a call to
            # get_details() will raise a googleplaces.GooglePlacesAttributeError.
            #
            place.get_details()
            place_dict['formatted_address'] = place.formatted_address
            place_dict['local_phone_number'] = place.local_phone_number
            place_dict['international_phone_number'] = place.international_phone_number
            place_dict['website'] = place.website
            place_dict['url'] = place.url
            query_list[i] = place_dict
            i = i + 1
        self.query_results = query_list
        return True
示例#42
0
class GOPprovider(basicProvider, goActivity, goLocation, goMedia, goProductsServices, goProfiles):
    ''' This class is used to:
        1. Make the connection to the Google Places API
        2. Get user's Photos
        3. Get OPENi album Photos
        4. Post Photos to OPENi album
    '''
    def __init__(self):
        ''' Initiate the connector '''
        YOUR_API_KEY = 'AIzaSyDoZ455JKv5GS2DgmK1jQc7R8Oj5JVjEnI'
        self.connector = GooglePlaces(YOUR_API_KEY)

    def get_nearby_places(self, data):
        """ EXTRA!!! Find nearby places """
        raw_datas = self.connector.nearby_search(location='London, England', keyword='Fish and Chips', radius=20000, types=[types.TYPE_FOOD])
        fields = ['id', 'type', 'service', 'url', 'user.id', 'user.username', 'website', 'name', 'details.formatted_address', 'details.formatted_address.number', 'geo_location.lat', 'geo_location.lng', 'created_time', 'types']
        alternatives = ['', 'place', 'openi', '', '', '', '', '', '', '', '', '', '', '']
        response = {
                    'meta':
                        {
                            'total_count': 'blah',
                            'next': 'bla'
                        },
                    'data': []
                    }
        for raw_data in raw_datas.places:
            data = self.get_fields(raw_data, fields, alternatives)
            response['data'].append(self.format_place_response(data))
        return response

    def add_a_place(self, data):
        """ EXTRA!!! Add a new place """
        # Returns a detailed instance of googleplaces.Place
        raw_data = self.connector.add_place(name=data['name'],
            lat_lng={'lat': data['lat'], 'lng': data['lng']},
            accuracy=data['accuracy'],
            types=data['type'],
            language=data['lang'])
        response = {
                        'added_place_reference': raw_data.reference,
                        'added_place_id': raw_data.id
                    }
        return response
    
    def delete_a_place(self, data):
        """ DELETE API_PATH/[PLACE_ID] """
        # Returns a detailed instance of googleplaces.Place
        raw_data = self.connector.delete_place(data['reference'])
        return { 'status': 'OK' }
示例#43
0
def nearby_search(keywords, location):
    cache_key = str((keywords, location))
    results = cache.get(cache_key)
    if results is not None:
        return results
    print "Google Places API Hit"
    google_places = GooglePlaces(settings.GOOGLE_PLACES_API_KEY)
    api_results = google_places.nearby_search(
        radius=25000,
        location=location,
        keyword=keywords
    )
    results = map(lambda p: p.name, api_results.places)
    cache.set(cache_key, results)
    return results
    def run(self):
        while True:
            Site_Address = self.queue.get()
            #print Site_Address
            API_KEY = 'xxx'
            google_places = GooglePlaces(API_KEY)

            quey_result = google_places.nearby_search(location='Singapore',keyword=Site_Address,radius = 30000)
            for place in quey_result.places:
                place.get_details()
                out_put = Site_Address+';'+place.name+';'+str(place.geo_location['lat'])+';'+str(place.geo_location['lng'])+';'+place.formatted_address
                threadlock.acquire()
                print out_put
                threadlock.release()
            self.queue.task_done()
示例#45
0
文件: index.py 项目: Ads7/zone_finder
def hello():
	## for parameters passed like name and location /?name=abc&location=abc
	if request.args.get('name'):
		name = request.args.get('name')
	if request.args.get('location'):
		location =  request.args.get('location')
	google_places = GooglePlaces(YOUR_API_KEY)	
	query_result = google_places.nearby_search(name='Kwality Restaurant',
		location='karol bagh , delhi',keyword='chicken',
		radius=20000, types=[types.TYPE_FOOD])
	data = []
	for place in query_result.places:
		print(place.name)
		print(place.geo_location)
		print(place.place_id)
	return str(place.name)+str(place.geo_location)+str(place.place_id)
示例#46
0
def main():
   if not has_internet():
       print "You must be connected to the Internet."
       return 1

   if len(sys.argv) != 4:
      print "usage: ./google_places.py <location> <keyword> <radius in mi>"
      print "   ex: ./google_places.py \"Somerville, MA\" \"Indian\" 1"
      return 1
   google_places = GooglePlaces(YOUR_API_KEY)

   #
   # Convert location to lat/long
   #
   #lat_long = google_places.geocode_location("Brighton, MA", sensor=False)
   #for k in lat_long:
   #   print(k)

   #exit()

   # You may prefer to use the text_search API, instead.
   query_result = google_places.nearby_search(
           location=sys.argv[1], keyword=sys.argv[2],
           radius=(float(sys.argv[3])*1609.34), types=[types.TYPE_FOOD])

   if query_result.has_attributions:
       print query_result.html_attributions


   for place in query_result.places:
       # Returned places from a query are place summaries.
       print place.name
       #print place.geo_location
       print "Lat/Lng [%s, %s]" % (place.geo_location['lat'], place.geo_location['lng'])
       #print place.place_id

       # The following method has to make a further API call.
       place.get_details()
       # Referencing any of the attributes below, prior to making a call to
       # get_details() will raise a googleplaces.GooglePlacesAttributeError.
       #print place.details # A dict matching the JSON response from Google.
       print place.formatted_address
       print place.local_phone_number
       print place.international_phone_number
       print "Website: %s" % place.website
       print "URL:     %s" % place.url
       print ""
def getDirections(current_location, transportation_mode, shop_preference):
  """Return a list of directions that the user should take to
    get from their current location to the ClickTime office while
    stopping for donuts and coffee along the way."""

  # Init API Clients
  google_places = GooglePlaces(GOOGLE_API_KEY)
  google_maps = Client(key=GOOGLE_API_KEY)

  # Get the coordinates of the nearest donut shop to the ClickTime office.
  query_result = google_places.nearby_search(
      lat_lng=CLICKTIME_LOCATION,
      name='donut',
      types='food',
      rankby=shop_preference)

  donut_shop_name = query_result.places[0].name
  donut_shop_location = query_result.places[0].geo_location

  # Get directions from current location to donut shop.
  # Had issues with waypoints so I broke the route into
  # two different pieces.
  directions_api_result = google_maps.directions(
      current_location,
      donut_shop_location, 
      mode=transportation_mode)

  directions = []
  for step in directions_api_result[0]['legs'][0]['steps']:
    directions.append(step['html_instructions'])
  directions.append('<font color="green">Arrived at ' 
      + donut_shop_name + '!</font>')

  # Get directions from the donut shop to the ClickTime office.
  directions_api_result = google_maps.directions(
      donut_shop_location,
      CLICKTIME_LOCATION, mode=transportation_mode)

  for step in directions_api_result[0]['legs'][0]['steps']:
    directions.append(step['html_instructions'])  
  directions.append('<font color="green">Arrived at ClickTime!</font>')
  
  return directions
示例#48
0
    def post(self):
        city = self.request.get('city')
        category = self.request.get('category')

        ##Image Search##


        google_places = GooglePlaces(GOOGLE_API_KEY)
        query_results = google_places.nearby_search(location=city, keyword=category, radius=20000)

        if query_results.has_attributions:
            print query_results.html_attributions

        locname = []
        loclat = []
        loclong = []
        marker = ""

        for place in query_results.places:
            try:
                n = str(place.name)
                location = place.geo_location
                lat = location["lat"]
                lng = location["lng"]
                locname.append(n)
                loclat.append(lat)
                loclong.append(lng)
            except:
                print " "

        for i in range(len(locname)):
            marker += locname[i]
            marker += ": "
            marker += str(loclat[i])
            marker += ", "
            marker += str(loclong[i])
            marker += "; "

        self.session["mark"] = marker
        self.session["city"] = city

        self.redirect('/')
示例#49
0
def _get_google_map_search_results(term, zip_code, count=5, radius=20000):
    google_places = GooglePlaces(settings.GOOGLE_MAPS_API_KEY)
    place_results = google_places.nearby_search(
        location=zip_code,
        keyword=term,
        radius=20000,
        types=[]
        )
    map(lambda x: x.get_details(), place_results.places[:count])
    json_results = [{
        "name": tpr.name,
        "address": tpr.formatted_address,
        "website": tpr.website,
        "phone_number": tpr.local_phone_number,
        "url": tpr.url,
        "id": tpr.id,
        "place_id": tpr.place_id
        }
        for tpr in place_results.places[:count]]
    return json_results
示例#50
0
def get_places(lng, lat, query):
    google_places = GooglePlaces(API_KEY)


    query_result = google_places.nearby_search(
        lat_lng={
            'lat': lat,
            'lng': lng
        },
        keyword=query,
        radius=10000,
        rankby='distance'
    )

    return [{
        'name': place.name,
        'lng': float(place.geo_location['lng']),
        'lat': float(place.geo_location['lat']),
        'id': place.place_id
    } for place in query_result.places]
示例#51
0
def init(lat, lng, speed):
	place_ref = GooglePlaces(API_KEY)

	geog_zone = {
		'keyword' : ['school', 'hospital'],
		'loc_type' : [[types.TYPE_SCHOOL], [types.TYPE_HOSPITAL]],
		'speed_lim' : ['25', 'nil'],
		'other_lim' : ['nil', 'no_horn']
	}

	os.system('clear')


	place_latlong = {
		'lat': lat,
		'lng': lng
	}


	for num in range(len(geog_zone['keyword'])):
		#nearby search based on current location
		query_result = place_ref.nearby_search(
	        lat_lng = place_latlong, keyword= geog_zone['keyword'][num],
	        radius=500, types = geog_zone['loc_type'][num])

		if query_result.has_attributions:
		    print query_result.html_attributions	

		
		if len(query_result.places) > 0:
			if geog_zone['keyword'][num] == 'school':
				if speed > geog_zone['speed_lim'][num]:
					os.system('play sounds/warning.wav')
					os.system('play sounds/school.wav')
					os.system('play sounds/speed.wav')
			elif geog_zone['keyword'][num] == 'hospital':
				os.system('play sounds/warning.wav')
				os.system('play sounds/hos.wav')
				os.system('play sounds/horn.wav')

		"""
示例#52
0
def results():
    if request.method == 'POST':
        city = request.form['city']
        type = request.form['type']

        GOOGLE_API_KEY = "AIzaSyBCsZBILrxQqRNd2Aji_abzot_15Rm9dIY"

        google_instance = GooglePlaces(GOOGLE_API_KEY)

        query_result = google_instance.nearby_search(
                location=city, keyword=type,
                radius=20000, types=[types.TYPE_FOOD])

        if query_result.has_attributions:
            print (query_result.html_attributions)

        query_result.places[0].get_details()
        address = query_result.places[0].formatted_address
    
        return render_template("results.html", name = query_result.places[0].name, name2 = address)
    else:
        return "Try again from the homepage"
gpdf = pd.read_csv(input_file)
tpdf = pd.read_csv(type_file)
gpdfi = gpdf.copy(deep=True)
curtp = 0
placenum = 0

print "Google Place Search Running for all types....."
print " *** It may take 12 hours or more to run *** "
for ti in range(tpdf.shape[0]):
    if ti >= curtp and tpdf['search'][ti]==1:
        tp = tpdf['type'][ti]
        print "Runing: ", tp, "......"
        for cdi in range(cddf.shape[0]):
            try:
                time.sleep(0.03)
                query_result = google_places.nearby_search(lat_lng={'lat': cddf['y'][cdi], 'lng': cddf['x'][cdi]}, radius=220., types=[tp])
            except:
                print '  Error Happend for google_places.nearby_search()...'
                print "  Try again 10s later:", cddf['y'][cdi],':', cddf['x'][cdi]
                time.sleep(10.1)
                query_result = google_places.nearby_search(lat_lng={'lat': cddf['y'][cdi], 'lng': cddf['x'][cdi]}, radius=220., types=[tp])

            if len(query_result.places)>0:
                if (cdi%400)==0:
                    print "\t%-6s: %.2f Completed (overall:%.2f)..." % (tp, 1.0*cdi/4300.0, 1.0*ti/(cddf.shape[0]+2))
                #print "%s:%d:%d; " % (tp, cdi, len(query_result.places)),
                exg = query_result.places
                for place in query_result.places:
                    place.get_details()
                    if sum(place.place_id == gpdf['g_id'])<1:
                        gpdf = gpdf.append(gpdfi, ignore_index=True)
示例#54
0
     pointLng[point_num] = point['lng']
     data_point = {
         'MapMyRunId': route_id,
         'Lat': pointLat[point_num],
         'Lng': pointLng[point_num],
     }
     cur.execute(add_point, data_point)
 # find key points to save in tracks database
 m = 0
 for point_num in xrange(0,points_count,points_count/4+1):
     point = route_points[point_num]
     keyLat[m] = point['lat']
     keyLng[m] = point['lng']
     loc = {'lat': keyLat[m], 'lng': keyLng[m]}
     try:
         query_result = gop.nearby_search(
             lat_lng=loc, radius=5000, types=[types.TYPE_PARK,types.TYPE_ZOO], rankby='distance')
         natureLat = query_result.places[0].geo_location['lat']
         natureLng = query_result.places[0].geo_location['lng']
         natureDist[m] = haversine((keyLat[m],keyLng[m]),(natureLat,natureLng))
     except:
         print "error caught in google places api request, default value used"
         time.sleep(1)
         natureDist[m] = 5000.0
     m = m+1
 centerLat = np.mean(keyLat)
 centerLng = np.mean(keyLng)
 route_nature = 1.0 - np.mean(natureDist)
 if route.name is not None:
     route_name = route.name.encode('ascii', 'ignore')
 else:
     route_name = 'None'
import json  #for reading oauth info and save the results
import io 
from googleplaces import GooglePlaces, types, lang
from pprint import pprint

with io.open('google_places_key.json') as cred:
    creds = json.load(cred)
    google_places = GooglePlaces(**creds)

    result = []
    #Put your lantitude and longtitude pairs in the list and run the search in turns
    lat_lng_list = [{'lat': 2.356357, 'lng': -71.0623345},  #Park Street Station
                    {'lat': 42.356357, 'lng': -71.0623345},  #China Town Station
                    {'lat': 42.3555885, 'lng': -71.0646816}] #Downtown Crossing Station
    for pair in lat_lng_list:
        query_result = google_places.nearby_search(
            lat_lng = pair, rankby = 'distance', types = [types.TYPE_FOOD])

        for place in query_result.places:
            place.get_details()
            tmp = vars(place)
            results.append(tmp)
                
    with open('my_boston_restaurants_google_places.json', 'wb') as f:
        results_json = json.dumps(results, indent=4, skipkeys=True, sort_keys=True)
            f.write(results_json)
示例#56
0
def buscar_activitats(destination, actTypes):
    google_places = GooglePlaces(GOOGLEAPI_KEY)
    types_list = actTypes.split(",")

    gact = Graph()
    gact.bind('activitat', activitat)

    #Realitzem la peticio d'activitats al servei extern
    query_result = google_places.nearby_search(
            location= locations[str(destination)], keyword='',
            radius=2000, types=types_list)

    #Afegim els resultats en un graf de resposta
    for place in query_result.places:
        act_obj = activitat.id + str(place.place_id)
        # Returned places from a query are place summaries.
        gact.add((act_obj, activitat.name, Literal(place.name)))
        # The following method has to make a further API call.
        place.get_details()
        # Referencing any of the attributes below, prior to making a call to
        # get_details() will raise a googleplaces.GooglePlacesAttributeError.
        gact.add((act_obj, activitat.subj, activitat.obj))
        gact.add((act_obj, activitat.rating, Literal(place.rating)))
        gact.add((act_obj, activitat.address, Literal(place.formatted_address)))
        gact.add((act_obj, activitat.phone, Literal(place.local_phone_number)))
        gact.add((act_obj, activitat.website, Literal(place.website)))

    #Obtenim el pagetoken de la peticio
    pt = query_result.next_page_token

    #Si no es null obtenim els seguents 20 resultats(maxim) de la query anterior
    if (pt is not None):
        #Es fa una parada de 2 segons perque no es pot realitzar una segona query de manera immediata
        time.sleep(2)

        query_result2 = google_places.nearby_search(
                location='Barcelona, Spain', keyword='',
                radius=2000, types=types_list, pagetoken = pt)

        pt = query_result2.next_page_token

        for place in query_result2.places:
            act_obj = activitat.id + str(place.place_id)
            gact.add((act_obj, activitat.name, Literal(place.name)))
            place.get_details()
            gact.add((act_obj, activitat.rating, Literal(place.rating)))
            gact.add((act_obj, activitat.address, Literal(place.formatted_address)))
            gact.add((act_obj, activitat.phone, Literal(place.local_phone_number)))
            gact.add((act_obj, activitat.website, Literal(place.website)))

    #Igual que abans, obtenim mes activitats si existeix una tercera pagina amb resultats
    if (pt is not None):
        #Es fa una parada de 2 segons perque no es pot realitzar una segona query de manera immediata
        time.sleep(2)

        query_result3 = google_places.nearby_search(
                location='Barcelona, Spain', keyword='',
                radius=2000, types=types_list, pagetoken = pt)

        for place in query_result3.places:
            act_obj = activitat.id + str(place.place_id)
            gact.add((act_obj, activitat.name, Literal(place.name)))
            place.get_details()
            gact.add((act_obj, activitat.rating, Literal(place.rating)))
            gact.add((act_obj, activitat.address, Literal(place.formatted_address)))
            gact.add((act_obj, activitat.phone, Literal(place.local_phone_number)))
            gact.add((act_obj, activitat.website, Literal(place.website)))

    return gact
示例#57
0
#YOUR_API_KEY = 'AIzaSyBoggHOZ8jWDzO69jVGNkoX4F-m8FYKa0Q'
YOUR_API_KEY = 'AIzaSyDo-xr-5RnuSbHDPJGRpR-YCG_cVQ9CXiI'
#print YOUR_API_KEY
#print type(YOUR_API_KEY)
#assert(0)
google_places = GooglePlaces(YOUR_API_KEY)

def readAirportList( myFilename = './Data/Airports.csv' ):

    myAirportData = pd.read_csv( myFilename, sep = ',' )
    return myAirportData.columns.values.tolist(), myAirportData.values.tolist()

    
# You may prefer to use the text_search API, instead.
myQueryResult = google_places.nearby_search(
                keyword = 'Airport',
                location = 'London, England',
                radius = 50000 )
                #types = [types.TYPE_AIRPORT])

#print myQueryResult.__dict__

for myPlace in myQueryResult._places :

    print myPlace.__dict__
    print myPlace._query_instance
    myLat = myPlace._geo_location['lat']
    myLng = myPlace._geo_location['lng']
    
    print myLat, myLng
    #myLatMin = myLat + 0.1
    #myLngMin = myLng - 0.1
示例#58
0
from googleplaces import GooglePlaces, types, lang
from pprint import pprint

YOUR_API_KEY = 'AIzaSyCLTwL7ffZJ1KPd8TqYVuCYN9qD7VwuZII'

google_places = GooglePlaces(YOUR_API_KEY)

# You may prefer to use the text_search API, instead.
query_result = google_places.nearby_search(location='London, England', keyword='Fish and Chips',
    radius=20000, types=[types.TYPE_FOOD])

if query_result.has_attributions:
    # print "hello\n\n\n"
    print query_result.html_attributions



ALL = []


for place in query_result.places:
    # Returned places from a query are place summaries.
    name = place.name
    geo = place.geo_location
    # id = place.place_id
    # print pprint(place.__dict__)
    # print "\n\n\n\nlkasjdklj\n\n\n"
    # The following method has to make a further API call.
    # pprint(place.get_details())
    # Referencing any of the attributes below, prior to making a call to
    place.get_details()# will raise a googleplaces.GooglePlacesAttributeError.
import urllib, json


YOUR_API_KEY = 'AIzaSyCiUUV45HvFFOYvbVITo65qABlHDNKQT7A'
params={}
request={}
google_places = GooglePlaces(YOUR_API_KEY)



f=open('latdatathree.txt')
while True:
    nameread=f.readline().split('\n')
    if not nameread:break     
    for names in nameread:
        print name.strip().split(",")
        params["name"] = names
        query_result = google_places.nearby_search(location="San Francisco", **params)
        for place in query_result.places[:1]:
                placeid = place.place_id
#
#
#        MyUrl = ('https://maps.googleapis.com/maps/api/place/details/json?placeid=%s&key=%s') % (placeid,YOUR_API_KEY)
#          #grabbing the JSON result
#        response = urllib.urlopen(MyUrl)
#        jsonRaw = response.read()
#        jsonData = json.loads(jsonRaw)
#        
#        hourno=str(jsonData).find('Tuesday:')+6
#        myfile.write('\n'+str(jsonData)[hourno:hourno+9]+','+str(jsonData)[hourno+13:hourno+26])