Skip to content

Instantly share code, notes, and snippets.

@Shtille
Created July 13, 2016 14:41
Show Gist options
  • Save Shtille/9311589c2b3d494db279a2036a4897d9 to your computer and use it in GitHub Desktop.
Save Shtille/9311589c2b3d494db279a2036a4897d9 to your computer and use it in GitHub Desktop.
Test program calculating number of tiles for a selected region
#include <iostream>
#include <cmath>
const int kMaxLod = 20;
const double GetMaxLatitude() { return 90.0; }
const double GetMinLatitude() { return -90.0; }
const double GetMaxLongitude() { return 180.0; }
const double GetMinLongitude() { return -180.0; }
template <typename T>
T Clip(T x, T min_x, T max_x)
{
return std::min(std::max(x, min_x), max_x);
}
int MapSize(int level_of_detail)
{
return 256 << level_of_detail;
}
void LatLongToPixelXY(double latitude, double longitude, int level_of_detail,
int& pixel_x, int& pixel_y)
{
latitude = Clip(latitude, GetMinLatitude(), GetMaxLatitude());
longitude = Clip(longitude, GetMinLongitude(), GetMaxLongitude());
double x = (longitude + 180.0) / 360.0;
double sin_latitude = sin(latitude * M_PI / 180.0);
double y = 0.5 - log((1.0 + sin_latitude) / (1.0 - sin_latitude)) / (4.0 * M_PI);
int map_size = MapSize(level_of_detail);
pixel_x = Clip((int)(x * (double)map_size + 0.5), 0, map_size - 1);
pixel_y = Clip((int)(y * (double)map_size + 0.5), 0, map_size - 1);
}
void LatLongToTileXY(double latitude, double longitude, int level_of_detail,
int& tile_x, int& tile_y)
{
LatLongToPixelXY(latitude, longitude, level_of_detail, tile_x, tile_y);
tile_x /= 256;
tile_y /= 256;
}
unsigned int GetEstimatedSize(double upper_latitude,
double left_longitude,
double lower_latitude,
double right_longitude)
{
// We will simply count how many tiles do we need to download
unsigned int tiles_count = 0;
int max_lod = kMaxLod;
// Compute tile keys for bound rect
int left, right, top, bottom;
LatLongToTileXY(upper_latitude,
left_longitude,
max_lod,
left, top);
LatLongToTileXY(lower_latitude,
right_longitude,
max_lod,
right, bottom);
for (int z = max_lod; z >= 0; --z)
{
int tiles_per_side = 1 << z;
int num_x = right - left + 1;
bool has_break = (num_x <= 0);
if (has_break)
num_x += tiles_per_side;
for (int y = top; y <= bottom; ++y)
{
for (int i = 0; i < num_x; ++i)
{
++tiles_count;
}
}
top >>= 1;
bottom >>= 1;
left >>= 1;
right >>= 1;
}
return tiles_count;
}
int main()
{
unsigned int size = GetEstimatedSize(40.0, -113.0, 38.0, -110.0);
std::cout << "tiles count = " << size << "\n";
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment