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 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 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 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 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 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_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")
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 adressToCoordinate(city, street, dom): client = Client("1eaf6c9f-0eab-4fe5-b3cb-51c3b819f7b8") coordinates = client.coordinates(city + " " + street + " " + dom) return [coordinates[0], coordinates[1]]
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("абырвалг")
def __init__(self): self.regions = load_data(STATION_LIST_DIR_RU) self.client = Client("c0d403ab-e5be-4049-908c-8122a58acf23")
from django.shortcuts import HttpResponse from django.views import View from django.views.generic.base import TemplateView from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator from yandex_geocoder import Client from django.conf import settings client = Client(settings.YANDEX_API_KEY) class GeoFormView(TemplateView): template_name = 'geoform.html' @method_decorator(csrf_exempt, name='dispatch') class GetGeoCodeView(View): def post(self, request): resp = request.POST.get('response') r = client.coordinates(resp) return HttpResponse(f'{r[0]} {r[1]}')
#Импортируем библиотеку(Которую заранее установили через pip install) # т.е вам надо в командной строке ввести # pip install xlrd # pip install xlwt # pip install yandex_geocoder # далее всё должно происходить в одной папке (т.е и сама программа и excel файл будут в одной папке) import xlrd, xlwt from decimal import Decimal from yandex_geocoder import Client #вводим ключ для геокодирования адресов (это мой ключ его можно получить в кабинете разработчика яндекс) client = Client("2ef6f488-c05f-465e-b89b-9c1b17066afc") #открываем файл с ваше базой данных адресов rb = xlrd.open_workbook('api2.xls') #выбираем активный лист sheet = rb.sheet_by_index(0) ################################################################# #Задаём переменную для будующего создания нового файла wb = xlwt.Workbook() #Задаём шаблонное название страницы в Excel ws = wb.add_sheet('1', cell_overwrite_ok=True) #с А3 по Е3 записываем шапку ws.write(0, 0, "id") ws.write(0, 1, "id_people") ws.write(0, 2, "description") ws.write(0, 3, "latitude_home") ws.write(0, 4, "longitude_home") ws.write(0, 5, "latitude_other") ws.write(0, 6, "longitude_other")
import geocoder from yandex_geocoder import Client _api_key = '40d1649f-0493-4b70-98ba-98533de7710b' _client = Client(_api_key) def _current_lat_lng(): g = geocoder.ip('me') lat, lng = g.latlng return lat, lng def current_location(): lat, lng = _current_lat_lng() return _client.address(lng, lat)
# -*- coding: utf-8 -*- import telegram from telegram.ext import Updater, CommandHandler, MessageHandler, Filters from settings import token, yandex_token, parse_content, radius from decimal import Decimal from yandex_geocoder import Client import requests import re import json import geopy.distance from tinydb import TinyDB, Query from datetime import datetime updater = Updater(token, use_context=True) ya_client = Client(yandex_token) db = TinyDB('users.json', ensure_ascii=False) def get_addresses(): # dictionary for collecting covid location points points_dic = {} url = 'https://mash.ru/letter/coronavirus-2/' html = requests.get(url) dirt_adr = re.findall('(hintContent: ".+)', html.text) dirt_coords = re.findall('(ymaps.Placemark\(\[\d+.\d+,\d+.\d+\])', html.text) for i in range(len(dirt_coords)): # print(dirt_adr[i])
def test_raises_if_address_not_found(mock_api): mock_api("address_not_found", 200, geocode="337.587093,55.733969") client = Client("well-known-key") with pytest.raises(NothingFound, match='Nothing found for "337.587093 55.733969"'): client.address(Decimal("337.587093"), Decimal("55.733969"))
from django.conf import settings from rest_framework import serializers from rest_framework.serializers import ModelSerializer from apps.eats.models import Shop from yandex_geocoder import Client client = Client(settings.YANDEX_GEOCODER_KEY) class ShopSerializer(ModelSerializer): owner_id = serializers.IntegerField(source='owner.id', read_only=True) class Meta: model = Shop exclude = ['owner'] read_only_fields = ('latitude', 'longitude', 'average_dish_cost') 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 get_average_dish_cost(self, instance): pass