Beispiel #1
0
def get_station_by_location(lat, lng):
    gm_client = googlemaps.Client(os.environ['api_google_key'])
    gmap = places.places_nearby(client=gm_client,
                                location={
                                    'lat': lat,
                                    'lng': lng
                                },
                                radius=140)
    geo = GoogleV3(os.environ['api_google_key'])
    res = gmap['results']
    res_list = []
    for i in range(len(res)):
        if 'gas_station' in res[i]['types']:
            name = res[i]['name']
            station_lat = res[i]['geometry']['location']['lat']
            station_lng = res[i]['geometry']['location']['lng']
            adress = str(
                geo.geocode(f"{station_lat}, {station_lng}")).split(',')
            street = adress[0] + ',' + adress[1]
            res_list.append({
                'name': name,
                'adress': street,
                'lat': station_lat,
                'lng': station_lng
            })
    return res_list
Beispiel #2
0
 def get_name(self):
     gm_client = googlemaps.Client(os.environ['api_google_key'])
     gmap = places.places_nearby(client=gm_client, location={'lat': self.lat, 'lng': self.long}, radius=25)
     res = gmap['results']
     for i in range(len(res)):
         if 'gas_station' in res[i]['types']:
             name = res[i]['name']
             return name
 def search_for_parks(self, keyword, location):
     return places.places_nearby(
         client=self._client,
         keyword=keyword,
         location=location,
         type="park",
         radius=20,
     )
Beispiel #4
0
def find_station_ids() -> list:
    """Finds a list of all the place ids of the stations around town"""

    print("Collecting gas station data.")
    stations = []

    print('Collecting result data')
    time.sleep(2)
    search_result = places.places_nearby(gmaps,
                                         '41.977576,-91.666851',
                                         160935,
                                         keyword='gas station')
    iter = 1
    while True:
        stations += search_result['results']
        if 'next_page_token' not in search_result:
            break
        else:
            iter += 1
            print("Collecting page {}".format(iter), end='\r')
            token = search_result['next_page_token']
            time.sleep(1)
            while True:
                try:
                    search_result = places.places_nearby(
                        gmaps,
                        '41.977576,-91.666851',
                        160935,
                        keyword='gas station',
                        page_token=token)
                    break
                except googlemaps.exceptions.ApiError as e:
                    continue

    result = []
    print("Filtering bad data")
    for s in tqdm(stations):
        info = places.place(gmaps, s['place_id'])['result']

        if info is not None and info['name'] != '':
            result.append(s['place_id'])
        else:
            print("Found a dud station entry, skipping")

    return result
def gethospitals():
	places=places_nearby(client,getlocation(),keyword="Hospitals near me",open_now=True,rank_by='distance',type="hospital")
	hospitals=[]
	for hospital in places['results']:
		name=hospital['name']
		if not 'Vetenary' in name:
			if not "Critical" in name:
				if not "Neuro" in name:

					hospitals.append(name)
	#return hospitals
	hospitaldistances={}
	for name in hospitals:
		hospitaldistances[name]=distance_matrix(client2,[tuple(getlocation())],name)['rows'][0]['elements'][0]['distance']['text']
	return hospitaldistances
Beispiel #6
0
def get_nearby():
    args = request.args
    # if len(args) not in range(1,4):
    #    return {"error": "not enough arguments"}
    address = args.get('address')
    rad = args.get('radius')
    print("args:", args)
    geo = geocoding.geocode(gmaps, address)
    lat = geo[0]['geometry']['location']['lat']
    lng = geo[0]['geometry']['location']['lng']
    nearby = places.places_nearby(gmaps,
                                  location=(lat, lng),
                                  radius=1,
                                  type="restaurant")
    return nearby
def find_nearby_landmarks(listing: Listing) -> List[Landmark]:
    landmarks = []
    if search_places:
        listing_coordinates = get_listing_coordinates(listing)
        if listing_coordinates is not None:
            for landmark_type in LandmarkType:
                response = places_nearby(gmaps_client,
                                         location=listing_coordinates,
                                         radius=3000,
                                         type=landmark_type.name)
                landmarks += [
                    create_landmark(place, landmark_type, listing,
                                    listing_coordinates)
                    for place in filter_places_response(
                        response, landmark_type)
                ]
    return landmarks
