當前位置: 首頁>>代碼示例>>Python>>正文


Python googleplaces.GooglePlaces類代碼示例

本文整理匯總了Python中googleplaces.GooglePlaces的典型用法代碼示例。如果您正苦於以下問題:Python GooglePlaces類的具體用法?Python GooglePlaces怎麽用?Python GooglePlaces使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了GooglePlaces類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: getOneWaypoint

def getOneWaypoint(waypoint, reference = None):
    pool = ConnectionPool('vendalize')
    cfmapWaypoint = pycassa.ColumnFamilyMap(data.Waypoint, pool, 'waypoints')    #map waypoints to Waypoint Class
    si = sunburnt.SolrInterface("http://54.225.230.44:8983/solr/vendalize.waypoints/")
    wp = waypoint.lower()
    wp = re.sub('[^\w\s]+','', wp)
    response = si.query(waypoint_c=wp).execute(constructor=data.Waypoint)
    if len(response) > 0:   #found waypoint in database so use the googleid as reference for data
        result = response[0]
        key = result.key
        reference = result.googlereference
    
    google_places = GooglePlaces(config.Config.googlePlacesAPIKey)
    place = {}
    if reference:
        place = google_places.get_place(reference)
        if not place:
            return getOneWaypoint(waypoint, None)   #reference lookup failed, try text search
    else:
        query_result = google_places.text_search(
            query = waypoint)
        if len(query_result.places) > 0:
            place = (query_result.places)[0]
            place.get_details()
        
    return place
開發者ID:cgil,項目名稱:Local-search-app,代碼行數:26,代碼來源:index.py

示例2: handle

    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)
開發者ID:hhaamm,項目名稱:preciosa,代碼行數:34,代碼來源:google_places.py

示例3: get_context_data

 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
開發者ID:Yablargo,項目名稱:splash-philadelphia,代碼行數:35,代碼來源:views.py

示例4: main

def main():
    woosmap_converted_asset = []
    with codecs.open(SEARCH_DATA_PATH, 'rb', encoding='utf8') as search_data_file:
        search_data = json.loads(search_data_file.read())
        google_places = GooglePlaces(GOOGLE_API_KEY)
        for place_id in search_data['places_ids']:
            try:
                place = google_places.get_place(place_id)
                converted_asset = google_places_to_woosmap(place.details)
                if bool(converted_asset):
                    print("... {place_name} ...converted to Wosmap OK".format(place_name=place.name.encode('utf-8')))
                    woosmap_converted_asset.append(converted_asset)

            except (GooglePlacesError, GooglePlacesAttributeError) as error_detail:
                print('Google Returned an Error : {0} for Place ID : {1}'.format(error_detail, place_id))
                pass

            except Exception as exception:
                print('Exception Returned {0} for Place ID : {1}'.format(exception, place_id))
                time.sleep(1)
                pass

        export_to_woosmap_json(woosmap_converted_asset)
        print('{0} google places extracted for {1} places_ids found '.format(len(woosmap_converted_asset),
                                                                             len(search_data['places_ids'])))
開發者ID:woosmap,項目名稱:samples,代碼行數:25,代碼來源:googleplaces_to_woosmap.py

示例5: get_nearby_achievements

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)
開發者ID:JordanGraves,項目名稱:AchievementUnlocked-AppEngine,代碼行數:27,代碼來源:Queries.py

示例6: google_places

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)
開發者ID:jhboyle,項目名稱:DC_RestaurantViolationForecasting,代碼行數:30,代碼來源:00_google_places.py

示例7: GOPprovider

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"}
開發者ID:mpetyx,項目名稱:open-I,代碼行數:59,代碼來源:connector.py

示例8: getNearbyWaypoints

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
開發者ID:cgil,項目名稱:Local-search-app,代碼行數:8,代碼來源:index.py

示例9: _find_places

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}
開發者ID:fawind,項目名稱:food-tindr,代碼行數:8,代碼來源:place_finders.py

示例10: get_context_data

    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
開發者ID:woodlinAyanna,項目名稱:SplashPhilly2014,代碼行數:9,代碼來源:views.py

示例11: content

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)
開發者ID:Prashant-Yadav,項目名稱:localizer,代碼行數:54,代碼來源:views.py

示例12: get_google_places

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
開發者ID:tdiede,項目名稱:hackscrapers_SF,代碼行數:11,代碼來源:google_places.py

示例13: get_restaurant

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
開發者ID:mef79,項目名稱:food-recommender-twitterbot,代碼行數:12,代碼來源:bot.py

示例14: GOPprovider

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' }
開發者ID:OPENi-ict,項目名稱:api-framework,代碼行數:49,代碼來源:connector.py

示例15: nearby_search

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
開發者ID:EntilZha,項目名稱:docker-workshop,代碼行數:15,代碼來源:google_places.py


注:本文中的googleplaces.GooglePlaces類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。