Ruby

Mapricot's API is plain HTTPS and JSON, so Ruby's standard library covers it, with no gem to install. This page calls each API: geocoding, places, routing, and IP geolocation, and shows where the free map tiles fit. It was tested with Ruby 3.3.

Set up

Create a server key in the dashboard with the products you'll use: Places for geocoding and places, Routing, and IP geolocation. Set it as an environment variable, so it stays out of your code:

export MAPRICOT_KEY="mapricot_sk_…"

Then add a method that sends the key with every request, retries when the API is busy, and raises on errors. It sends a POST when there's a body:

require "json"
require "net/http"

def mapricot(path, params: nil, body: nil)
  uri = URI("https://api.mapricot.com#{path}")
  uri.query = URI.encode_www_form(params) if params
  request = body ? Net::HTTP::Post.new(uri, "Content-Type" => "application/json") : Net::HTTP::Get.new(uri)
  request["Authorization"] = "Bearer #{ENV.fetch("MAPRICOT_KEY")}"
  request.body = JSON.generate(body) if body
  (1..4).each do |attempt|
    response = Net::HTTP.start(uri.host, uri.port, use_ssl: true, open_timeout: 10, read_timeout: 30) do |http|
      http.request(request)
    end
    if %w[429 503].include?(response.code) && attempt < 4
      sleep 2**attempt
      next
    end
    json = JSON.parse(response.body)
    raise "Mapricot returned #{response.code}: #{json["error"]["message"]}" unless response.is_a?(Net::HTTPSuccess)
    return json
  end
end

Geocode an address

/v1/search turns an address or place name into coordinates:

data = mapricot("/v1/search", params: { q: "128 SW 3rd Ave, Portland", limit: 1 })
data["results"].each do |result|
  puts "#{result["label"]} #{result["lat"]} #{result["lon"]}"
end
128 SW 3rd Avenue, Portland, OR, USA 45.521736 -122.673276

Each result also has its address in parts under address, and a type, such as address, street, or locality, that says how exact the match is. To limit results to some countries, pass country: "US,CA". Geocoding lists every parameter and field.

Find the address at a point

/v1/reverse turns coordinates into the nearest address:

nearest = mapricot("/v1/reverse", params: { lat: 45.5217, lon: -122.6733, limit: 1 })["results"].first
puts "#{nearest["label"]} #{nearest["distanceMeters"]}"
128 SW 3rd Avenue, Portland, OR, USA 4

Suggest places as someone types

/v1/autocomplete takes the text typed so far. focus ranks results near a point first:

suggestion = mapricot("/v1/autocomplete", params: { q: "stumpt", focus: "45.52,-122.68", limit: 1 })["results"].first
puts "#{suggestion["label"]} #{suggestion["id"]}"
Stumptown Coffee Roasters, Portland, OR, USA mp_b3BlbnN0cmVldG1hcDp2ZW51ZTpub2RlLzExOTg2MjI2NjYw

Find places nearby

/v1/nearby lists places of a category around a point, nearest first:

data = mapricot("/v1/nearby", params: { lat: 45.52, lon: -122.68, category: "food:coffee_shop", radius: 1000, limit: 1 })
data["results"].each do |place|
  puts "#{place["name"]} #{place["distanceMeters"]}"
end
Public Domain 37

Look up a place by ID

Every result has an id. Save it, and /v1/places/{id} fetches that place again later:

place = mapricot("/v1/places/#{suggestion["id"]}")["result"]
puts place["label"]
Stumptown Coffee Roasters, Portland, OR, USA

Get a route

/v1/route takes a JSON body with two to 20 waypoints and a mode of drive, walk, or bicycle:

route = mapricot("/v1/route", body: {
  waypoints: [{ lat: 43.7396, lon: 7.4275 }, { lat: 43.734, lon: 7.4222 }],
  mode: "walk",
})["routes"].first
puts "#{route["distanceMeters"]} #{route["durationSeconds"]}"
1044 739

Distances are in meters and times in seconds. When no path connects the waypoints, routes is empty. The route's line is in polyline, encoded with six decimal places, so decode it with precision 6, as decoding a route polyline explains.

Look up an IP address

/v1/ip/{ip} gives the approximate location of an IPv4 or IPv6 address:

location = mapricot("/v1/ip/8.8.8.8")
puts "#{location["city"]} #{location["countryCode"]}"
Mountain View US

Show a map

Map tiles are free and need no key. MapLibre GL JS draws them in the browser from https://tiles.mapricot.com/styles/light.json, so Ruby doesn't fetch them: send your results to a web page, and draw them there, as Map tiles shows. MapLibre takes coordinates as [lon, lat].

Errors and retries

mapricot raises a RuntimeError for any error response, with the status and the API's message:

begin
  mapricot("/v1/search", params: { q: "" })
rescue RuntimeError => error
  puts error.message
end
Mapricot returned 400: The service rejected the request.

It retries 429 and 503 responses up to three times, waiting 2, 4, then 8 seconds. Errors aren't billed, so retrying them costs nothing. A 429 that keeps coming back can also mean the account is out of credit. Each account has a limit on requests in progress at once, so send requests one at a time or a few at once. The API reference lists every status.