working location button

This commit is contained in:
Ward 2021-07-13 14:39:50 +02:00
parent 4276d4a47d
commit ca1871262e

View file

@ -8,13 +8,18 @@ import LayoutConfig from "../../Customizations/JSON/LayoutConfig";
import { VariableUiElement } from "../../UI/Base/VariableUIElement"; import { VariableUiElement } from "../../UI/Base/VariableUIElement";
export default class GeoLocationHandler extends VariableUiElement { export default class GeoLocationHandler extends VariableUiElement {
/** /**
* Wether or not the geolocation is active, aka the user requested the current location * Wether or not the geolocation is active, aka the user requested the current location
* @private * @private
*/ */
private readonly _isActive: UIEventSource<boolean>; private readonly _isActive: UIEventSource<boolean>;
/**
* Wether or not the geolocation is locked, aka the user requested the current location and wants the crosshair to follow the user
* @private
*/
private readonly _isLocked: UIEventSource<boolean>;
/** /**
* The callback over the permission API * The callback over the permission API
* @private * @private
@ -30,7 +35,10 @@ export default class GeoLocationHandler extends VariableUiElement {
* @private * @private
*/ */
private readonly _hasLocation: UIEventSource<boolean>; private readonly _hasLocation: UIEventSource<boolean>;
private readonly _currentGPSLocation: UIEventSource<{ latlng: any; accuracy: number }>; private readonly _currentGPSLocation: UIEventSource<{
latlng: any;
accuracy: number;
}>;
/** /**
* Kept in order to update the marker * Kept in order to update the marker
* @private * @private
@ -52,29 +60,36 @@ export default class GeoLocationHandler extends VariableUiElement {
private readonly _previousLocationGrant: UIEventSource<string>; private readonly _previousLocationGrant: UIEventSource<string>;
private readonly _layoutToUse: UIEventSource<LayoutConfig>; private readonly _layoutToUse: UIEventSource<LayoutConfig>;
constructor(
constructor(currentGPSLocation: UIEventSource<{ latlng: any; accuracy: number }>, currentGPSLocation: UIEventSource<{ latlng: any; accuracy: number }>,
leafletMap: UIEventSource<L.Map>, leafletMap: UIEventSource<L.Map>,
layoutToUse: UIEventSource<LayoutConfig>) { layoutToUse: UIEventSource<LayoutConfig>
) {
const hasLocation = currentGPSLocation.map((location) => location !== undefined); const hasLocation = currentGPSLocation.map(
const previousLocationGrant = LocalStorageSource.Get("geolocation-permissions") (location) => location !== undefined
);
const previousLocationGrant = LocalStorageSource.Get(
"geolocation-permissions"
);
const isActive = new UIEventSource<boolean>(false); const isActive = new UIEventSource<boolean>(false);
super( super(
hasLocation.map(hasLocation => { hasLocation.map(
(hasLocation) => {
if (hasLocation) { if (hasLocation) {
return Svg.crosshair_blue_ui() return Svg.crosshair_blue_ui();
} }
if (isActive.data) { if (isActive.data) {
return Svg.crosshair_blue_center_ui(); return Svg.crosshair_blue_center_ui();
} }
return Svg.crosshair_ui(); return Svg.crosshair_ui();
}, [isActive]) },
[isActive]
)
); );
this._isActive = isActive; this._isActive = isActive;
this._permission = new UIEventSource<string>("") this._isLocked = new UIEventSource<boolean>(false);
this._permission = new UIEventSource<string>("");
this._previousLocationGrant = previousLocationGrant; this._previousLocationGrant = previousLocationGrant;
this._currentGPSLocation = currentGPSLocation; this._currentGPSLocation = currentGPSLocation;
this._leafletMap = leafletMap; this._leafletMap = leafletMap;
@ -82,47 +97,49 @@ export default class GeoLocationHandler extends VariableUiElement {
this._hasLocation = hasLocation; this._hasLocation = hasLocation;
const self = this; const self = this;
const currentPointer = this._isActive.map(isActive => { const currentPointer = this._isActive.map(
(isActive) => {
if (isActive && !self._hasLocation.data) { if (isActive && !self._hasLocation.data) {
return "cursor-wait" return "cursor-wait";
} }
return "cursor-pointer" return "cursor-pointer";
}, [this._hasLocation]) },
currentPointer.addCallbackAndRun(pointerClass => { [this._hasLocation]
);
currentPointer.addCallbackAndRun((pointerClass) => {
self.SetClass(pointerClass); self.SetClass(pointerClass);
}) });
this.onClick(() => self.init(true));
this.onClick(() => self.init(true)) this.init(false);
this.init(false)
}
private init(askPermission: boolean) {
const self = this;
const map = this._leafletMap.data;
this._currentGPSLocation.addCallback((location) => { this._currentGPSLocation.addCallback((location) => {
self._previousLocationGrant.setData("granted"); self._previousLocationGrant.setData("granted");
const timeSinceRequest = (new Date().getTime() - (self._lastUserRequest?.getTime() ?? 0)) / 1000; const timeSinceRequest =
(new Date().getTime() - (self._lastUserRequest?.getTime() ?? 0)) / 1000;
if (timeSinceRequest < 30) { if (timeSinceRequest < 30) {
self.MoveToCurrentLoction(16) self.MoveToCurrentLoction(16);
} else if (self._isLocked.data) {
self.MoveToCurrentLoction();
} }
let color = "#1111cc"; let color = "#1111cc";
try { try {
color = getComputedStyle(document.body).getPropertyValue("--catch-detail-color") color = getComputedStyle(document.body).getPropertyValue(
"--catch-detail-color"
);
} catch (e) { } catch (e) {
console.error(e) console.error(e);
} }
const icon = L.icon( const icon = L.icon({
{
iconUrl: Img.AsData(Svg.crosshair.replace(/#000000/g, color)), iconUrl: Img.AsData(Svg.crosshair.replace(/#000000/g, color)),
iconSize: [40, 40], // size of the icon iconSize: [40, 40], // size of the icon
iconAnchor: [20, 20], // point of the icon which will correspond to marker's location iconAnchor: [20, 20], // point of the icon which will correspond to marker's location
}) });
const map = self._leafletMap.data;
console.log("check for map", map);
const newMarker = L.marker(location.latlng, { icon: icon }); const newMarker = L.marker(location.latlng, { icon: icon });
newMarker.addTo(map); newMarker.addTo(map);
@ -132,87 +149,80 @@ export default class GeoLocationHandler extends VariableUiElement {
} }
self._marker = newMarker; self._marker = newMarker;
}); });
}
private init(askPermission: boolean) {
const self = this;
if (self._isActive.data) {
self.MoveToCurrentLoction(16);
return;
}
try { try {
navigator?.permissions
navigator?.permissions?.query({name: 'geolocation'}) ?.query({ name: "geolocation" })
?.then(function (status) { ?.then(function (status) {
console.log("Geolocation is already", status) console.log("Geolocation is already", status);
if (status.state === "granted") { if (status.state === "granted") {
self.StartGeolocating(false); self.StartGeolocating(false);
} }
self._permission.setData(status.state); self._permission.setData(status.state);
status.onchange = function () { status.onchange = function () {
self._permission.setData(status.state); self._permission.setData(status.state);
} };
}); });
} catch (e) { } catch (e) {
console.error(e) console.error(e);
} }
if (askPermission) { if (askPermission) {
self.StartGeolocating(true); self.StartGeolocating(true);
} else if (this._previousLocationGrant.data === "granted") { } else if (this._previousLocationGrant.data === "granted") {
this._previousLocationGrant.setData(""); this._previousLocationGrant.setData("");
self.StartGeolocating(false); self.StartGeolocating(false);
} }
} }
private locate() { private MoveToCurrentLoction(targetZoom?: number) {
const self = this;
const map: any = this._leafletMap.data;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
self._currentGPSLocation.setData({
latlng: [position.coords.latitude, position.coords.longitude],
accuracy: position.coords.accuracy
});
}, function () {
console.warn("Could not get location with navigator.geolocation")
});
return;
} else {
map.findAccuratePosition({
maxWait: 10000, // defaults to 10000
desiredAccuracy: 50 // defaults to 20
});
}
}
private MoveToCurrentLoction(targetZoom = 16) {
const location = this._currentGPSLocation.data; const location = this._currentGPSLocation.data;
this._lastUserRequest = undefined; this._lastUserRequest = undefined;
if (
if (this._currentGPSLocation.data.latlng[0] === 0 && this._currentGPSLocation.data.latlng[1] === 0) { this._currentGPSLocation.data.latlng[0] === 0 &&
console.debug("Not moving to GPS-location: it is null island") this._currentGPSLocation.data.latlng[1] === 0
) {
console.debug("Not moving to GPS-location: it is null island");
return; return;
} }
// We check that the GPS location is not out of bounds // We check that the GPS location is not out of bounds
const b = this._layoutToUse.data.lockLocation const b = this._layoutToUse.data.lockLocation;
let inRange = true; let inRange = true;
if (b) { if (b) {
if (b !== true) { if (b !== true) {
// B is an array with our locklocation // B is an array with our locklocation
inRange = b[0][0] <= location.latlng[0] && location.latlng[0] <= b[1][0] && inRange =
b[0][1] <= location.latlng[1] && location.latlng[1] <= b[1][1]; b[0][0] <= location.latlng[0] &&
location.latlng[0] <= b[1][0] &&
b[0][1] <= location.latlng[1] &&
location.latlng[1] <= b[1][1];
} }
} }
if (!inRange) { if (!inRange) {
console.log("Not zooming to GPS location: out of bounds", b, location.latlng) console.log(
} else { "Not zooming to GPS location: out of bounds",
this._leafletMap.data.setView( b,
location.latlng, targetZoom location.latlng
); );
} else {
this._leafletMap.data.setView(location.latlng, targetZoom);
} }
} }
private StartGeolocating(zoomToGPS = true) { private StartGeolocating(zoomToGPS = true) {
const self = this; const self = this;
console.log("Starting geolocation") console.log("Starting geolocation");
this._lastUserRequest = zoomToGPS ? new Date() : new Date(0); this._lastUserRequest = zoomToGPS ? new Date() : new Date(0);
if (self._permission.data === "denied") { if (self._permission.data === "denied") {
@ -220,25 +230,26 @@ export default class GeoLocationHandler extends VariableUiElement {
return ""; return "";
} }
if (this._currentGPSLocation.data !== undefined) { if (this._currentGPSLocation.data !== undefined) {
this.MoveToCurrentLoction(16) this.MoveToCurrentLoction(16);
} }
console.log("Searching location using GPS");
console.log("Searching location using GPS") if (self._isActive.data) {
this.locate();
if (!self._isActive.data) {
self._isActive.setData(true);
Utils.DoEvery(60000, () => {
if (document.visibilityState !== "visible") {
console.log("Not starting gps: document not visible")
return; return;
} }
this.locate(); self._isActive.setData(true);
})
}
}
navigator.geolocation.watchPosition(
function (position) {
self._currentGPSLocation.setData({
latlng: [position.coords.latitude, position.coords.longitude],
accuracy: position.coords.accuracy,
});
},
function () {
console.warn("Could not get location with navigator.geolocation");
}
);
}
} }