在做地图相关开发时候,绕不开不同坐标系间的转化,因此我根据查阅相关资料后将不同坐标系间的转换封装到一个GeoTranslate类中,该类转换函数不仅支持Qt/C++调用,同时可在QML中直接调用,配合上QML/Map很方便,我将该类做了个Demo,方便使用者使用,效果如图:
在QML的地图Map中使用高德的路径规划的效果:
使用方法为将 GeoTranslate类添加到工程中,调用转换函数即可
geotranslate.h:
#ifndef GEOTRANSLATE_H
#define GEOTRANSLATE_H
#include <QtMath>
#include <QObject>
#include <QGeoCoordinate>
class GeoTranslate : public QObject
{
public:
explicit GeoTranslate(QObject *parent = nullptr);
static constexpr double pi = 3.14159265358979323846;
static constexpr double a = 6378245.0;
static constexpr double ee = 0.00669342162296594323;
Q_INVOKABLE static QGeoCoordinate wgs84ToGcj02(QGeoCoordinate coordinate);
Q_INVOKABLE static QGeoCoordinate gcj02ToWgs84(QGeoCoordinate coordinate);
Q_INVOKABLE static QGeoCoordinate wgs84ToGcj02(double lat,double lon);
Q_INVOKABLE static QGeoCoordinate gcj02ToWgs84(double lat,double lon);
Q_INVOKABLE static QGeoCoordinate gcj02ToBd09(QGeoCoordinate coordinate);
Q_INVOKABLE static QGeoCoordinate bd09ToGcj02(QGeoCoordinate coordinate);
Q_INVOKABLE static QGeoCoordinate gcj02ToBd09(double gg_lat, double gg_lon);
Q_INVOKABLE static QGeoCoordinate bd09ToGcj02(double bd_lat,double bd_lon);
private:
static double transformLat(double x,double y);
static double transformLon(double x,double y);
static bool outOfChina(double lat,double lon);
static QGeoCoordinate transform(double lat,double lon);
};
#endif // GEOTRANSLATE_H
调用方法:
void Widget::on_pushButton_1_clicked()
{
QGeoCoordinate wgs(ui->lineEditLa_1->text().toDouble(),ui->lineEditLo_1->text().toDouble());
QGeoCoordinate gcj02 = GeoTranslate::wgs84ToGcj02(wgs);
ui->lineEditLa_2->setText(QString::number(gcj02.latitude()));
ui->lineEditLo_2->setText(QString::number(gcj02.longitude()));
}
void Widget::on_pushButton_2_clicked()
{
QGeoCoordinate gcj02(ui->lineEditLa_3->text().toDouble(),ui->lineEditLo_3->text().toDouble());
QGeoCoordinate wgs = GeoTranslate::gcj02ToWgs84(gcj02);
ui->lineEditLa_4->setText(QString::number(wgs.latitude()));
ui->lineEditLo_4->setText(QString::number(wgs.longitude()));
}
void Widget::on_pushButton_3_clicked()
{
QGeoCoordinate gcj02(ui->lineEditLa_5->text().toDouble(),ui->lineEditLo_5->text().toDouble());
QGeoCoordinate bd09 = GeoTranslate::gcj02ToBd09(gcj02);
ui->lineEditLa_6->setText(QString::number(bd09.latitude()));
ui->lineEditLo_6->setText(QString::number(bd09.longitude()));
}
void Widget::on_pushButton_4_clicked()
{
QGeoCoordinate bd09(ui->lineEditLa_7->text().toDouble(),ui->lineEditLo_7->text().toDouble());
QGeoCoordinate gcj02 = GeoTranslate::bd09ToGcj02(bd09);
ui->lineEditLa_8->setText(QString::number(gcj02.latitude()));
ui->lineEditLo_8->setText(QString::number(gcj02.longitude()));
}
完整Demo(包含geotranslate.h / geotranslate.cpp)我上传到CSDN库中,自行下载即可运行: