<body><script type="text/javascript"> function setAttributeOnload(object, attribute, val) { if(window.addEventListener) { window.addEventListener('load', function(){ object[attribute] = val; }, false); } else { window.attachEvent('onload', function(){ object[attribute] = val; }); } } </script> <iframe src="http://www.blogger.com/navbar.g?targetBlogID=4684235500622716427&amp;blogName=Caiwangqin&#39;s+blog&amp;publishMode=PUBLISH_MODE_HOSTED&amp;navbarType=BLUE&amp;layoutType=CLASSIC&amp;searchRoot=http://blog.caiwangqin.com/search&amp;blogLocale=zh_CN&amp;v=1&amp;homepageUrl=http://blog.caiwangqin.com/&amp;vt=3393395200455623441" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" height="30px" width="100%" id="navbar-iframe" allowtransparency="true" title="Blogger 导航和搜索"></iframe> <div></div>

Caiwangqin's blog

Focus on Web2.0, Business, Architecture, Agile, Technic and beyond…

Ruby 代码片断-计算两点之间的距离

2006年9月15日 星期五

根据两点的经纬度计算两点之间的距离:


# converts degrees to radians

# params: degree to convert

# returns: answer in radians

def self.convert_to_radians(degree_num)

radians = degree_num.to_f * Math::PI/180

end


# calculate the distance between two zips using the great circle ormula

# params: orig latitude, orig longitude, to latitude, to longitude

# returns: distance in miles

def self.calc_distance_between(orig_lat, orig_long, to_lat, to_long)

# find the delta’s of latitude and longitude

delta_lat = to_lat - orig_lat

delta_long = to_long - orig_long


# compute the sin^2(delta_*/2)

computed_lat = Math.sin(delta_lat/2)

computed_lat = computed_lat * computed_lat

computed_long = Math.sin(delta_long/2)

computed_long = computed_long * computed_long


# find the inner part of the great circle

inner_equation = computed_lat + Math.cos(orig_lat) * Math.cos(to_lat) * computed_long

# find the outer part of the great circle

outer_equation = 2 * Math.atan2(Math.sqrt(inner_equation),Math.sqrt(1-inner_equation))

# find the distance in miles

distance = 3956 * outer_equation

end


标签:

posted by Jesse Cai, 上午12:38

0 Comments:

发表评论

订阅 帖子评论 [Atom]

<< 主页