【C++】緯度経度からquadKey生成

2019年4月10日

pythonとかRubyとかC#では似たようなソース見つけたけどC++でquadkeyを生成するソールはあまりなかったので置いておく。

pythonみたいにモジュールとかないので計算で出してみる。
includeの<>が全角なのは半角に置き換えてください。



#include <math.h>

std::string latlon_to_quadkey(double lat, double lon, int zoom_level)
{
    // 緯度経度からタイル座標に変換
    double x = (lon / 180 + 1) * std::pow(2, zoom_level) / 2;
    int xtile = int(x);
    double y = ((-log(tan((45 + lat / 2) * M_PI / 180)) + M_PI) * std::pow(2, zoom_level) / (2 * M_PI));
	int ytile = int(y);

    // タイル座標からQuadkeyに変換
    std::string quadKey;
    for (int i = zoom_level; i > 0; i--) {
        int digit = 0;
        int mask = 1 << (i-1);
        if ((xtile & mask) != 0) {
            digit++;
        }
        if ((ytile & mask) != 0) {
            digit++;
            digit++;
        }
        quadKey += std::to_string(digit);
    }
    return quadKey;
}

std::string main()
{
    double lat = 34.704444;
    double lon = 137.549228;
    int zoom_level = 20;
    str::string quadkey = latlon_to_quadkey(lat, lon, zoom_level);

    return quadkey;
}

未分類

Posted by cttr