Last active
August 29, 2015 14:01
-
-
Save stabenfeldt/036d5e32a118b5922d50 to your computer and use it in GitHub Desktop.
Geodata reverse lookup Ruby client
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
class GeoData | |
require 'json' | |
require 'net/http' | |
attr_reader :lat, :lon | |
def initialize(lat: lat, lon: lon) | |
@lat = lat | |
@lon = lon | |
end | |
def reverse_lookup | |
build_query_params | |
result = query_geodata | |
build_address_hash(result) | |
end | |
private | |
def build_address_hash(result) | |
a = result['address'] | |
return if a.blank? | |
hash = { | |
street: a['Adresse'], | |
place: a['Stedsnavn'], | |
poi: a['POI'], | |
post_area: a['Poststed'], | |
area_code: a['Postnummer'], | |
municipality: a['Kommune'] | |
} | |
hash.delete_if {|k, v| v == nil } | |
puts "built hash: #{hash}" | |
hash | |
end | |
def build_query_params | |
location = { x: lon, y: lat, spatialReference:{ wkid: 4326 } }.to_json | |
@uri = URI('https://services2.geodataonline.no/arcgis/rest/services/' + | |
'Geosok/GeosokLokasjon2/GeocodeServer/reverseGeocode') | |
@params = { location: location, token: generate_token, f: :json } | |
end | |
def query_geodata | |
@uri.query = URI.encode_www_form(@params) | |
res = Net::HTTP.get_response(@uri) | |
puts "result from Geodata API: #{res.body}" | |
JSON.parse(res.body) | |
end | |
def generate_token | |
uri = URI("https://tokens.geodataonline.no/arcgis/tokens/generateToken" + | |
"?username=#{ENV['GEODATA_USERNAME']}" + | |
"&password=#{ENV['GEODATA_PASSWORD']}") | |
Net::HTTP.get_response(uri).body | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment