Im trying to automate importing png files in the qgis build in python console with the following code:
from qgis.core import QgsRasterLayer, QgsProject, QgsCoordinateReferenceSystem, QgsRectangle
import math
# Function to calculate the geographic bounds of a tile in EPSG:3857
def tile_bounds(x, y, zoom):
tile_size = 256
initial_resolution = 2 * math.pi * 6378137 / tile_size
origin_shift = 2 * math.pi * 6378137 / 2.0
zoom_level = zoom
resolution = initial_resolution / (2**zoom_level)
min_lon = x * tile_size * resolution - origin_shift
max_lon = (x + 1) * tile_size * resolution - origin_shift
min_lat = origin_shift - (y + 1) * tile_size * resolution
max_lat = origin_shift - y * tile_size * resolution
return [min_lon, min_lat, max_lon, max_lat]
# Tile coordinates and zoom level from URL
x = 56
y = 24
zoom = 6
# Specify the URL of the PNG image
url = "https://api.inaturalist.org/v1/taxon_ranges/1402613/6/56/24.png?color=green"
# Create a new raster layer from the URL
raster_layer = QgsRasterLayer(url, "Inaturalist Taxon Range")
# Check if the layer is valid
if not raster_layer.isValid():
print("Layer failed to load!")
else:
# Specify the desired CRS as EPSG:3857
crs = QgsCoordinateReferenceSystem("EPSG:3857")
# Assign the CRS to the raster layer
raster_layer.setCrs(crs)
# Calculate the bounds of the tile and set the layer's extent
bounds = tile_bounds(x, y, zoom)
raster_layer_extent = QgsRectangle(bounds[0], bounds[1], bounds[2], bounds[3])
raster_layer.setExtent(raster_layer_extent)
# Add the layer to the map
QgsProject.instance().addMapLayer(raster_layer)
print("Layer added successfully!")
It correctly zooms to the right area, but my image doesnt appear.
After a bit of testing I figured out the image itself remains stuck at 0,0. I just cannot figure out why its not moving, nor stretching to the desired size