Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ok.rb -- Geocoder Gem

Ok.rb -- Geocoder Gem

Jon McCartie

May 12, 2011
Tweet

More Decks by Jon McCartie

Other Decks in Programming

Transcript

  1. Geocoding is a pain SELECT *, 3958.755864232 * 2 *

    ASIN(SQRT(POWER(SIN((35.6527 - lat) * PI() / 180 / 2), 2) + COS(35.6527 * PI() / 180) * COS(lat * PI() / 180) * POWER(SIN((-97.419 - lng) * PI() / 180 / 2), 2) )) AS distance, CAST(DEGREES(ATAN2( RADIANS(lng - -97.419), RADIANS(lat - 35.6527))) + 360 AS decimal) % 360 AS bearing FROM "locations" WHERE (lat BETWEEN 35.21850465066746 AND 36.08689534933254 AND lng BETWEEN -97.95335153642718 AND -96.88464846357282
  2. Geo at LifeChurch.tv § Current process: § Load Maxmind DAT

    file (27mb) –or— § Put entire MaxMind data file into your database § Query for the user’s IP, get Lat/Lng § Query database for nearest location
  3. Behold! The Geocoder Gem! § Geocoding § by street or

    IP address § Reverse geocoding § find street address based on given coordinates § Distance queries § Example: Venue.near("Billings, MT")
  4. Geo By IP § IP: 70.112.132.198 § = debug request.location

    § data: § city: Round Rock § region_code: TX § region_name: Texas § metrocode: '635' § zipcode: '' § longitude: '-97.6795' § country_name: United States § country_code: US § ip: 70.112.132.198 § latitude: '30.5248'
  5. Model Setup § Have latitude / longitude columns? You’re done.

    § Named something else? class Location < ActiveRecord::Base geocoded_by :address, :latitude => :lat, :longitude => :lng end § Don’t have lat/long? Have an address? def address [street_1, city, state, country].compact.join(', ') end
  6. Geo Queries § Nearest LifeChurch.tv location § Location.near(request.location.coordinates).first § Distance

    to that location? § @nearest.distance_to(request.coordinates) § Midpoint between here and there? § Geocoder::Calculations.geographic_center([@loc_array, [@nearest.lat, @nearest.lng]])
  7. Geo Queries § Bearing to that point? § @nearest.bearing §

    Compass direction? (N, NW, etc) § Geocoder::Calculations.compass_point(@nearest.bearing.to_i) § Other locations nearby? § @nearest.nearbys(30)
  8. Reverse Geocoding § No Lat/Lng? No problem! § Assuming an

    “address method” on your model: def address [street_1, city, state, country].compact.join(', ') end Geocoder.search( Location.where(:name => "Fort Worth").first.address_array )
  9. More info § http://www.rubygeocoder.com/ § https://github.com/alexreisner/geocoder § My demo page

    for this presentation: § http://okrb-geo.heroku.com/ § https://github.com/jmccartie/OK.RB----Geocoder-Demo § Me: § Twitter/Github: jmccartie § http://lifechurch.tv/causes/digital-missions § https://github.com/lifechurch