gmaps.rb 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # Copyright (C) 2012-2016 Zammad Foundation, http://zammad-foundation.org/
  2. class Service::GeoLocation::Gmaps
  3. def self.geocode(address)
  4. url = "http://maps.googleapis.com/maps/api/geocode/json?address=#{CGI.escape address}&sensor=true"
  5. response = UserAgent.get(
  6. url,
  7. {},
  8. {
  9. open_timeout: 2,
  10. read_timeout: 4,
  11. total_timeout: 4,
  12. },
  13. )
  14. return if !response.success?
  15. result = JSON.parse(response.body)
  16. return if !result
  17. return if !result['results']
  18. return if !result['results'].first
  19. lat = result['results'].first['geometry']['location']['lat']
  20. lng = result['results'].first['geometry']['location']['lng']
  21. latlng = [lat, lng]
  22. end
  23. def self.reverse_geocode(lat, lng)
  24. url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=#{lat},#{lng}&sensor=true"
  25. response = UserAgent.get(
  26. url,
  27. {},
  28. {
  29. json: true,
  30. open_timeout: 2,
  31. read_timeout: 4,
  32. total_timeout: 4,
  33. },
  34. )
  35. return if !response.success?
  36. result = JSON.parse(response.body)
  37. address = result['results'].first['address_components'].first['long_name']
  38. address
  39. end
  40. end