osm.rb 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Service::GeoLocation::Osm
  3. OSM_SEARCH_URL = 'https://nominatim.openstreetmap.org/search?q=%s&format=jsonv2'.freeze
  4. OSM_REVERSE_URL = 'https://nominatim.openstreetmap.org/reverse?lat=%s&lon=%s&format=jsonv2'.freeze
  5. def self.geocode(address)
  6. url = format(OSM_SEARCH_URL, CGI.escape(address))
  7. response = UserAgent.get(
  8. url,
  9. {},
  10. {
  11. open_timeout: 2,
  12. read_timeout: 4,
  13. total_timeout: 4,
  14. verify_ssl: true,
  15. },
  16. )
  17. return if !response.success?
  18. result = JSON.parse(response.body)
  19. return if !result || !result.first
  20. lat = result.first['lat'].to_f
  21. lng = result.first['lon'].to_f
  22. [lat, lng]
  23. end
  24. def self.reverse_geocode(lat, lng)
  25. url = format(OSM_REVERSE_URL, lat, lng)
  26. response = UserAgent.get(
  27. url,
  28. {},
  29. {
  30. json: true,
  31. open_timeout: 2,
  32. read_timeout: 4,
  33. total_timeout: 4,
  34. verify_ssl: true,
  35. },
  36. )
  37. return if !response.success?
  38. result = JSON.parse(response.body)
  39. return if !result
  40. result['display_name']
  41. end
  42. end