Skip to content

Instantly share code, notes, and snippets.

@wtachau
Created January 11, 2018 19:52
Show Gist options
  • Select an option

  • Save wtachau/10adda4b2c95b8644acecd7c7370adfc to your computer and use it in GitHub Desktop.

Select an option

Save wtachau/10adda4b2c95b8644acecd7c7370adfc to your computer and use it in GitHub Desktop.
Loop up city, state from IP then determine distance from other city/state
[
["184.167.84.13", "Cheyenne", "WY"],
# ...
["205.157.110.11", "Round Rock", "TX"],
].each do |info|
d_city = info[1]
d_state = info[2]
res = Geocoder.search(info[0]).first
o_city = res.city
o_state = res.state
key = "[REDACTED]"
origin = "#{o_city},#{o_state}"
destination = "#{d_city},#{d_state}"
url = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=#{origin}&destinations=#{destination}&key=#{key}"
response = JSON.parse(RestClient.get(url))
distance = response.with_indifferent_access.try(:[], :rows).try(:first).try(:[], :elements).try(:first).try(:[], :distance).try(:[], :text)
puts "$#{o_city}, #{o_state} to #{d_city}, #{d_state}$ \t | \t #{distance}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment