From b53160dc1ee2b44599a8576acb5f54dea7c26d1f Mon Sep 17 00:00:00 2001 From: Cellie Date: Mon, 15 Sep 2025 12:45:21 +0200 Subject: [PATCH] Clamp latitude to 85 degrees --- README.md | 4 ++-- src/OpenStreetMap-esp32.cpp | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index e1454d7..931a39e 100644 --- a/README.md +++ b/README.md @@ -99,11 +99,11 @@ bool fetchMap(LGFX_Sprite &map, double longitude, double latitude, uint8_t zoom, ``` - Overflowing `longitude` are wrapped and normalized to +-180°. -- Overflowing `latitude` are clamped to +-90°. +- Overflowing `latitude` are clamped to +-85°. - Valid range for the `zoom` level is from `getMinZoom()` to `getMaxZoom()`. - `timeoutMS` can be used to throttle the amount of downloaded tiles per call. Setting it to anything other than `0` sets a timeout. Sane values start around ~100ms. -**Note:** No more tiles will be downloaded after the timeout expires, but tiles that are downloading will be finished. +**Note:** No more tile downloads will be started after the timeout expires, but tiles that are downloading will be finished. **Note:** You might end up with missing map tiles. Or no map at all if you set the timeout too short. ### Free the psram memory used by the tile cache diff --git a/src/OpenStreetMap-esp32.cpp b/src/OpenStreetMap-esp32.cpp index 9241a11..17cbbab 100644 --- a/src/OpenStreetMap-esp32.cpp +++ b/src/OpenStreetMap-esp32.cpp @@ -325,8 +325,13 @@ bool OpenStreetMap::fetchMap(LGFX_Sprite &mapSprite, double longitude, double la return false; } + // Web Mercator projection only supports latitudes up to ~85.0511°. + // See https://en.wikipedia.org/wiki/Web_Mercator_projection#Formulas + // We use 85.0° as a safe and simple boundary. + constexpr double MAX_MERCATOR_LAT = 85.0; + longitude = fmod(longitude + 180.0, 360.0) - 180.0; - latitude = std::clamp(latitude, -90.0, 90.0); + latitude = std::clamp(latitude, -MAX_MERCATOR_LAT, MAX_MERCATOR_LAT); tileList requiredTiles; computeRequiredTiles(longitude, latitude, zoom, requiredTiles);