天天看点

地图坐标转换C代码

WGS-84:是国际标准,GPS坐标(Google Earth使用、或者GPS模块)

GCJ-02(火星坐标):中国坐标偏移标准,Google Map、高德、腾讯使用

BD-09:百度坐标偏移标准,Baidu Map使用

/*
 pi: 圆周率。
 a: 卫星椭球坐标投影到平面地图坐标系的投影因子。
 ee: 椭球的偏心率。
 x_pi: 圆周率转换量。
 transformLat(double x, double y): 坐标转换方法。
 transformLon(double x, double y): 坐标转换方法。
 wgs2gcj(double lat, double lon, double* pLat, double* pLon): WGS坐标转换为GCJ坐标。
 gcj2bd(double lat, double lon, double* pLat, double* pLon): GCJ坐标转换为百度坐标。
*/

double pi = 3.14159265358979324;
double a = 6378245.0;
double ee = 0.00669342162296594323;
double x_pi = 3.14159265358979324 * 3000.0 / 180.0;

int wgs2bd(double lat, double lon, double* pLat, double* pLon) {
       double lat_ = 0.0, lon_ = 0.0;
       wgs2gcj(lat, lon, &lat_, &lon_);
       gcj2bd(lat_, lon_,  pLat, pLon);
       return 0;
}

int gcj2bd(double lat, double lon, double* pLat, double* pLon) {
       double x = lon, y = lat;
       double z = sqrt(x * x + y * y) + 0.00002 * sin(y * x_pi);
       double theta = atan2(y, x) + 0.000003 * cos(x * x_pi);
       *pLon = z * cos(theta) + 0.0065;
       *pLat = z * sin(theta) + 0.006;
       return 0;
}

int bd2gcj(double lat, double lon, double* pLat, double* pLon) {
       double x = lon - 0.0065, y = lat - 0.006;
       double z = sqrt(x * x + y * y) - 0.00002 * sin(y * x_pi);
       double theta = atan2(y, x) - 0.000003 * cos(x * x_pi);
       *pLon = z * cos(theta);
       *pLat = z * sin(theta);
       return 0;
}

int wgs2gcj(double lat, double lon, double* pLat, double* pLon) {
       double dLat = transformLat(lon - 105.0, lat - 35.0);
       double dLon = transformLon(lon - 105.0, lat - 35.0);
       double radLat = lat / 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);
       *pLat = lat + dLat;
       *pLon = lon + dLon;
       return 0;
}

double transformLat(double x, double y) {
       double ret = 0.0;
       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;
}

double transformLon(double x, double y) {
       double ret = 0.0;
       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;
}
           

继续阅读