Mapbox Static Images API – Achieving Perfect Edges for Tile Positioning in Mapbox Static Images API

mapboxmapbox-studio

I'm working on a Python project that builds large hi-res images using tiles retrieved from the Mapbox static images API using customized styles designed in Mapbox studio.
https://docs.mapbox.com/api/maps/static-images/
(updated with correct link)

At the moment I have a proof of concept that works well at z15.5 but it won't work at other zoom levels without a good bit of work. I'm thinking there's a better/proper/elegant way to handle tile positioning.

Any suggestions on how to calculate the lat/lon for a second tile that aligns seamlessly with the first one? Longitude is easy enough, since the difference in distance between tiles stays the same every time. It's latitude that has the fun factor, since it changes for each tile.

I've tried using QGIS to export a large image but it didn't perform very well and pummeled the API usage.

Best Answer

After using Mercantile I got a better understanding of navigating the map grid. In the end I'm not using it in my project but it was a good hands on learning tool.

Basically, the step to the next tile needs to be scaled. This is because the static images API can return larger images that cover larger areas than the usual 512px grid tile. This turns out to be very simple. Instead of just going to the next tile over on the grid you need to go to the position that is requested_image_size / 512 away. So, a 1024px static images response will join seamlessly with one that is 2 grid tiles away, or 2.5 for a 1280px image.

I'm using this to generate images that are used for print so I'm not aiming for a fast web app. The standard grid tiles are perfect for interactive stuff. For my purposes this approach results in a faster final image.

Performance notes for a final image that's 10240px square:

  • 64 requests for 1280px images: 79 seconds to complete
  • 100 requests for 1024px images: 103 seconds to complete
  • 400 requests for 512px images: 208 seconds to complete

This only works starting at z11 for 1024px images and z12 for 1280px. The grid needs enough tiles to accommodate larger sizes. Zoom levels below these thresholds will not join seamlessly.

Zoom levels below z11 need to be done with 512px tiles so I also have things setup to use the Static Tiles API for this scenario and maintain API usage cost efficiency at that tile size.

Related Question