Beispiel #8
0
 def find_closest_foodbank(self, address):
     geolocator = Nominatim(user_agent="foodBankLocator")
     location = geolocator.geocode(address)
     coordinates = (location.latitude, location.longitude)
     client = googlemaps.Client(key=config.googleKey)
     nearby_banks = places.places_nearby(client=client,
                                         location=coordinates,
                                         radius=24140,
                                         keyword='food bank')
     food_bank_list = []
     for foodbank in nearby_banks['results']:
         location_coord = foodbank['geometry']['location']['lat'], foodbank[
             'geometry']['location']['lng']
         address = geolocator.reverse(
             str(location_coord[0]) + ", " + str(location_coord[1]))
         food_bank_list.append(foodbank['name'])
     print(food_bank_list)
     return food_bank_list
def get_nearby_place(client, current_location, chat_id):
    result = {'message': 'Места в радиусе 500 метров', 'places': []}
    names = get_places_names(chat_id)
    if names:
        for name in names:
            try:
                selection = places_nearby(client, current_location, radius=500, name=name[1])
                if selection['results']:
                    result['places'] += check_place_id(selection, name[0])
                else:
                    continue
            except TransportError:
                result['message'] = 'Googlemaps временно не работает\nПовторите попытку позже'
        if not result['places']:
            result['message'] = 'Поблизости нет сохранённых мест.'
    else:
        result['message'] = 'Ваш список мест пуст!'
    return result
Beispiel #10
0
def find_places(user_location, user_radius, place_type):
    if type(user_location) == Location:
        location = (user_location['latitude'], user_location['longitude'])
    else:
        location = user_location

    result = places.places_nearby(client,
                                  location=location,
                                  radius=user_radius,
                                  type=place_type,
                                  language='ru')['results']
    for place in result:
        if 'rating' not in place:
            place['rating'] = 0
        if 'opening_hours' not in place:
            place['is_open'] = 'No information'
        elif place['opening_hours']['open_now']:
            place['is_open'] = 'Is open now'
        else:
            place['is_open'] = 'Is closed now'

    return sorted(result, key=lambda item: item['rating'], reverse=True)
def get_place_info(client, current_location, keyword):  # Для установления точного адреса места, которое хотят сохранить
    try:
        selection = places_nearby(client, current_location, radius=200, name=keyword)
    except TransportError:
        return {'message': 'Googlemaps временно не работает\nПовторите попытку позже', 'place_info': {}}
    if selection['results']:
        places = selection['results']
        print(places)
        place = places[0]  # Чаще всего первый пример из выборки совпадает с местом пользователя
        location = place['geometry']['location']
        return {'message': 'OK!',
                'place_info': {'place_id': place['place_id'],
                               'name': place['name'],
                               'address': place['vicinity'],
                               'lat': location['lat'],
                               'lng': location['lng'],
                               'photo_id': None,
                               'visitor_id': None
                               }
                }
    else:
        return {'message': 'Информация о месте не найдена!', 'place_info': {}}
]

with open('restau.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(cols)

with open('restau.csv', 'a') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    j = 1
    for loc in locations:
        print("location number: {}".format(j))
        j += 1
        i = 1
        response = places_nearby(gmaps,
                                 location=loc,
                                 radius=500,
                                 max_price=3,
                                 type="restaurant")
        for obj in response['results']:
            photo = obj["photos"][0]["photo_reference"] if (
                "photos" in obj) else np.float("nan")
            rating = obj["rating"] if ("rating" in obj) else np.float("nan")
            user_ratings_total = obj["user_ratings_total"] if (
                "user_ratings_total" in obj) else np.float("nan")
            writer.writerow([
                obj['geometry']['location']['lat'],
                obj['geometry']['location']['lng'], obj["name"], photo, rating,
                user_ratings_total, obj["vicinity"], obj["place_id"],
                obj["types"]
            ])
        print("page number {}".format(i))
Beispiel #13
0
def get_nearby_locations(coordinates, **kwargs):
    assert isinstance(coordinates, tuple)
    results = Places.places_nearby(CLIENT, coordinates, RADIUS, **kwargs)
    return results['results']
import googlemaps
from googlemaps import places

from tools.json_to_yaml import write_yaml

gmaps = googlemaps.Client(key='AIzaSyCWOSz0D-dfNnfv7FJh6pP3dghHM9NmyuQ')
" https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.8670522,151.1957362&radius=1500&type=restaurant&keyword=cruise&key=AIzaSyCWOSz0D-dfNnfv7FJh6pP3dghHM9NmyuQ"

# Geocoding an address
geocode_result = places.places_nearby(gmaps,
                                      location='-33.8670522,151.1957362',
                                      radius=1500,
                                      type='restaurant',
                                      keyword='cruise')
write_yaml(geocode_result, 'nearbysearch_result.yaml')