使用HERE API获取流量数据时,无法获取目标城市XYZ坐标求助
Hey Damien, no need to apologize at all—this is a super common point of confusion when getting started with HERE's tile-based traffic APIs! Let me walk you through exactly how to turn a city name into the XYZ coordinates you need.
Step 1: Convert City Name to Latitude/Longitude
First, you’ll need to get the geographic center (or full boundary) of your target city using HERE’s Geocoding API. This tool takes plaintext location names (like "Paris, France" or "Toronto, Canada") and returns precise geographic coordinates.
A basic request structure (replace YOUR_API_KEY with your actual API key) looks like this:
GET /geocode?q=Madrid,Spain&apiKey=YOUR_API_KEY
In the response, look for the DisplayPosition object—it will give you the city’s center latitude and longitude. If you need to cover the entire city (not just a single tile), check the MapView section which includes the north/south/east/west bounds of the urban area.
Step 2: Convert Lat/Lng to XYZ Tile Coordinates
HERE uses the standard Web Mercator (EPSG:3857) tile system, so you can calculate XYZ using these straightforward formulas (you’ll need to pick a zoom level—HERE Traffic Flow API typically supports zoom levels 10–18, depending on the region):
- Convert latitude to radians:
lat_rad = latitude * Math.PI / 180 - Calculate the tile Y coordinate:
y = Math.floor((1 - Math.log(Math.tan(lat_rad) + 1 / Math.cos(lat_rad)) / Math.PI) / 2 * Math.pow(2, zoom)) - Calculate the tile X coordinate:
x = Math.floor((longitude + 180) / 360 * Math.pow(2, zoom))
If you don’t want to code this manually, most mapping libraries (like Leaflet or OpenLayers) have built-in functions to handle this conversion automatically.
Bonus: Covering an Entire City
If your target city spans multiple tiles (which most do at higher zoom levels), use the bounding box from the Geocoding API response to calculate all XYZ tiles within that range. Simply convert the west/east and south/north bounds to tile coordinates, then iterate over all x and y values in between to get every tile that covers the city.
That should give you everything you need to pull traffic flow data successfully. Let me know if you hit any snags along the way!
内容的提问来源于stack exchange,提问作者Damien

