Incorrect orientation on Android in landscape mode

I’m trying to get the correct orientation in my web application. On iOS, event.webkitCompassHeading works very well, but on Android, it is either undefined or returns NaN.

After searching on Google, I found this type of code:

headingMio = Math.round(roundedAlpha + 85) % 360;
if (headingMio < 0) {
    headingMio += 360; 
}

But it doesn’t work in landscape mode. How can I fix this?There is my code:

let lastHeading = null;
    let threshold = 5;
    let threshold2 = 15;

    document.addEventListener('click', async function requestOrientationPermission() {
        if (typeof DeviceOrientationEvent.requestPermission === 'function') {
            try {
                const permissionState = await DeviceOrientationEvent.requestPermission();
                if (permissionState === 'granted') {
                    console.log("Permesso concesso per l'orientamento del dispositivo.");
                    // Aggiungi l'event listener per l'orientamento
                    window.addEventListener('deviceorientation', handleDeviceOrientation);
                    document.removeEventListener('click', requestOrientationPermission);
                } else {
                    console.log("Permesso negato per l'orientamento del dispositivo.");
                }
            } catch (error) {
                console.error('Errore nel richiedere il permesso:', error);
            }
        } else {
            window.addEventListener('deviceorientation', handleDeviceOrientation);
        }
    });

    // Funzione che gestisce i dati di orientamento del dispositivo
    function handleDeviceOrientation(event) {
        roundedAlpha = Math.round(360 - event.alpha);
        roundedBeta = Math.round(event.beta);
        roundedGamma = Math.round(event.gamma);

        headingMio = Math.round(event.webkitCompassHeading);

        if (headingMio === undefined || isNaN(headingMio)) {
            if (roundedBeta > 80 && roundedBeta < 105) {
               //not worikng landscape
            } else {
                headingMio = Math.round(roundedAlpha + 85) % 360;
                if (headingMio < 0) {
                    headingMio += 360; 
                }
            }
        }

        const c = document.getElementById("orientation");

        if (lastHeading === null || Math.abs(headingMio - lastHeading) > threshold) {
            lastHeading = headingMio;

            c.innerText = `Alpha (Z): ${roundedAlpha}, Beta (X - Inclinazione avanti/indietro): ${roundedBeta}, Gamma (Y - Inclinazione laterale): ${roundedGamma}, Nord Magnetico (Compass Heading): ${headingMio}`;

            if (!isNaN(headingMio)) {
                map.setHeading(parseInt(headingMio, 10));
            }
        }

        c.innerText = `Alpha (Z): ${roundedAlpha}, Beta (X - Inclinazione avanti/indietro): ${roundedBeta}, Gamma (Y - Inclinazione laterale): ${roundedGamma}, Nord Magnetico (Compass Heading): ${headingMio}`;

    }