Skip to content

Instantly share code, notes, and snippets.

@dbrockman
Created February 11, 2014 08:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dbrockman/8931435 to your computer and use it in GitHub Desktop.
Save dbrockman/8931435 to your computer and use it in GitHub Desktop.
How to count the number of tiles in a map region with min/max zoom level
- (NSUInteger)countTilesInRegionSouthWest:(CLLocationCoordinate2D)southWest
northEast:(CLLocationCoordinate2D)northEast
minZoom:(int)minZoom
maxZoom:(int)maxZoom
{
double minLat = southWest.latitude;
double maxLat = northEast.latitude;
double minLon = southWest.longitude;
double maxLon = northEast.longitude;
if (minZoom > maxZoom || maxLat <= minLat || maxLon <= minLon) {
return 0;
}
int n, xMin, yMax, xMax, yMin;
NSUInteger totalTiles = 0;
for (int zoom = minZoom; zoom <= maxZoom; zoom++) {
n = pow(2.0, zoom);
xMin = floor(((minLon + 180.0) / 360.0) * n);
yMax = floor((1.0 - (log(tan(minLat * M_PI / 180.0) + 1.0 / cos(minLat * M_PI / 180.0)) / M_PI)) / 2.0 * n);
xMax = floor(((maxLon + 180.0) / 360.0) * n);
yMin = floor((1.0 - (log(tan(maxLat * M_PI / 180.0) + 1.0 / cos(maxLat * M_PI / 180.0)) / M_PI)) / 2.0 * n);
totalTiles += (xMax + 1 - xMin) * (yMax + 1 - yMin);
}
return totalTiles;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment