Status
screenshots/videos/online info? /cc
Location
Washington, DC
Subscribe to GeoRSS Subscribe to KML


Howto

Spatial programming with Ruby on Rails

Published in Geolocation, Howto, Programming, Ruby


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


Floating text below an absolutely positioned div

Published in Howto, Programming, Web


This is probably odd to most people, but for a project I had to put a caption below an image on a webpage. But I wanted the image to be fixed in position and the caption would automatically flow and remain centered no matter how long the string was. I knew the size of the image (original div) but not the text string.

CSS CaptionThe trick lies in embedding the caption div within another div. Then the outer div should have a left: equal to half the image (or other div)’s width. The relevant CSS is:


outercaption {
	position: relative;
	left: 13px;
	}
.caption {
	text-align: center;
	position: relative;
	left: -50%;
	white-space: nowrap;
	}

Which will work with this HTML code.


Short

Here is an example. You can even put in your own text to see how it is dynamically sized.