Skip to content

Instantly share code, notes, and snippets.

@seamusabshere
Created October 25, 2012 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seamusabshere/3953959 to your computer and use it in GitHub Desktop.
Save seamusabshere/3953959 to your computer and use it in GitHub Desktop.
get neighborhood name and polygon using maponics spatial api
# encoding: utf-8
require 'multi_json'
require 'httpclient'
require 'cache_method'
require 'active_support/core_ext'
module Maponics
USERNAME = 'oaisjdoaisjdoaisjd'
PASSWORD = 'aosidjoasidjoaisjdoasid'
ENDPOINT = 'http://api.maponics.com/interface/'
HEADERS = {'Content-Type' => 'application/x-www-form-urlencoded'}
def Maponics.post(method, params)
x =<<-EOS
<?xml version="1.0" encoding="UTF-8" ?>
<data>
<auth>
<loginname>#{USERNAME}</loginname>
<key>#{PASSWORD}</key>
</auth>
<request>
<dataset>N</dataset>
<method>#{method}</method>
<returnType>json</returnType>
<parameters>
#{params.map { |k, v| "<#{k}>#{v.to_s.to_xs}</#{k}>" }.join }
</parameters>
</request>
</data>
EOS
res = HTTPClient.post(ENDPOINT, x, HEADERS)
payload = MultiJson.load res.body
$stderr.puts "Maponics #{method}"
if payload[0]['resultcode'] == 0
payload[1][0]
else
raise payload[0].inspect
end
end
# most efficient to get name and [n]id at the same time
def Maponics.id_by_lat_lon(lat, lon)
id_and_name_by_lat_lon(lat, lon)[0]
end
# most efficient to get name and [n]id at the same time
def Maponics.name_by_lat_lon(lat, lon)
id_and_name_by_lat_lon(lat, lon)[1]
end
def Maponics.id_and_name_by_lat_lon(lat, lon)
attr = attr_by_lat_lon(lat, lon, ['nid', 'neighborhd'])
[ attr['nid'], attr['neighborhd'] ]
end
def Maponics.attr_by_lat_lon(lat, lon, fields)
params = { lat: lat, lon: lon, fields: fields.join(',') }
data = post 'getGeoAttByCoord', params
raise "no attrs" unless data.is_a?(Hash)
data
end
def Maponics.poly_by_id(id)
data = post 'getGeoPolyByID', id: id
geom = data['geom']
raise "bad geom" unless geom =~ /\d+\.\d+/
rawlonlat = geom[(geom.index('(((')+3)...geom.rindex(')))')]
rawlonlat.split(',').map { |pair| pair.split(' ').reverse.map(&:to_f) }
end
class << self
cache_method :attr_by_lat_lon
cache_method :poly_by_id
end
end
if __FILE__ == $0
require 'redis'
CacheMethod.config.storage = Redis.new
require 'geocoder'
if (results = Geocoder.search(ARGV[0], :params => {:countrycodes => "us"})).any?
lat, lon = results[0].latitude, results[0].longitude
id = Maponics.id_by_lat_lon(lat, lon)
puts Maponics.name_by_lat_lon(lat, lon)
puts Maponics.poly_by_id(id).inspect
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment