1 # frozen_string_literal: true
 
   4   class NominatimQueriesController < QueriesController
 
   5     include NominatimMethods
 
   9       response = fetch_xml(nominatim_query_url(:format => "xml"))
 
  11       # extract the results from the response
 
  12       results = response.elements["searchresults"]
 
  17       # create parameter hash for "more results" link
 
  19                      .permit(:query, :minlon, :minlat, :maxlon, :maxlat, :exclude)
 
  20                      .merge(:exclude => results.attributes["exclude_place_ids"])
 
  23       results.elements.each("place") do |place|
 
  24         lat = place.attributes["lat"]
 
  25         lon = place.attributes["lon"]
 
  26         klass = place.attributes["class"]
 
  27         type = place.attributes["type"]
 
  28         name = place.attributes["display_name"]
 
  29         min_lat, max_lat, min_lon, max_lon = place.attributes["boundingbox"].split(",")
 
  30         prefix_name = if type.empty?
 
  33                         t "geocoder.search_osm_nominatim.prefix.#{klass}.#{type}", :default => type.tr("_", " ").capitalize
 
  35         if klass == "boundary" && type == "administrative"
 
  36           rank = (place.attributes["address_rank"].to_i + 1) / 2
 
  37           prefix_name = t "geocoder.search_osm_nominatim.admin_levels.level#{rank}", :default => prefix_name
 
  40           place_tags = %w[linked_place place]
 
  41           place.elements["extratags"].elements.each("tag") do |extratag|
 
  42             border_type = t "geocoder.search_osm_nominatim.border_types.#{extratag.attributes['value']}", :default => border_type if extratag.attributes["key"] == "border_type"
 
  43             place_type = t "geocoder.search_osm_nominatim.prefix.place.#{extratag.attributes['value']}", :default => place_type if place_tags.include?(extratag.attributes["key"])
 
  45           prefix_name = place_type || border_type || prefix_name
 
  47         prefix = t "geocoder.search_osm_nominatim.prefix_format", :name => prefix_name
 
  48         object_type = place.attributes["osm_type"]
 
  49         object_id = place.attributes["osm_id"]
 
  51         @results.push(:lat => lat, :lon => lon,
 
  52                       :min_lat => min_lat, :max_lat => max_lat,
 
  53                       :min_lon => min_lon, :max_lon => max_lon,
 
  54                       :prefix => prefix, :name => name,
 
  55                       :type => object_type, :id => object_id)
 
  57     rescue StandardError => e
 
  58       host = URI(Settings.nominatim_url).host
 
  59       @error = "Error contacting #{host}: #{e}"
 
  60       render :action => "error"