Improving readbility of the javascript.

This commit is contained in:
Sergiotarxz 2023-11-20 21:21:50 +01:00
parent d6d827fe8d
commit f3f111060b
2 changed files with 98 additions and 82 deletions

View File

@ -1,15 +1,18 @@
import Map from "ol/Map";
import View from "ol/View";
import Projection from "ol/proj/Projection.js";
import Map from "ol/Map"
import View from "ol/View"
import Projection from "ol/proj/Projection.js"
import TileLayer from 'ol/layer/Tile'
import OSM from 'ol/source/OSM'
import * as olProj from "ol/proj";
import * as olProj from "ol/proj"
import Feature from 'ol/Feature'
import Point from 'ol/geom/Point'
export default class Conquer {
private conquerContainer: HTMLDivElement;
private map: Map;
private currentLongitude: number;
private currentLatitude: number;
private rotationOffset = 0;
private conquerContainer: HTMLDivElement
private map: Map
private currentLongitude: number
private currentLatitude: number
private rotationOffset = 0
private heading = 0
private disableSetRotationOffset = false
private conquerLogin: HTMLDivElement
@ -26,18 +29,19 @@ export default class Conquer {
private conquerRegisterRepeatPassword: HTMLInputElement
private conquerRegisterSubmit: HTMLButtonElement
private conquerRegisterError: HTMLParagraphElement
private alpha = 0;
private beta = 0;
private gamma = 0;
private currentPositionFeature: Feature | null
private alpha = 0
private beta = 0
private gamma = 0
static start() {
const conquerContainer = document.querySelector(".conquer-container");
const conquerContainer = document.querySelector(".conquer-container")
if (conquerContainer !== null) {
if (!(conquerContainer instanceof HTMLDivElement)) {
console.error(".conquer-container is not a div.");
return;
console.error(".conquer-container is not a div.")
return
}
const conquer = new Conquer(conquerContainer);
conquer.run();
const conquer = new Conquer(conquerContainer)
conquer.run()
}
}
setCenterDisplaced(lat: number, lon: number) {
@ -94,12 +98,12 @@ export default class Conquer {
this.conquerLoginSubmit.addEventListener('click', (event: Event) => {
event.preventDefault()
this.onLoginRequested()
});
})
}
async onLoginRequested(): Promise<void> {
const username = this.conquerLoginUsername.value;
const password = this.conquerLoginPassword.value;
const username = this.conquerLoginUsername.value
const password = this.conquerLoginPassword.value
const urlUser = new URL('/conquer/user/login', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port)
let responseJson
let status
@ -116,28 +120,28 @@ export default class Conquer {
} catch(e) {
console.error(e)
this.addNewLoginError('El servidor ha enviado datos inesperados.')
return;
return
}
if (status !== 200) {
this.addNewLoginError(responseJson.error)
return
}
this.unsetLoginAndRegisterErrors()
const isLogged = await this.isLogged();
const isLogged = await this.isLogged()
if (isLogged) {
await this.removeLoginRegisterCombo()
}
}
async goToRegister(): Promise<void> {
const isLogged = await this.isLogged();
const isLogged = await this.isLogged()
await this.removeLoginRegisterCombo()
if (!isLogged) {
this.conquerRegister.classList.remove('conquer-display-none')
}
}
async goToLogin(): Promise<void> {
const isLogged = await this.isLogged();
const isLogged = await this.isLogged()
await this.removeLoginRegisterCombo()
if (!isLogged) {
this.conquerLogin.classList.remove('conquer-display-none')
@ -221,7 +225,7 @@ export default class Conquer {
} catch(e) {
console.error(e)
this.addNewRegisterError('El servidor ha enviado datos inesperados.')
return;
return
}
if (status !== 200) {
this.addNewRegisterError(responseJson.error)
@ -251,27 +255,27 @@ export default class Conquer {
async run() {
this.fillConquerLogin()
this.fillConquerRegister()
const isLogged = await this.isLogged();
const isLogged = await this.isLogged()
if (!isLogged) {
this.conquerLogin.classList.remove('conquer-display-none')
}
const conquerContainer = this.conquerContainer;
const conquerContainer = this.conquerContainer
//layer.on('prerender', (evt) => {
// // return
// if (evt.context) {
// const context = evt.context as CanvasRenderingContext2D;
// context.filter = 'grayscale(80%) invert(100%) ';
// context.globalCompositeOperation = 'source-over';
// const context = evt.context as CanvasRenderingContext2D
// context.filter = 'grayscale(80%) invert(100%) '
// context.globalCompositeOperation = 'source-over'
// }
//});
//})
//layer.on('postrender', (evt) => {
// if (evt.context) {
// const context = evt.context as CanvasRenderingContext2D;
// context.filter = 'none';
// const context = evt.context as CanvasRenderingContext2D
// context.filter = 'none'
// }
//});
olProj.useGeographic();
//})
olProj.useGeographic()
this.map = new Map({
target: conquerContainer,
layers: [
@ -283,33 +287,45 @@ export default class Conquer {
zoom: 21,
maxZoom: 22,
}),
});
const proccessLocation = (location: GeolocationPosition) => {
this.currentLatitude = location.coords.latitude
this.currentLongitude = location. coords.longitude
if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {
this.disableSetRotationOffset = true
this.heading = location.coords.heading
this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading*Math.PI*2)/360
}
this.setCenterDisplaced(this.currentLatitude, this.currentLongitude)
})
this.setLocationChangeTriggers()
this.setRotationChangeTriggers()
}
setRotationChangeTriggers(): void {
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", (event) => {
if (event.alpha !== null && event.beta !== null && event.gamma !== null) {
this.onRotate(event.alpha, event.beta, event.gamma)
}
}, true)
}
this.setCenterDisplaced(37.58237, -5.96766)
navigator.geolocation.watchPosition((location) => {
proccessLocation(location)
}, (err) => {
return
}, {
enableHighAccuracy: true,
maximumAge: 0
});
}
processLocation(location: GeolocationPosition) {
this.currentLatitude = location.coords.latitude
this.currentLongitude = location. coords.longitude
if (location.coords.heading !== null && (this.alpha != 0 || this.beta != 0 || this.gamma != 0) && !this.disableSetRotationOffset) {
this.disableSetRotationOffset = true
this.heading = location.coords.heading
this.rotationOffset = this.compassHeading(this.alpha, this.beta, this.gamma) + (location.coords.heading*Math.PI*2)/360
this.setCenterDisplaced(this.currentLatitude, this.currentLongitude)
const currentPositionFeature = new Feature({
type: 'currentPositionFeature',
geometry: new Point([this.currentLatitude, this.currentLongitude])
})
this.currentPositionFeature = currentPositionFeature
}
}
setLocationChangeTriggers(): void {
window.setInterval(() => {
this.disableSetRotationOffset = false
}, 10000);
}, 10000)
this.currentPositionFeature = null
window.setTimeout(() => {
window.setInterval(() => {
navigator.geolocation.getCurrentPosition((location) => {
proccessLocation(location)
this.processLocation(location)
}, () => {
return
}, {
@ -318,37 +334,26 @@ export default class Conquer {
})
}, 1000)
}, 1000)
if (window.DeviceOrientationEvent) {
window.addEventListener("deviceorientation", (event) => {
if (event.alpha !== null && event.beta !== null && event.gamma !== null) {
this.onRotate(event.alpha, event.beta, event.gamma);
}
}, true);
}
this.setCenterDisplaced(37.58237, -5.96766)
navigator.geolocation.watchPosition((location) => {
this.processLocation(location)
}, (err) => {
return
}, {
enableHighAccuracy: true,
maximumAge: 0
})
}
realCoordinatesToOl(lat: number, lon: number): number[] {
return olProj.transform(
[lon, lat],
new Projection({ code: "WGS84" }),
new Projection({ code: "EPSG:900913" }),
);
)
}
compassHeading(alpha:number, beta:number, gamma:number): number {
const alphaRad = alpha * (Math.PI / 180);
const alphaRad = alpha * (Math.PI / 180)
return alphaRad
let betaRad = beta * (Math.PI / 180);
const gammaRad = gamma * (Math.PI / 180);
betaRad = 1.5707963268;
const cA = Math.cos(alphaRad);
const sA = Math.sin(alphaRad);
const sB = Math.sin(betaRad);
const cG = Math.cos(gammaRad);
const sG = Math.sin(gammaRad);
const rA = - cA * sG - sA * sB * cG;
const rB = - sA * sG + cA * sB * cG;
return Math.atan2(rA, rB)
}
logToServer(logValue: string) {
@ -360,7 +365,7 @@ export default class Conquer {
console.error(error)
})
}
enabledOnRotate = true;
enabledOnRotate = true
onRotate(alpha: number, beta: number, gamma: number) {
if (this.enabledOnRotate) {
this.alpha = alpha
@ -377,7 +382,7 @@ export default class Conquer {
this.setCenterDisplaced(this.currentLatitude, this.currentLongitude)
}
constructor(conquerContainer: HTMLDivElement) {
this.conquerContainer = conquerContainer;
this.conquerContainer = conquerContainer
}
private async addNewLoginRegisterError(message: string): Promise<void> {
this.addNewRegisterError(message)
@ -385,7 +390,7 @@ export default class Conquer {
}
private async isLogged(): Promise<boolean> {
const urlUser = new URL('/conquer/user', window.location.protocol + '//' + window.location.hostname + ':' + window.location.port)
let responseJson;
let responseJson
let status
try {
const response = await fetch(urlUser)

File diff suppressed because one or more lines are too long