最近项目中用到 了GPS模块,GPS报文解析后给地图,都定位到 湖里面了!
查资料知道要 坐标转换,找了很多资料都没有关于C语言的;
自己写一个吧!
实测定位精度:2m
先来张效果图:
//==============================================================
bool outOfChina(double lon, double lat)
{
if ((lon < 72.004 || lon > 137.8347) && (lat < 0.8293 || lat > 55.8271))
{
return true;
}
else
{
return false;
}
}
double transformLon(double x, double y)
{
static double pi = 3.14159265358979324;
double ret =
300.0 +
x +
2.0 * y +
0.1 * x * x +
0.1 * x * y +
0.1 * sqrt(abs(x));
ret +=
((20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0) / 3.0;
ret +=
((20.0 * sin(x * pi) + 40.0 * sin((x / 3.0) * pi)) * 2.0) / 3.0;
ret +=
((150.0 * sin((x / 12.0) * pi) + 300.0 * sin((x / 30.0) * pi)) * 2.0) / 3.0;
return ret;
}
double transformLat(double x, double y)
{
static double pi = 3.14159265358979324;
double ret =
-100.0 +
2.0 * x +
3.0 * y +
0.2 * y * y +
0.1 * x * y +
0.2 * sqrt(abs(x));
ret +=
((20.0 * sin(6.0 * x * pi) + 20.0 * sin(2.0 * x * pi)) * 2.0) /3.0;
ret +=
((20.0 * sin(y * pi) + 40.0 * sin((y / 3.0) * pi)) * 2.0) / 3.0;
ret +=
((160.0 * sin((y / 12.0) * pi) + 320 * sin((y * pi) / 30.0)) * 2.0)/ 3.0;
return ret;
}
// 地球坐标系(WGS-84)转火星坐标系(GCJ) 转 火星坐标转百度坐标:
void transformWGS84ToGCJ02ToBD09(GPS *pGPS )
{
double wgLat=pGPS->trueLatitude;
double wgLon=pGPS->trueLongitude;
double mars_pointlat;
double mars_pointlng;
static double pi = 3.14159265358979324;
static double ee = 0.00669342162296594323;
static double x_pi = (3.14159265358979324 * 3000.0) / 180.0;
static double a = 6378245.0; // a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
if (outOfChina(wgLon, wgLat)) {
mars_pointlat = wgLat;
mars_pointlng = wgLon;
return;
}
double dLat = transformLat(wgLon - 105.0, wgLat - 35.0);
double dLon = transformLon(wgLon - 105.0, wgLat - 35.0);
double radLat = (wgLat / 180.0) * pi;
double magic = sin(radLat);
magic = 1 - ee * magic * magic;
double sqrtMagic = sqrt(magic);
dLat = (dLat * 180.0) / (((a * (1 - ee)) / (magic * sqrtMagic)) * pi);
dLon = (dLon * 180.0) / ((a / sqrtMagic) * cos(radLat) * pi);
mars_pointlat = wgLat + dLat;
mars_pointlng = wgLon + dLon;
//=============================================
double x2 = mars_pointlng * mars_pointlng;
double y2 = mars_pointlat * mars_pointlat;
double z = sqrt(x2 + y2) + 0.00002 * sin(mars_pointlat * x_pi);
double theta = atan2(mars_pointlat, mars_pointlng) + 0.000003 * cos(mars_pointlng * x_pi);
pGPS->BD09Latitude = z * sin(theta) + 0.006;
pGPS->BD09Longitude = z * cos(theta) + 0.0065;
}