Created
April 5, 2016 18:24
-
-
Save phsacramento/7b9093bac76d019d6e9c43a5a8a2f997 to your computer and use it in GitHub Desktop.
Geocoder.rb
This file contains hidden or 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 'geocoder' | |
module ImportXML | |
class Geocoder | |
attr_accessor :result | |
GERMAN_STATES = { | |
"Germany" => "Deutschland", | |
"Bavaria" => "Bayern", | |
"Hesse" => "Hessen", | |
"Lower Saxony" => "Niedersachsen", | |
"North Rhine-Westphalia" => "Nordrhein-Westfalen", | |
"Saxony" => "Sachsen", | |
"Saxony-Anhalt" => "Sachsen-Anhalt", | |
"Thuringia" => "Thüringen" | |
} | |
def initialize(options={}) | |
@street = options[:street] | |
@number = options[:number] | |
@city = options[:city] | |
@postal_code = options[:postal_code] | |
@latitude = options[:latitude] || nil | |
@longitude = options[:longitude] || nil | |
@country = options[:country] || 'Germany' | |
@force_search = options[:force_search] || false | |
::Geocoder.configure(:lookup => :google_premier, :api_key => ['6tmZ1qZL7Gq-wv9JFVZDs80pqvE=', 'gme-smmovedeutschland', '']) | |
end | |
def geocordinates | |
response = search() | |
return nil unless response | |
return OpenStruct.new(response.data['geometry']['location']) if @force_search || (@latitude.nil? && @longitude.nil?) | |
OpenStruct.new(lat: @latitude, lng: @longitude) | |
end | |
def search | |
@result = ::Geocoder.search(full_address).first | |
end | |
def state | |
begin | |
state_english = @result.data['address_components'].reject{|x| !x['types'].include?('administrative_area_level_1')}.first['long_name'] | |
state_german = GERMAN_STATES[state_english] | |
return state_english unless state_german.present? | |
state_german | |
rescue Exception => e | |
nil | |
end | |
end | |
def country?(name) | |
@result.data['address_components'].collect{|x| x['long_name']}.include?(name) | |
end | |
private | |
def full_address | |
[@street, @number, @city, @postal_code, @country].compact.join(', ') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment