Spatial programming with Ruby on Rails

Many of my projects employ a spatial aspect. I am fascinated by location, context, community, and of course, the technology that drives this all. I created my travelogue a while ago, but it's rather dated, buggy, and not fun to maintain or update since it's all written in PHP as I was learning PHP.

I've really gotten "rolling with rails" (pun intended). One of the factors that really excites many developers is an active community. This can be seen by observing the Mac community (hyperlink any number of weblogs, fan sites, howtos, books, et al. here), car clubs, kennel clubs, etc. Ruby and Rails are both pumping out huge numbers of plugins, add-ons, and howtos that further fuels the fire.

However, there aren't currently any good spatial libraries or support within RoR. Specifically, I would like to store general geometry information (areas, points, lines) in a database, create the model in Rails, and then query the model with code like: @user.get_within_radius(:users, 50).

Databases and GIS


My biggest difficulty is that my shared host (Dreamhost) does not provide PostgreSQL databases, only MySQL. As anyone in the GIS field knows, PostGIS, an extension module for PostgreSQL is the requirement for proper spatial database storage and retrieval. Instead of storing locations as a pair of floats, true geometry in the form of POINT, POLYGON, CURVE, and others are used.

MySQL Spatial Extensions are began to emerge in MySQL 4.1. However, as this article on GIS and Spatial Extensions with MySQL points out, many of the core functions are missing (most notably Distance()). This is true even in the current MySQL 5.0. The result is having to do more complex queries to get distance information:

SELECT
c.cab_driver,
ROUND(GLength(LineStringFromWKB(LineString(AsBinary(c.cab_loc),
AsBinary(a.address_loc)))))
AS distance
FROM cab c, address a
WHERE a.address = 'Foobar street 110'
ORDER BY distance ASC LIMIT 1;

In the meantime, there are several stop-gap solutions. Bryan Wood (glytch.com) put together a Ruby library file that provides a small number spatial operation utilities, and is useful for operating on the "simple database scheme" of a latitude, longitude pair of float columns. The operations are performed by doing a simple SQL query where the latitude and longitude are within max/min bounds. This can't handle radius or spherical operations quickly, but is good for a rough estimate.

For an actual spherical measurement, you can do the following in your ruby code (via GeocodeAmerica):

@places = Place.find_by_sql ["select p.* from places p where
((3963.0 * acos(sin(p.latitude/57.2958) *
sin(?/57.2958) + cos(p.latitude/57.2958) * cos(?/57.2958) *
cos(?/57.2958 - p.longitude/57.2958))) < ?)",
lat, lat, lon, distance]

Extending Ruby on Rails


A better solution would be to develop a model that provides a GIS interface to a PostGIS or other OGC-style database. This requires extending the Ruby on Rails model to arbitrary column data types, and then providing the data types as getters/setters.

Given the SQL create cod:

CREATE TABLE address (
address CHAR(80) NOT NULL,
address_loc POINT NOT NULL,
PRIMARY KEY(address),
SPATIAL KEY(address_loc)
);

class Address < ActiveRecord::Base
def address_loc=(textrepresentation)
write_attribute(:address_loc,
Address.find_by_sql(["SELECT GeomFromText(?)
as value", textrepresentation]).first.value)
end

def address_loc
Address.find_by_sql(["SELECT AsText(address_loc) as value
FROM addresses WHERE id = ?", id]).first.value
end
end


Geocoding


Geocoding is the act of converting a location name (major name, street address, etc.) into latitude and longitude (or whatever your preferred numerical location representation may be).

Ruby Geocoding Resources

About this article

written on
posted in ProgrammingGeolocationRubyHowto Back to Top

About the Author

Andrew Turner is an advocate of open standards and open data. He is actively involved in many organizations developing and supporting open standards, including OpenStreetMap, Open Geospatial Consortium, Open Web Foundation, OSGeo, and the World Wide Web Consortium. He co-founded CrisisCommons, a community of volunteers that, in coordination with government agencies and disaster response groups, build technology tools to help people in need during and after a crisis such as an earthquake, tsunami, tornado, hurricane, flood, or wildfire.