Map extent issue

Hello,
I’m trying to adjust the map extent dynamically based on the size of the map, to make sure the extent fits properly and respects the aspect ratio.
The problem is that map.width only gives me values like "100%" or "800px", which I can’t use directly to calculate the actual dimensions.
The only workaround I found is to use JS to read the map size:

val mapId = map.id.orElse(“map”)
map.element.executeJs(
“”"
const el = document.getElementById(’$mapId’);
if (el) {
return [el.clientWidth, el.clientHeight];
} else {
return [0, 0];
}
“”".trimIndent()
).then { }
However, because this call is asynchronous, setting map.mapView.extent or using zoomToExtent(...) right after doesn’t reliably update the map — the extent just doesn’t apply correctly.
Do you have a recommended way to handle this ?
Thanks!

Hello Aycha!

Could you clarify, do you set extent in pixels or you dynamically calculate the extent considering pixels?

Please note that extent takes values according to CRS (coordinate reference system). For instance, in EPSG:3857 it is meters, in EPSG:4326 it is degree (latitude and longitude).

Thanks for your reply.
To clarify, I’m not setting the extent in pixels, I’m calculating it dynamically , then adjusting it to fit the map container size.
1- Get the extent from GeoServer :
val allExtents = map.layers
.filterIsInstance()
.mapNotNull { layer →
if (layer.id != “tiles” && layer.visible)
getLayerExtentFromGeoserver(layer)
else null
}
val maxLayersExtent = Extent(
allExtents.minOf { it.minX },
allExtents.minOf { it.minY },
allExtents.maxOf { it.maxX },
allExtents.maxOf { it.maxY }
)
2. Get the map’s actual pixel dimensions: I use JS to get clientWidth and clientHeight:
val mapId = map.id.orElse(“map”)
map.element.executeJs("""
const el = document.getElementById(’$mapId’);
if (el) {
return [el.clientWidth, el.clientHeight];
} else {
return [0, 0];
}
“”".trimIndent()).then { jsResult →
val width = jsResult.getNumber(0)
val height = jsResult.getNumber(1)
val aspectRatio = width / height

val adjustedExtent = adjustExtentToAspectRatio(maxLayersExtent, aspectRatio)

map.mapView.extent = adjustedExtent
map.zoomToExtent(adjustedExtent)

}
Even after setting map.mapView.extent and calling zoomToExtent(…), the extent is not applied correctly,