Created
March 30, 2017 20:41
-
-
Save thesunwave/bfbc3d486dac666071a9b6cf00660695 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rest-client' | |
class YandexGeocoder | |
attr_reader :data, :address | |
NotFound = Class.new(StandardError) | |
EmptyRequest = Class.new(StandardError) | |
BASE_URL = 'https://geocode-maps.yandex.ru/1.x/'.freeze | |
PARAMS = { | |
format: :json, | |
results: 1, | |
geocode: nil | |
} | |
def initialize(address) | |
@address = address | |
end | |
def data | |
@data ||= response(address) | |
end | |
def region | |
data['metaDataProperty']['GeocoderMetaData']['AddressDetails']['Country']['AdministrativeArea']['AdministrativeAreaName'] | |
end | |
def city | |
address_components.select { |e| e['kind'] == 'locality' }.map { |e| e['name'] }.first | |
end | |
def street | |
address_components.select { |e| e['kind'] == 'street' }.map { |e| e['name'] }.first | |
end | |
def house | |
address_components.select { |e| e['kind'] == 'house' }.map { |e| e['name'] }.first | |
end | |
def full_address | |
data['metaDataProperty']['GeocoderMetaData']['Address']['formatted'] | |
end | |
def coords | |
arr = data['Point']['pos'].split(' ').map(&:to_f).reverse | |
{ | |
lat: arr[0], | |
lon: arr[1] | |
} | |
end | |
private | |
def request(address) | |
JSON.parse(RestClient.get(BASE_URL, params: PARAMS.merge(geocode: address)).body) | |
end | |
def response(address) | |
raise EmptyRequest, "Your request is empty" if address.empty? | |
result = request(address)['response']['GeoObjectCollection'] | |
if result['featureMember'].empty? | |
response = result['metaDataProperty']['GeocoderResponseMetaData'] | |
raise NotFound, "Found #{response['found']} equals by request: #{response['request']}" | |
else | |
result['featureMember'][0]['GeoObject'] | |
end | |
end | |
def address_components | |
data['metaDataProperty']['GeocoderMetaData']['Address']['Components'] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment