def get_coord_by_add(address): loc = {"latitude": 0, "longitude": 0} cl = Client(y_apikey) coord = cl.coordinates(address) loc['latitude'] = round(float(coord[1]), 6) loc['longitude'] = round(float(coord[0]), 6) return loc
def create(self, validated_data): shop = Shop(**validated_data) shop.owner = self.context['request'].user client = Client(settings.YANDEX_GEOCODER_KEY) shop.latitude, shop.longitude = client.coordinates(shop.addres) shop.save() return shop
def save(self, *args, **kwargs): if self.address: client = Client(YANDEX_GEOCODER_API_KEY) longitude, latitude = client.coordinates(self.address) self.point, _ = Point.objects.get_or_create(latitude=latitude, longitude=longitude) super().save(*args, **kwargs)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None): client = Client("%s" % settings.API_KEY_YANDEX_GEOCODER) coordinates = client.coordinates(self.address) self.latitude = coordinates[0] self.longitude = coordinates[1] return super(Shops, self).save()
def test_raises_for_unknown_response(mock_api): mock_api({}, 500, geocode="Москва Льва Толстого 16") client = Client("well-known-key") with pytest.raises(UnexpectedResponse) as exc_info: client.coordinates("Москва Льва Толстого 16") assert "status_code=500, body=b'{}'" in exc_info.value.args
def test_raises_for_unknown_response(mock_api): mock_api({}, 500, geocode="37.587093,55.733969") client = Client("well-known-key") with pytest.raises(UnexpectedResponse) as exc_info: client.address(Decimal("37.587093"), Decimal("55.733969")) assert "status_code=500, body=b'{}'" in exc_info.value.args
def test_returns_found_address(mock_api): mock_api("address_found", 200, geocode="37.587093,55.733969") client = Client("well-known-key") assert ( client.address(Decimal("37.587093"), Decimal("55.733969")) == "Россия, Москва, улица Льва Толстого, 16" )
def test_request_fails(requests_mocker): requests_mocker.get( 'https://geocode-maps.yandex.ru/1.x/?geocode=b&format=json', status_code=400) with pytest.raises(YandexGeocoderHttpException, message='Non-200 response from yandex geocoder'): Client.request('b')
def create(self, validated_data): owner = self.context['request'].user shop = Shop(**validated_data) shop.Owner = owner client = Client(yandexToken) shop.lat, shop.lon = client.coordinates(shop.addres) shop.save() return shop
def test_returns_found_coordinates(mock_api): mock_api("coords_found", 200, geocode="Москва Льва Толстого 16") client = Client("well-known-key") assert client.coordinates("Москва Льва Толстого 16") == ( Decimal("37.587093"), Decimal("55.733969"), )
def get_coordinates(self): """ Get coordinates from Yandex API by string representation of the address. Api key is stored in the docker env variables. """ api_key = settings.YANDEX_API_KEY client = Client(api_key) coordinates = client.coordinates(self.address) return coordinates[0], coordinates[1]
def get_coords(address: str) -> list: # Yandex API connection client = Client("086a1aa1-6152-47a3-af40-b645a86409ae") # YandexAPI online request coordinates = client.coordinates(address) latitude, longitude = float(coordinates[1]), float(coordinates[0]) return [latitude, longitude]
def handle_waiting(bot, update, job_queue): if address := update.message.text: try: client = Client(os.getenv("API_KEY")) lon, lat = client.coordinates(address) current_pos = float(lon), float(lat) except exceptions.NothingFound: bot.send_message(text='Не могу распознать этот адрес', chat_id=update.message.chat_id) return "HANDLE_WAITING"
def get_coords(self): """Возвращает координаты заведения (долгота, широта)""" client = Client(YANDEX_GEOCODER_KEY) try: coord = client.coordinates(self.address) except Exception: raise APIException( 'Невозможно определить координаты заведения. Проверьте правильность адреса.' ) return coord
def Geokoder(document): client = Client("9577d1e2-cf09-4dea-94cc-5c80d4de81e6") coordinates = client.coordinates("Москва Льва Толстого 16") assert coordinates == (Decimal("37.587093"), Decimal("55.733969")) address = client.address(Decimal("37.587093"), Decimal("55.733969")) assert address == "Россия, Москва, улица Льва Толстого, 16" d = client.coordinates(document) return d
def test_raises_for_invalid_api_key(mock_api): mock_api( {"statusCode": 403, "error": "Forbidden", "message": "Invalid key"}, 403, geocode="37.587093,55.733969", api_key="unkown-api-key", ) client = Client("unkown-api-key") with pytest.raises(InvalidKey): client.address(Decimal("37.587093"), Decimal("55.733969"))
def get_coordinates(sender, instance, **kwargs): if instance.latitude is None: try: YANDEX_KEY = os.getenv('YANDEX_KEY') client = Client(YANDEX_KEY) coordinates = client.coordinates(instance.address) instance.latitude = coordinates[1] instance.longitude = coordinates[0] instance.save() except NothingFound: logger.warning('the address provided by user is wrong')
def get_address_by_coordinates(coordinates: tuple) -> Optional[AnyStr]: """ Return address string value by coordinates :param coordinates: Coordinates (latitude, longitude) :return: string value """ client = Client('4d16304f-12ba-4134-ac9b-f0da5028a1f4') latitude = coordinates[0] longitude = coordinates[1] location = client.address(longitude, latitude) return location
def test_raises_for_invalid_api_key(mock_api): mock_api( { "statusCode": 403, "error": "Forbidden", "message": "Invalid key" }, 403, geocode="Москва Льва Толстого 16", api_key="unkown-api-key", ) client = Client("unkown-api-key") with pytest.raises(InvalidKey): client.coordinates("Москва Льва Толстого 16")
class YandexGeocoder: def __init__(self): self.regions = load_data(STATION_LIST_DIR_RU) self.client = Client("c0d403ab-e5be-4049-908c-8122a58acf23") def get_location(self, station, region=''): try: long, lat = map(float, self.client.coordinates(f"{region} {station}")) return [lat, long] except Exception: print(Exception) def update_regions(self): for region, station_data in self.regions.items(): for station, station_id in station_data.items(): locations = self.get_location(station, region) if locations: new_data = dict(id=station_id, location=locations) self.regions[region][station] = new_data print( f'{region} - {station}: координаты обновлены!' ) else: self.regions[region][station] = dict(id=station_id, location=None) print( f'{region} - {station}: ---------------------------------------------ненаход' ) def save_data(self): filename = '../stations/ru_meteo_yandex_locatons.json' with open(filename, 'w') as f: json.dump(self.regions, f, indent=2, ensure_ascii=False)
def test_request_ok(requests_mocker): requests_mocker.get( 'https://geocode-maps.yandex.ru/1.x/?geocode=b&format=json', json={'response': { 'ok': True }}) assert Client.request('b') == {'ok': True}
def get_text_by_coordinates(coordinates): try: result = Client.request(f'{coordinates[1]}, {coordinates[0]}') return result['GeoObjectCollection']['featureMember'][0]['GeoObject'][ 'name'] except Exception as e: print(e) return None
def try_get_coordinates(address: str) -> tuple: try: coordinates = Client.coordinates(address) y, x = coordinates return x, y except exceptions.YandexGeocoderAddressNotFound: return None except exceptions.YandexGeocoderHttpException: print('http exception') return None
def location(message): if message.location is not None: # по координатам получаем адрес и присылаем человеку, ему останется проверить адрес и внести правки. client = Client(YANDEX_API_KEY) address = client.address(Decimal(message.location.longitude), Decimal(message.location.latitude)) markup = types.ReplyKeyboardMarkup(row_width=1) yes_button = types.KeyboardButton(text='Да') no_button = types.KeyboardButton(text='Нет') markup.row(yes_button, no_button) bot.send_message( message.chat.id, address) # 'Ваш адрес: г. Волгодонск, ул. Моская, д. 92' bot.send_message(message.chat.id, 'Верно ли определён Ваш адрес?', reply_markup=markup) with open(settings.MEDIA_ROOT + f'{message.chat.id}.txt', 'a') as f: f.writelines([address + '\n']) bot.register_next_step_handler(message, check_address)
def process(entity): entity_type = enums.Entity.Type(entity.type) try: geo = Client.coordinates(entity.name) except Exception: return None return { "name": entity.name, "type": entity_type.name, "geo": list(map(float, geo)) }
def get_user_coordinates(): """ Получаем координаты пользователя от геокодера Yandex. Меняем местами координаты, полученные от Yandex (долгота, широта), на (широта, долгота), т.к. GeoPy принимает координаты в формате (широта, долгота). """ user_location = input("Где вы находитесь?: ") user_coordinates = Client.coordinates(user_location) user_coordinates_swapped = user_coordinates[::-1] return user_coordinates_swapped
def main(): location = input("Где вы находитесь? ") mycoords = coords_swap(list(Client.coordinates(location))) bardata = [] with open('data/data-2897-2019-04-09.json', encoding='cp1251') as jsonfile: bars_data = json.load(jsonfile) for bar in bars_data: title = bar['Name'] latitude = float(bar['Latitude_WGS84']) longitude = float(bar['Longitude_WGS84']) bar_distance = distance.distance(mycoords, (latitude,longitude)).km bardata.append({'title':title, 'latitude':latitude, 'longitude':longitude, 'distance':bar_distance}) sorted_bars = sorted(bardata, key=get_bar_distance) map = folium.Map(location=[float(mycoords[0]), float(mycoords[1])]) tooltip = 'Бар здесь!' for item in sorted_bars[:5]: title = item['title'] folium.Marker([item['latitude'], item['longitude']], popup='<b>{}</b>'.format(title), \ tooltip=tooltip).add_to(map) map.save('output/index.html') app = Flask(__name__) app.add_url_rule('/', 'hello', hello_world) app.run('0.0.0.0')
def handle_order(headers, params, recipient_id, message): try: current_pos = Client.coordinates(message) except YandexGeocoderAddressNotFound as error: logging.error(error) send_message(recipient_id, message='Не смогли определить адрес, попробуйте еще.') current_pos = None if current_pos is None: return 'HANDLE_ORDER' closest_pizzeria = utils.get_closest_pizzeria(db, current_pos) text, distance = utils.calculate_distance_for_message(closest_pizzeria) send_message(recipient_id, message='Данные приняты, спасибо') send_message(recipient_id, message=text) create_delivery_buttons(recipient_id, distance=distance) user = json.loads(db.get(f'facebook_{recipient_id}')) user['closest_pizzeria'] = closest_pizzeria user['user_address'] = message db.set(f'facebook_{recipient_id}', json.dumps(user)) return 'WAITING_CHOOSING'
def test_raises_if_coordinates_not_found(mock_api): mock_api("coords_not_found", 200, geocode="абырвалг") client = Client("well-known-key") with pytest.raises(NothingFound, match='Nothing found for "абырвалг"'): client.coordinates("абырвалг")
for bar in bars: folium.Marker( location=[bar["latitude"], bar["longitude"]], popup=f"{bar['title']}", icon=folium.Icon(icon="glass"), ).add_to(bar_map) bar_map.save("index.html") return None @app.route("/") def show_map(): return send_from_directory("", "index.html") if __name__ == "__main__": with open("data-2897-2019-07-10.json", encoding="cp1251") as fh: bars_data = json.load(fh) customer_location = input("Enter your location: ") customer_coord = Client.coordinates(customer_location)[::-1] bars_collection = collect_bars(bars_data, customer_coord) closest_bars = sorted(bars_collection, key=get_bar_distance)[:5] draw_map(closest_bars, customer_coord) app.run()