Get Distance Between 2 Cities in Ruby
I had to find the distance between 2 cities using Ruby, here is my code. Note that you can find out about the Yahoo REST API and the geocoder.us service by following those links. You will need to sign up for a Yahoo developer key (it’s free and a quick form). I’ve included the default Yahoo API key below so the sample will work.
I know, I’m not parsing the XML response the right way, but it works, I needed to hack something together for my Seattle Accountant Site and I didn’t want to deal with XML parsing.
You will also notice that I added a retry for the HTTP request. I need this as this script is run many times in a row and occasionally the request fails. So much for TCP being a “reliable” protocol.
def get_url2(url)
retry_count = 0
while true
begin
return resp = Net::HTTP.get_response(URI.parse(url))
rescue
retry_count+=1
puts "retrying " + retry_count.to_s() + ":" + url
end
end
end
def get_city_distance(city1, state1, city2, state2)
url = "http://local.yahooapis.com/MapsService/V1/geocode?appid=BswRHq7V34F6vFQJHH_PH29zDy9AkdHq7TGuUk8jPYCPq9QfILVzoZIOi1Mu7Bp_hQ--&city=" + city1.gsub(' ','+') + "&state=" + state1
resp = get_url2(url)
long1 = resp.body.split('<Longitude>')[1].split('</Longitude>')[0]
lat1 = resp.body.split('<Latitude>')[1].split('</Latitude>')[0]
url = "http://local.yahooapis.com/MapsService/V1/geocode?appid=BswRHq7V34F6vFQJHH_PH29zDy9AkdHq7TGuUk8jPYCPq9QfILVzoZIOi1Mu7Bp_hQ--&city=" + city2.gsub(' ','+') + "&state=" + state2
resp = get_url2(url)
long2 = resp.body.split('<Longitude>')[1].split('</Longitude>')[0]
lat2 = resp.body.split('<Latitude>')[1].split('</Latitude>')[0]
url = "http://geocoder.us/service/distance?lat1=" + lat1 + "&lat2=" + lat2 + "&lng1=" + long1 + "&lng2=" + long2
resp = get_url2(url)
distance = resp.body.split("=")[1].split('miles')[0].strip.to_f
#puts lat1 + "," + long1 + "," + lat1 + "," +lat2 + ": '" + distance.to_s + "'"
return distance
end