Skip to content

Instantly share code, notes, and snippets.

@HarlemSquirrel
Created September 12, 2022 19:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HarlemSquirrel/fdfbc37e1542421c8b44aceaac784f9e to your computer and use it in GitHub Desktop.
Save HarlemSquirrel/fdfbc37e1542421c8b44aceaac784f9e to your computer and use it in GitHub Desktop.
Compare location-biased autocomplete search results from Mapbox and Google Places
#!/usr/bin/env ruby
##
# Compare location-biased autocomplete search results from Mapbox and Google Places
#
require 'json'
require 'net/http'
QUERIES = [
'beer',
'disn',
'hospital',
'downtown'
]
# lat,long
COORDINATES = {
"Denver Airport": [39.849, -104.673],
"New Orleans Jackson Square": [29.957857133560957, -90.06446474050662],
"Bangor, ME Airport": [44.777,-68.828],
"Shipyard Brewing Co, Portland, ME": [43.662129666625134, -70.24868070388654]
}
COORDINATES.each do |from_name, coordinates|
puts "\n🧍 #{from_name} - #{coordinates}"
QUERIES.each do |query|
puts " 🔎 #{query}"
# https://docs.mapbox.com/api/search/geocoding/#forward-geocoding
uri = URI("https://api.mapbox.com/geocoding/v5/mapbox.places/#{query}.json")
params = { access_token: ENV.fetch('MAPBOX_ACCESS_TOKEN'), limit: 3, proximity: coordinates.reverse.join(',') }
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
puts " Mapbox"
JSON.parse(res.body)["features"].each_with_index do |feature, i|
puts " #{i + 1}. #{feature['text']} (#{feature["place_name"]})"
end
else
raise res
end
# https://developers.google.com/maps/documentation/places/web-service/autocomplete
uri = URI("https://maps.googleapis.com/maps/api/place/autocomplete/json")
params = { key: ENV.fetch('GOOGLE_API_KEY'), limit: 3, input: query, locationbias: "circle:10000@#{coordinates.join(',')}" }
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
puts " Google Places Autocomplete"
JSON.parse(res.body)["predictions"][0..2].each_with_index do |prediction, i|
puts " #{i + 1}. #{prediction['description']}"
end
else
raise res
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment