user4584963
user4584963

Reputation: 2523

Ruby hash with duplicate keys to create URL parameters

I am using a hash for parameters to be used in generating a URL. I have something like this:

params = {
  :center => Geocoder.coordinates(currentlocation).join(","),
  :zoom => 10,
  :size => "460x280",
  :markers => Geocoder.coordinates(markerlocation).join(","),
  :sensor => true,
  :key => ENV["GOOGLE_API_KEY"]
  }

query_string =  params.map{|k,v| "#{k}=#{v}"}.join("&")
image_tag "https://maps.googleapis.com/maps/api/staticmap?#{query_string}", :alt => location

However I need to have multiple "markers" parameters in the URL. For each URL I generate I won't know how many "markers" parameters I need. For example if I have an array markerlocations I will need to create a :markers key-value pair for each member of the array for use in the URL. What is the best way to accomplish this?

Upvotes: 1

Views: 201

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

require 'net/http'
params = {
  :center => Geocoder.coordinates(currentlocation).join(","),
  :zoom => 10,
  :size => "460x280",
  :markers => [Geocoder.coordinates(markerlocation).join(",")],
  :sensor => true,
  :key => ENV["GOOGLE_API_KEY"]
  }
query_string = URI.encode_www_form(params)
image_tag ...

Upvotes: 1

Related Questions