Windows XP 平板电脑版嵌入式Visual C++ 7.1Visual C++ 8.0Windows VistaVisual C++ 7.0Windows 2003Windows 2000Visual C++ 6.0Windows XP初学者中级WindowsC++
使用 c++ 通过经纬度计算距离
正如标题所示。
Title: Distance using Longitude and latitude Author: Chhibs Email: annum0@gmail.com Member ID: 12345 Language: C++ Platform: Windows, Linux Technology: WiMAX,WiFi, WDM Level: Intermediate, Advanced Description: A quick code dump for haversine formula Section Language c++ SubSection Howto
引言
我在网站上看到过使用 C# 等计算距离的代码,使用的是海弗森公式,但没有使用 C++ 的,所以这里提供一段仅用于此的代码。
背景(可选)
我看到一些文章使用海弗森公式进行距离计算,但使用的是 .Net。由于我使用 C++ 编程(除非真的需要,否则不用 .Net),所以我将其移植到 C++,以下是代码。
来自数学论坛
http://mathforum.org/library/drmath/view/51879.html
Presuming a spherical Earth with radius R (see below), and that the locations of the two points in spherical coordinates (longitude and latitude) are lon1,lat1 and lon2,lat2, then the Haversine Formula (from R. W. Sinnott, "Virtues of the Haversine," Sky and Telescope, vol. 68, no. 2, 1984, p. 159): dlon = lon2 - lon1 dlat = lat2 - lat1 a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2 c = 2 * atan2(sqrt(a), sqrt(1-a)) d = R * c will give mathematically and computationally exact results. The intermediate result c is the great circle distance in radians. The great circle distance d will be in the same units as R.
使用代码
我只是发布一段我用于一个类的代码片段,它为我计算距离。// Sample format for latitide and longitudes // double lat1=45.54243333333333,lat2=45.53722222,long1=-122.96045277777778,long2=-122.9630556; // Below is the main code #include <cmath> double PI = 4.0*atan(1.0); //main code inside the class double dlat1=lat1*(PI/180); double dlong1=long1*(PI/180); double dlat2=lat2*(PI/180); double dlong2=long2*(PI/180); double dLong=dlong1-dlong2; double dLat=dlat1-dlat2; double aHarv= pow(sin(dLat/2.0),2.0)+cos(dlat1)*cos(dlat2)*pow(sin(dLong/2),2); double cHarv=2*atan2(sqrt(aHarv),sqrt(1.0-aHarv)); //earth's radius from wikipedia varies between 6,356.750 km — 6,378.135 km (˜3,949.901 — 3,963.189 miles) //The IUGG value for the equatorial radius of the Earth is 6378.137 km (3963.19 mile) const double earth=3963.19;//I am doing miles, just change this to radius in kilometers to get distances in km double distance=earth*cHarv;