Commit ef32c5d
Changed files (2)
app
helpers
GeoLocationService
app/helpers/GeoLocationService/spec/GeoLocationService_spec.rb
@@ -0,0 +1,42 @@
+require_relative '../GeoLocationService.rb'
+
+describe GeoLocationService do
+ it "can get a location" do
+ result = GeoLocationService.GetGeoLocation("Stampede Grounds, Calgary, Alberta")
+ result.should_not be_nil
+ result.should be_an_instance_of(GeoLocation)
+ end
+
+ it "can get a correction location" do
+ result = GeoLocationService.GetGeoLocation("Stampede Grounds, Calgary, Alberta")
+ result.should_not be_nil
+ result.x.should_not be_nil
+
+ end
+
+ it "can get a location data" do
+ result = GeoLocationService.GetGeoLocationData("Stampede Grounds, Calgary, Alberta")
+ result.should_not be_nil
+ end
+
+ it "can parse json result to get geolocation" do
+ json = GeoLocationService.GetGeoLocationData("Stampede Grounds, Calgary, Alberta")
+ result = GeoLocationService.ExtractGeoLocationFromJson(json)
+ result.should_not be_nil
+ result.should be_an_instance_of(GeoLocation)
+ end
+
+ it "can get correct geo location for stampede grounds" do
+ result = GeoLocationService.GetGeoLocation("Stampede Grounds, Calgary, Alberta")
+ result.should be_an_instance_of(GeoLocation)
+ result.x.should be_within(0.0001).of(-114.0630194)
+ result.y.should be_within(0.0001).of(51.045220523)
+ end
+
+ it "can look up by address" do
+ result = GeoLocationService.GetGeoLocation("200 E Randolph St, Chicago, IL")
+ result.should be_an_instance_of(GeoLocation)
+ result.x.should be_within(0.0001).of(-87.6221405679)
+ result.y.should be_within(0.0001).of(41.8845104628)
+ end
+end
\ No newline at end of file
app/helpers/GeoLocationService/GeoLocationService.rb
@@ -0,0 +1,42 @@
+# A service that can look up a geo-location from a string
+# the api this is based on (ERSI) seems fairly robust and can
+# take landmarks (Stampede Grounds) and street addresses.
+
+# work by Chris Desmarais (codeshoulders@gmail.com)
+
+require 'rest_client'
+require 'open-uri'
+require 'json'
+
+class GeoLocationService
+
+ def self.GetGeoLocation( locationString)
+ return ExtractGeoLocationFromJson( GetGeoLocationData( locationString ) )
+ end
+
+ def self.GetGeoLocationData(locationString)
+ urlAsString = "http://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?f=pjson&text="
+ urlAsString += URI::encode(locationString)
+ return RestClient.get urlAsString
+ end
+
+ def self.ExtractGeoLocationFromJson( jsonString)
+ parsed = JSON.parse(jsonString)
+
+ # need to handle more than one match
+ x = parsed["locations"][0]["feature"]["geometry"]["x"]
+ y = parsed["locations"][0]["feature"]["geometry"]["y"]
+ return GeoLocation.new( x, y)
+ end
+end
+
+class GeoLocation
+
+ attr_accessor :x, :y
+
+ def initialize (x,y)
+ @x = x
+ @y = y
+ end
+end
+