通过传递Zipcode,从Google地理编码服务中检索城市州和邮政信息
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过传递Zipcode,从Google地理编码服务中检索城市州和邮政信息相关的知识,希望对你有一定的参考价值。
require 'net/http' require 'uri' require "rexml/document" # Retrieves US Location data based on a passed in Zipcode. Uses # Google Maps geocoding service to retrieve a Hash of city, state, and zip # For more info on the service see: http://code.google.com/apis/maps/documentation/geocoding/ # # example: # puts get_location_data(97030).inspect # outputs: # {:state=>"OR", :zip=>"97030", :city=>"Gresham"} def get_location_data(zip) url = "http://maps.google.com/maps/geo" uri = URI.parse(url) req = Net::HTTP::Get.new(uri.path + "?output=xml&q=#{zip}") res = Net::HTTP.start(uri.host, uri.port) do |http| http.request(req) end data = res.body result = {} address = "" doc = REXML::Document.new data doc.elements.each('//Placemark[1]/address') do |element| address = element.text end if address parts = address.split(/[,s*]/) result[:city] = parts[0] result[:state] = parts[2] result[:zip] = parts[3] end result end
以上是关于通过传递Zipcode,从Google地理编码服务中检索城市州和邮政信息的主要内容,如果未能解决你的问题,请参考以下文章