DEV Community

Cover image for Geocoding with Ruby
Davide Santangelo
Davide Santangelo

Posted on

Geocoding with Ruby

Geocoding is the process of converting addresses or place names into geographical coordinates, such as latitude and longitude. These coordinates can then be used to place markers on a map, or to perform other spatial operations.

In this article, we will explore how to perform geocoding using the Ruby programming language. We will cover several different approaches, including using the geocoder gem, the Google Maps API, and the Mapbox API.

Using the geocoder gem

The geocoder gem is a popular Ruby gem that provides a simple interface for geocoding and reverse geocoding (converting coordinates to addresses). It supports a variety of geocoding providers, including Google Maps, Bing Maps, and OpenStreetMap.

To use the geocoder gem, you will need to install it first. Open a terminal and enter the following command:

gem install geocoder
Enter fullscreen mode Exit fullscreen mode

Once the gem is installed, you can use it in your Ruby code by requiring it and creating a new instance of the Geocoder class. For example:

require 'geocoder'

geocoder = Geocoder.new
Enter fullscreen mode Exit fullscreen mode

To perform a geocoding query, you can call the geocode method on the geocoder object, passing in the address or place name that you want to geocode. For example:

result = geocoder.geocode("1600 Amphitheatre Parkway, Mountain View, CA")

if result.success?
  puts "Latitude: #{result.latitude}"
  puts "Longitude: #{result.longitude}"
else
  puts "Geocoding failed: #{result.message}"
end
Enter fullscreen mode Exit fullscreen mode

This will output the latitude and longitude of the specified address. If the geocoding query fails, it will output an error message.

You can also use the reverse_geocode method to convert coordinates to an address. For example:

result = geocoder.reverse_geocode(37.423021, -122.083739)

if result.success?
  puts "Address: #{result.address}"
else
  puts "Reverse geocoding failed: #{result.message}"
end
Enter fullscreen mode Exit fullscreen mode

Using the Google Maps API

Another option for geocoding with Ruby is to use the Google Maps API. This requires creating a Google Maps API key and making HTTP requests to the API's geocoding endpoint.

To get started, you will need to sign up for a Google Cloud account and enable the Google Maps API. You can then create an API key in the Google Cloud Console.

Once you have an API key, you can use it to make geocoding requests in Ruby using the Net::HTTP class. For example:

require 'net/http'
require 'uri'

# Replace YOUR_API_KEY with your actual API key
api_key = "YOUR_API_KEY"

# Set up the URL for the geocoding request
url = URI("https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=#{api_key}")

# Make the request and parse the response
response = Net::HTTP.get(url)
json = JSON.parse(response)
Enter fullscreen mode Exit fullscreen mode

To parse the response and extract the latitude and longitude, you can use the following code:

# Check the status code to make sure the request was successful
if json["status"] == "OK"
  # Extract the latitude and longitude from the first result
  result = json["results"][0]
  lat = result["geometry"]["location"]["lat"]
  lng = result["geometry"]["location"]["lng"]

  puts "Latitude: #{lat}"
  puts "Longitude: #{lng}"
else
  puts "Geocoding failed: #{json["status"]}"
end
Enter fullscreen mode Exit fullscreen mode

You can also perform reverse geocoding using the Google Maps API by making a request to the reverseGeocode endpoint and passing in the latitude and longitude coordinates. For example:

# Set up the URL for the reverse geocoding request
url = URI("https://maps.googleapis.com/maps/api/geocode/json?latlng=37.423021,-122.083739&key=#{api_key}")

# Make the request and parse the response
response = Net::HTTP.get(url)
json = JSON.parse(response)

# Check the status code to make sure the request was successful
if json["status"] == "OK"
  # Extract the formatted address from the first result
  result = json["results"][0]
  address = result["formatted_address"]

  puts "Address: #{address}"
else
  puts "Reverse geocoding failed: #{json["status"]}"
end
Enter fullscreen mode Exit fullscreen mode

Using the Mapbox API

Mapbox is another popular mapping platform that provides a geocoding API. Like the Google Maps API, it requires creating an API key and making HTTP requests to its geocoding endpoint.

To get started with the Mapbox API, you will need to sign up for a Mapbox account and create an API key. Once you have an API key, you can use it to make geocoding requests in Ruby using the Net::HTTP class.

For example:

require 'net/http'
require 'uri'

# Replace YOUR_API_KEY with your actual API key
api_key = "YOUR_API_KEY"

# Set up the URL for the geocoding request
url = URI("https://api.mapbox.com/geocoding/v5/mapbox.places/1600+Amphitheatre+Parkway,+Mountain+View,+CA.json?access_token=#{api_key}")

# Make the request and parse the response
response = Net::HTTP.get(url)
json = JSON.parse(response)

# Check the status code to make sure the request was successful
if json["code"] == "Ok"
  # Extract the latitude and longitude from the first result
  result = json["features"][0]
  lat = result["center"][1]
  lng = result["center"][0]

  puts "Latitude: #{lat}"
  puts "Longitude: #{lng}"
else
  puts "Geocoding failed: #{json["message"]}"
end
Enter fullscreen mode Exit fullscreen mode

You can also perform reverse geocoding using the Mapbox API by making a request to the reverse endpoint and passing in the latitude and longitude coordinates. For example:

# Set up the URL for the reverse geocoding request
url = URI("https://api.mapbox.com/geocoding/v5/mapbox.places/37.423021,-122.083739.json?access_token=#{api_key}")

# Make the request and parse the response
response = Net::HTTP.get(url)
json = JSON.parse(response)

# Check the status code to make sure the request was successful
if json["code"] == "Ok"
  # Extract the formatted address from the first result
  result = json["features"][0]
  address = result["place_name"]

  puts "Address: #{address}"
else
  puts "Reverse geocoding failed: #{json["message"]}"
end
Enter fullscreen mode Exit fullscreen mode

Conclusion

In this article, we have explored how to perform geocoding with Ruby using the geocoder gem, the Google Maps API, and the Mapbox API. Each of these approaches has its own strengths and limitations, and you can choose the one that best fits your needs.

Whether you are building a mapping application, a location-based service, or just need to convert addresses to coordinates for some other purpose, geocoding is a valuable tool that can help you work with geographical data in your Ruby projects.

Top comments (0)