示例#1
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
示例#2
0
def FoodScore(location, t=None):  #pass place id instead?
    from googleplaces import GooglePlaces
    import math
    gplaces = GooglePlaces("AIzaSyB1qIvuAxzchC8QWG2Y0nn_9LnYsshrApw")
    rank = 0
    if t != None:
        if t in typerank:
            rank = typerank.index(t) + 1
            mult = (1 + (rank / 8))
        else:
            return 0

    query = gplaces.text_search(location=location, radius=0)
    raw = query.raw_response['results'][0]
    rscore = raw['rating'] * (
        1 + 1 / (1 + math.pow(math.e, -raw['user_ratings_total'])))
    if t == None:
        place = query.places[0]
        place.get_details()
        for t in place.details['types']:
            if t in typerank:
                if typerank.index(t) > rank:
                    rank = typerank.index(t)
        if rank == 0:
            return 0
        mult = (1 + (rank / 8))

    return 1.25 * mult * rscore
示例#3
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) }
示例#4
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))
示例#5
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
示例#6
0
def create_map_pois(gui_data):
    places_api = GooglePlaces(gui_data['api_key'])

    pois = {}
    for cat in gui_data['categories']:
        pois[cat+"Poi"] = fetch_for_category(places_api, cat, gui_data['lat_lng'], gui_data['radius'])
    return pois
示例#7
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 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
示例#9
0
def search_places(query_search, places):
    from googleplaces import GooglePlaces
    YOUR_API_KEY = 'AIzaSyA1Ox-CnVRe2684Lxqf_oXDjV0imAY1wx4'
    google_places = GooglePlaces(YOUR_API_KEY)

    # You may prefer to use the text_search API, instead.
    query_result = google_places.text_search(
        query = query_search, radius = 200000)
    
    for i in range(10):
        places[i]["name"] = ""
        places[i]["rating"] = ""
        places[i]["address"] = ""
        places[i]["wesbite"] = ""
        places[i]["number"] = ""
    
    
    entry = 0    
    for place in query_result.places:
        # Returned places from a query are place summaries.
        place.get_details()
        places[entry]["name"] = str(place.name)
        rate = str(place.rating)
        places[entry]["rating"] = rate + u"\u2b50"
        places[entry]["address"] = str(place.formatted_address)
        places[entry]["wesbite"] = str(place.website)
        places[entry]["number"] = str(place.local_phone_number)
        entry += 1
        if (entry > 9): break
        print places
示例#10
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)
示例#11
0
    def handle(self, *args, **options):
        longitude = options.get("longitude")
        latitude = options.get("latitude")
        number = options.get("number")
        if number:
            self.number = number
        else:
            self.number = 60  # default limit from google places api doc

        YOUR_API_KEY = settings.GOOGLE_API_KEY

        self.google_places = GooglePlaces(YOUR_API_KEY)

        # You may prefer to use the text_search API, instead.
        query_result = self.google_places.nearby_search(
            lat_lng={
                "lat": latitude,
                "lng": longitude
            },
            radius=400,
            language=lang.FRENCH,
            types=[
                types.TYPE_FOOD, types.TYPE_RESTAURANT,
                types.TYPE_MEAL_TAKEAWAY
            ],
        )
        self.count = 0
        self.get_page_places(query_result)

        self.stdout.write(self.style.SUCCESS(f"{self.count} PLACES LOADED"))
示例#12
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
示例#13
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)
示例#14
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)
示例#15
0
 def __init__(self, API_KEY):
     self.gmaps = googlemaps.Client(key=API_KEY,
                                    queries_per_second=50,
                                    retry_over_query_limit=False)
     self.gmaps_get_place_ID = googlemaps.Client(
         key=API_KEY, queries_per_second=50, retry_over_query_limit=False)
     self.google_places = GooglePlaces(API_KEY)
示例#16
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
示例#17
0
文件: views.py 项目: jadedh/CS411
def api(request):
    if request.method == 'POST':
        try:
            q = request.POST['query']
            query_text = QueryText.objects.get(query=q)
            return JsonResponse(
                {'results': list(query_text.querydata_set.all().values())})
        except QueryText.DoesNotExist:
            google_places = GooglePlaces(
                'AIzaSyCYwqirZB73zzrsHF3P7y0XZRX0df2c2TM')
            query_result = google_places.text_search(query=q,
                                                     radius=500,
                                                     lat_lng={
                                                         'lat': -33.8665433,
                                                         'lng': 151.1956316
                                                     })
            qt = QueryText(query=q)
            qt.save()
            qt_loaded = QueryText.objects.get(query=q)
            arr = []
            for item in query_result.places:
                lat = item.geo_location['lat']
                long = item.geo_location['lng']
                obj = QueryData(query_id=qt_loaded.id, lat=lat, long=long)
                arr.append({'lat': float(lat), 'long': float(long)})
                obj.save()

            return JsonResponse({'results': arr})

    assert isinstance(request, HttpRequest)
    return render(request, 'app/api.html', {
        'title': 'Home Page',
        'year': datetime.now().year,
    })
示例#18
0
def main(request):
    YOUR_API_KEY = 'AIzaSyAutyhulLRnlnWms5bEQVys3e0kQPO5Fo8'
    google_places = GooglePlaces(YOUR_API_KEY)

    direction = "Diosito"

    return render(request, 'test.html', context={'direction': direction},)
示例#19
0
 def __init__(self,
              key=ApiKeys['Google Places'],
              max_per_business_name=None):
     self.places_api = GooglePlaces(ApiKeys['Google Places'])
     self.max_per_business_name = max_per_business_name
     if not self.max_per_business_name:
         self.max_per_business_name = 3
示例#20
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')
示例#21
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"
    }
示例#22
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
示例#23
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
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
示例#25
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)
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
示例#27
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})
示例#28
0
def search_for_web_results(file_location_of_list_of_practices, YOUR_API_KEY, directory_where_you_want_to_save_the_new_file):
    practices = pd.read_excel(file_location_of_list_of_practices)
    #print(practices)
    for index, row in practices.iterrows(): 
        practice_name = getattr(row, "Common Account Name")
        practice_address = getattr(row, "Physical Street")
        practice_city = getattr(row, "Physical City")
        practice_state = getattr(row, "Physical State/Province")
        practice_zip = str(getattr(row, "Physical Zip/Postal Code"))
        google_places = GooglePlaces(YOUR_API_KEY)
        query_result = google_places.text_search(query = practice_name + ' ' + practice_address + ' ' + practice_city + ' ' + practice_state + ' ' + practice_zip)
        print(len(query_result.places))
        for place in query_result.places:
            try:
                place.get_details()
                practices.iloc[index, 11] = place.name
                practices.iloc[index, 12] = place.formatted_address
                practices.iloc[index, 13] = place.international_phone_number
                practices.iloc[index, 14] = place.place_id
                practices.iloc[index, 15] = place.url
                practices.iloc[index, 16] = place.website
                practices.iloc[index, 17] = place.permanently_closed
            except:
                continue
    os.chdir(directory_where_you_want_to_save_the_new_file)
    practices.to_excel(new_file_name, 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
示例#30
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
     })