Skip to content

Commit

Permalink
Task to fill lat/lng for those labs missing values
Browse files Browse the repository at this point in the history
Over the past two years a bug in lab form resulted in no lat/lng
being saved to the database. With this task, call
the Places API to try fill in missing values.
To test/run on production server.
  • Loading branch information
MacTwister committed Oct 18, 2023
1 parent af32ddf commit c3f0a89
Showing 1 changed file with 60 additions and 0 deletions.
60 changes: 60 additions & 0 deletions lib/tasks/fixes.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
require 'httparty'

namespace :fixes do

desc "Any labs without GEO coordinates, fill from address"
task labsgeo: :environment do

labs = Lab.where(latitude: nil)

labs.each do |lab|

query_lines = []
query_lines << lab.address_1 if lab.address_1.present?
query_lines << lab.address_2 if lab.address_2.present?
query_lines << lab.city if lab.city.present?
query_lines << lab.county if lab.county.present?
query_lines << lab.subregion if lab.subregion.present?
query_lines << lab.region if lab.region.present?
query_lines << lab.postal_code if lab.postal_code.present?
query_lines << lab.country_code if lab.country_code.present?

querytext = query_lines.join(', ')

puts querytext

response = HTTParty.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json',
query: {
key: ENV['GOOGLE_PLACES_API_KEY'],
input: querytext,
fields: 'formatted_address,name,geometry',
inputtype: 'textquery',
},
)

data = JSON.parse(response.body)

if !data.key?('candidates') || !data['candidates'].is_a?(Array)
warn "#{lab.slug}: No results returned."
next
end

if data['candidates'].empty?
warn "#{lab.slug}: No results returned."
next
end

if data['candidates'].length > 1
warn "#{lab.slug}: More than one result, skipping..."
next
end

result = data['candidates'].first

puts "FOUND: #{result['geometry']['location']['lat']}"

lab.update(latitude: result['geometry']['location']['lat'], longitude: result['geometry']['location']['lng'])

end
end
end

0 comments on commit c3f0a89

Please sign in to comment.