<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> <div id="navbar-iframe-container"></div> <script type="text/javascript" src="https://apis.google.com/js/platform.js"></script> <script type="text/javascript"> gapi.load("gapi.iframes:gapi.iframes.style.bubble", function() { if (gapi.iframes && gapi.iframes.getContext) { gapi.iframes.getContext().openChild({ url: 'https://www.blogger.com/navbar.g?targetBlogID\x3d4684235500622716427\x26blogName\x3dCaiwangqin\x27s+blog\x26publishMode\x3dPUBLISH_MODE_HOSTED\x26navbarType\x3dBLUE\x26layoutType\x3dCLASSIC\x26searchRoot\x3dhttp://blog.caiwangqin.com/search\x26blogLocale\x3dzh_CN\x26v\x3d2\x26homepageUrl\x3dhttp://blog.caiwangqin.com/\x26vt\x3d3393395200455623441', where: document.getElementById("navbar-iframe-container"), id: "navbar-iframe", messageHandlersFilter: gapi.iframes.CROSS_ORIGIN_IFRAMES_FILTER, messageHandlers: { 'blogger-ping': function() {} } }); } }); </script>

Caiwangqin's blog

Focus on Life, Cloud Service, Smart Hardware, Architecture, 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 Caiwangqin, 00:38

0 Comments:

发表评论

订阅 博文评论 [Atom]

<< 主页