0

I am using TomTom API to retrieve Traffic Data in PBF format

example /traffic/map/{versionNumber}/tile/flow/{style}/{zoom}/{x}/{y}.{format}

api call tried https://api.tomtom.com/traffic/map/4/tile/flow/relative0/12/1207/1539.pbf?tileSize=256&key=*****

I have only just realised that the x,y coordinates are the x and y coordinates corresponding to the tile's position on the grid for that zoom level, and not geographical.

To overcome this, I found the following JavaScript code to convert from z/x/y to lat/long

function tileZXYToLatLon(zoomLevel, x, y) {
  const MIN_ZOOM_LEVEL = 0
  const MAX_ZOOM_LEVEL = 22

  if (
    zoomLevel == undefined ||
    isNaN(zoomLevel) ||
    zoomLevel < MIN_ZOOM_LEVEL ||
    zoomLevel > MAX_ZOOM_LEVEL
  ) {
    throw new Error(
      "Zoom level value is out of range [" +
        MIN_ZOOM_LEVEL.toString() +
        "," +
        MAX_ZOOM_LEVEL.toString() +
        "]"
    )
  }

  let z = Math.trunc(zoomLevel)
  let minXY = 0
  let maxXY = Math.pow(2, z) - 1

  if (x == undefined || isNaN(x) || x < minXY || x > maxXY) {
    throw new Error(
      "Tile x value is out of range [" +
        minXY.toString() +
        "," +
        maxXY.toString() +
        "]"
    )
  }

  if (y == undefined || isNaN(y) || y < minXY || y > maxXY) {
    throw new Error(
      "Tile y value is out of range [" +
        minXY.toString() +
        "," +
        maxXY.toString() +
        "]"
    )
  }

  let lon = (x / Math.pow(2, z)) * 360.0 - 180.0

  let n = Math.PI - (2.0 * Math.PI * y) / Math.pow(2, z)
  let lat = (180.0 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)))

  return lat.toString() + "/" + lon.toString()
}

However, I am not very competent in JavaScript and would much rather use Python. Can anyone advise me how I can replicate this script into Pythonic format?

  • Does this answer your question: [Convert xyz coordinate of a tile to longitude/latitude](https://stackoverflow.com/questions/32046601/convert-xyz-coordinate-of-a-tile-to-longitude-latitude) or [this](https://stackoverflow.com/questions/62800466/transform-x-y-pixel-values-into-lat-and-long) ? – Maurice Meyer Jan 25 '23 at 13:43

0 Answers0