12
16

More than 5 years have passed since last update.

【C++】 緯度経度より距離を求める

Posted at

はじめに

上記のサイトを参考というか、このサイトではPHPで書かれているのをC++に書き換えてみました。では、どうぞ↓

ソースコード

distanceMeasurement.cpp
#include <iostream>
#include <math.h>

#define rad2deg(a) ((a)/M_PI * 180.0) /* rad を deg に換算するマクロ関数 */
#define deg2rad(a) ((a)/180.0 * M_PI) /* deg を rad に換算するマクロ関数 */

using namespace std;

typedef struct{
    char positionName[120];
    double latitude;
    double longitude;
}coordinate;

int main(){
    double earth_r = 6378.137;
    double laRe,loRe,NSD,EWD,distance;
    coordinate A;
    coordinate B;
    cout<<"1つ目の場所についての情報を入れてください。"<<endl;
    cout<<"地名:";
    cin>>A.positionName;
    cout<<"緯度:";
    cin>>A.latitude;
    cout<<"経度:";
    cin>>A.longitude;
    cout<<"2つ目の場所についての情報を入れてください。"<<endl;
    cout<<"地名:";
    cin>>B.positionName;
    cout<<"緯度:";
    cin>>B.latitude;
    cout<<"経度:";
    cin>>B.longitude;
    laRe = deg2rad(B.latitude - A.latitude);
    loRe = deg2rad(B.longitude - A.longitude);
    NSD = earth_r*laRe;
    EWD = cos(deg2rad(A.latitude))*earth_r*loRe;
    distance = sqrt(pow(NSD,2)+pow(EWD,2));
    cout<<A.positionName<<"と"<<B.positionName<<"の距離は"<<distance<<"km"<<endl;
}

実行結果

1つ目の場所についての情報を入れてください。
地名:大阪駅
緯度:34.702113
経度:135.494807
2つ目の場所についての情報を入れてください。
地名:東京駅
緯度:35.681541
経度:139.767103
大阪駅と東京駅の距離は405.91km

補足

座標はGoogleMapを利用して取得しました。
今回取得した距離はおおよその直線距離で実際の距離とは異なります。
精度を高めるにはもっと複雑な計算が必要ですが今回は簡易な方法で行いました。

12
16
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
16