This worked for me:
It's a React.js implementation.
const lon2tile = (lon: any, zoom: any) => {
return Math.floor(((lon + 180) / 360) * Math.pow(2, zoom))
}
const lat2tile = (lat: any, zoom: any) => {
return Math.floor(
((1 -
Math.log(Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)) / Math.PI) /
2) *
Math.pow(2, zoom)
)
}
const zoomToUse = Math.floor(mapZoom)
const currentX = mapBounds?.ne && lon2tile((mapBounds.ne as TLngLatLike).lng, zoomToUse)
const currentY = mapBounds?.sw && lat2tile(Math.abs((mapBounds.sw as TLngLatLike).lat), zoomToUse)
const currentZ = zoomToUse
And this is how I call the tiles API to check first if valid tiles are returned for the current x, y, z:
let tilesURLWithCoordinates = tiles.replace("{z}", zoomToUse.toString())
tilesURLWithCoordinates = tilesURLWithCoordinates.replace("{x}", currentX.toString())
tilesURLWithCoordinates = tilesURLWithCoordinates.replace("{y}", currentY.toString())
const response = await fetch(tilesURLWithCoordinates, {
method: "GET",
})