Skip to content

Instantly share code, notes, and snippets.

@amitpatelx
Created September 21, 2020 07:56
Show Gist options
  • Save amitpatelx/332f64fe59be358af6f168cefc4599f7 to your computer and use it in GitHub Desktop.
Save amitpatelx/332f64fe59be358af6f168cefc4599f7 to your computer and use it in GitHub Desktop.
Set city, zipcode, address from lat and long using Geocoder
# Utility method to set city, zipcode and address from geolocation
# +item+ - a hash which should have latitude and longitude set
# +skip_city+ - set to true to skip setting city from geolocation
# +skip_zipcode+ - set to true to skip setting zipcode from geolocation
# +skip_address+ - set to true to skip setting address from geolocation
def self.set_location_details!(item:, skip_city: false, skip_zipcode: false, skip_address: false)
results = Geocoder.search([item[:latitude], item[:longitude]])
if results.present?
unless skip_city
result = results.first.address_components.find { |c| c['types'].include?('locality') }
item[:city] = result['long_name'] if result.present?
end
return if skip_zipcode && skip_address
nearest_location = results.first
return if nearest_location.blank?
item[:zipcode] = nearest_location.postal_code unless skip_zipcode
item[:address] = nearest_location.formatted_address unless skip_address
end
end
...
...
# Set latitude and longitude
item[:latitude] = <set latitude here>
item[:longitude] = <set longitude here>
# Set city, zipcode and address
ApplicationSpider.set_location_details!(item: item)
# Set only zipcode and address skipping city
ApplicationSpider.set_location_details!(item: item, skip_city: true)
# pass skip_city, skip_zipcode, skip_address etc with boolean `true` as required. Default is false for all those options.
# You can always override values set by `set_location_details!` after you make call to it like
ApplicationSpider.set_location_details!(item: item)
item[:city] = 'Copenhagen'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment