Skip to content

Instantly share code, notes, and snippets.

@IzumiSy
Last active November 21, 2018 00:33
Show Gist options
  • Save IzumiSy/3fe0aba974054a558ee53f7611c8318d to your computer and use it in GitHub Desktop.
Save IzumiSy/3fe0aba974054a558ee53f7611c8318d to your computer and use it in GitHub Desktop.
require "faraday"
require "json"
require "awesome_print"
require "byebug"
module Geolocation
class Result
attr_reader :address_components, :formatted_address, :geometry, :place_id, :types
def initialize(address_components, formatted_address, geometry, place_id, types)
@address_components = address_components
@formatted_address = formatted_address
@geometry = geometry
@place_id = place_id
@types = types
end
end
class Address
attr_reader :long_name, :short_name, :types
def initialize(long_name, short_name, types)
@long_name = long_name
@short_name = short_name
@types = types
end
end
class Geometry
attr_reader :bounds, :location, :location_type, :viewport
def initialize(bounds, location, location_type, viewport)
@bounds = bounds.map { |k, v| [k.to_sym, Geolocation::Geometry::LatLng.new(v["lat"], v["lng"])] }.to_h
@location = LatLng.new(location["lat"], location["lng"])
@location_type = location_type
@viewport = viewport.map { |k, v| [k.to_sym, Geolocation::Geometry::LatLng.new(v["lat"], v["lng"])] }.to_h
end
LatLng = Struct.new(:latitude, :longitude)
end
API_KEY = "hoge" # TODO
BASE_URL = "https://maps.googleapis.com/maps/api/geocode/json?"
def address_lookup(address)
parse_response Faraday.get("#{BASE_URL}address=#{address}&key=#{API_KEY}")
rescue => e
# TODO
end
def latlng_lookup
parse_response Faraday.get("#{BASE_URL}latlng=#{latitude},#{longitude}&key=#{API_KEY}")
rescue => e
# TODO
end
private
def parse_response(response)
_results = JSON.parse(response.body)
_results = _results["results"]
_results.map do |r|
address_components = r["address_components"].map { |a| Geolocation::Address.new(a["long_name"], a["short_name"], a["types"]) }
g = r["geometry"]
geometry = Geolocation::Geometry.new(g["bounds"], g["location"], g["location_type"], g["viewport"])
Geolocation::Result.new(address_components, r["formatted_address"], geometry, r["place_id"], r["types"])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment