Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 2x 2x 2x 2x 9x 2x 9x 2x 9x 1x 9x 1x 9x 1x 9x 1x 9x 1x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 2x 4x 2x 1x 1x 2x 2x 1x 1x 27x 27x 27x 27x 12x 6x 24x 6x 6x 6x 6x 6x 6x 6x 11x 11x 11x 5x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 6x 6x 6x 6x 6x 6x 6x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 2x 1x 1x 2x 2x 27x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 5x 5x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 11x 11x 11x 11x 11x 11x 11x 11x 1x 10x 10x 3x 3x 3x 3x 6x 6x 6x 6x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 2x 12x 12x 2x 2x 11x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 11x 1x | import { Injectable, Component } from '@angular/core';
import { OnInit, AfterViewInit, OnDestroy } from '@angular/core';
import { Input, Output, EventEmitter, ViewChild } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { HttpClient } from '@angular/common/http';
import { Subject, Subscription } from 'rxjs';
import { take } from 'rxjs/operators';
import { Geolocation } from '@awesome-cordova-plugins/geolocation/ngx';
import { AndroidPermissions } from '@awesome-cordova-plugins/android-permissions/ngx';
import { languageSupport, languageService } from './language';
import { platformService } from './platform';
import { httpService } from './http';
import { alertService } from './alert';
import { toastService } from './toasts';
import { viewService } from './view';
import { AppConstants} from '@unpispas/upp-defs';
/**
* Represents structured to store coordinates.
*/
export interface Coordinates {
lat: number,
lng: number
}
/**
* Represents structured position data retrieved from the device.
*/
export interface WatchPosition {
granted: boolean,
coordinates: {
lat: number,
lng: number,
},
accuracy: number
}
export interface GeocodePosition {
coords: {
latitude: number;
longitude: number;
altitude: number | null;
accuracy: number;
altitudeAccuracy: number | null;
heading: number | null;
speed: number | null;
};
timestamp: number;
}
export type GeocodePositionCallback = (position: GeocodePosition) => void
export type GeocodePositionErrorCallback = (error: GeolocationPositionError) => void;
/************************************/
/* GOOGLE ADDRESS DATA */
/************************************/
/**
* Represents structured address data retrieved from the Google Geocoding API.
*/
export interface Address {
formatted: string;
location: {
lat : number,
lng : number
};
number: string;
street: {
route: string,
locality: string,
};
postal_code: string;
area: {
level1: string,
level2: string,
level3: string
},
timezone: string;
}
/************************************/
/* GEOCODE SERVICE */
/************************************/
/**
* Provides geocoding and geolocation services for interacting with Google Maps API
* to retrieve address, timezone, and positional data.
*/
@Injectable({
providedIn: 'root'
})
export class geocodeService {
private _mapsurl = 'https://maps.googleapis.com/maps/api/geocode/json?key=' + AppConstants.googleApiKey;
private _tmznurl = 'https://maps.googleapis.com/maps/api/timezone/json?key=' + AppConstants.googleApiKey;
private _requestCache = new Map();
private _resolveCache = new Map();
private _timezneCache = new Map();
private _requestAndroidPermissions() {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_FINE_LOCATION);
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.ACCESS_COARSE_LOCATION);
}
public GMAP_API_LOADED = false;
LoadGoogleMaps(loaded: Subject<boolean>): Promise<void> {
return new Promise((resolve, reject) => {
if ((window as any).google && (window as any).google.maps) {
resolve();
}
else {
const _script = document.createElement('script');
_script.async = true;
_script.defer = true;
_script.src = "https://maps.googleapis.com/maps/api/js?key=" + AppConstants.googleApiKey + "&loading=async&callback=initGoogleMaps";
_script.onload = () => {
this.GMAP_API_LOADED = true;
console.info("[GOOGLE MAPS] API requested..");
(window as any).initGoogleMaps = async () => {
console.info("[GOOGLE MAPS] API loaded.");
setTimeout(() => {
loaded.next(true);
}, 0);
resolve();
};
};
_script.onerror = (error) => {
console.error("[GOOGLE MAPS] Error loading API: ", error)
reject(error);
};
document.body.appendChild(_script);
}
});
}
/**
* Initializes the service and requests Android permissions if applicable.
*/
constructor(private androidPermissions: AndroidPermissions, private geolocation: Geolocation, private http: httpService, private lang: languageService, private modalCtrl: ModalController, private alertCtrl: alertService, private toast: toastService, private platform: platformService) {
this._requestAndroidPermissions(); // request location permission for android devices
}
// https://developers.google.com/maps/documentation/geocoding/start?hl=es
private _parseGoogleResponse(response: any) {
const address: Address = {
formatted: '',
location: {
lat: 0.0,
lng: 0.0
},
number: '',
street: {
route: '',
locality: ''
},
postal_code: '',
area: {
level1: '',
level2: '',
level3: '',
},
timezone: 'UTC'
};
// https://developers.google.com/maps/documentation/geocoding/intro?hl=es#GeocodingResponses
Iif ((response.status != 'OK') || (response.results.length == 0)) {
console.error("[GEOCODE] Parsing google response", response);
Iif (response.status != 'ZERO_RESULTS'){
this.toast.ShowAlert('danger', this.lang.tr('@gmaps_request_error', [ response.status, response.error_message ]));
}
return null;
}
const data = response['results'][0];
for(let i=0; i < data['address_components'].length; i++) {
if (data.address_components[i]['types'].indexOf('street_number') != -1) {
address.number = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('route') != -1) {
address.street.route = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('locality') != -1) {
address.street.locality = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('postal_code') != -1) {
address.postal_code = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('administrative_area_level_1') != -1) {
address.area.level1 = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('administrative_area_level_2') != -1) {
address.area.level2 = data.address_components[i]['long_name'];
}
if (data.address_components[i]['types'].indexOf('country') != -1) {
address.area.level3 = data.address_components[i]['short_name'];
}
}
address.formatted = data['formatted_address'];
address.location = {
lat: parseFloat(data['geometry']['location']['lat']),
lng: parseFloat(data['geometry']['location']['lng'])
};
return address;
}
/**
* Generates a static map URL for a specific latitude and longitude.
*
* @param lat - Latitude of the center point.
* @param lng - Longitude of the center point.
* @param width - Width of the generated map image.
* @param height - Height of the generated map image.
* @param zoom - Zoom level (default is 15).
* @returns The constructed URL for the static map image.
*/
StaticUrl(lat: number, lng: number, width: number, height: number, zoom=15) {
let _url = 'https://maps.googleapis.com/maps/api/staticmap';
_url += '?key=' + AppConstants.googleApiKey;
_url += '&size=' + width + "x" + height;
_url += '¢er=' + lat + "," + lng + '&zoom=' + zoom;
_url += '&markers=color:red|'+ lat + ',' + lng;
return _url;
}
/**
* Requests address data from the Google Geocoding API based on latitude and longitude.
* Caches responses to reduce repeated network requests.
*
* @param lat - Latitude of the requested location.
* @param lng - Longitude of the requested location.
* @returns A promise resolving to address data or `null` if an error occurs.
*/
RequestAddress(lat: number, lng: number): Promise <any> {
return new Promise <any> ((resolve) => {
const latlng = lat + ',' + lng;
Iif (this._requestCache.has(latlng)) {
setTimeout(() => {
resolve(this._requestCache.get(latlng));
}, 10);
}
else {
const _request = this.http.get(this._mapsurl + '&latlng=' + latlng, false);
_request.pipe(take(1)).subscribe({
next: (data) => {
const _address = this._parseGoogleResponse(data)
if (_address) {
this._requestCache.set(latlng, _address);
}
resolve(_address);
},
error: (error) => {
if (error.status != 0){
this.toast.ShowAlert('danger', this.lang.tr('@http_request_error', [ error.status ]));
}
else {
console.error("[HTTP] status = 0");
}
resolve(null);
},
complete: () => {
// nothing to do
}
});
}
});
}
/**
* Requests timezone information for a specific location using the Google Timezone API.
*
* @param lat - Latitude of the requested location.
* @param lng - Longitude of the requested location.
* @returns A promise resolving to the timezone ID or 'UTC' if an error occurs.
*/
RequestTimezne(lat: number, lng: number): Promise <string> {
return new Promise <string> ((resolve) => {
const latlng = lat.toFixed(4) + ',' + lng.toFixed(4);
Iif (this._timezneCache.has(latlng)) {
setTimeout(() => {
resolve(this._timezneCache.get(latlng));
}, 10);
}
else {
const tstamp = Math.floor(new Date().getTime() / 1000);
const _request = this.http.get(this._tmznurl + '&location=' + latlng + '×tamp=' + tstamp, false);
_request.pipe(take(1)).subscribe({
next: (data: any) => {
if (data && data['timeZoneId']) {
this._timezneCache.set(latlng, data['timeZoneId']);
}
resolve(data['timeZoneId']);
},
error: (error) => {
if (error.status != 0){
this.toast.ShowAlert('danger', this.lang.tr('@http_request_error', [ error.status ]));
}
else E{
console.error("[HTTP] status = 0");
}
resolve('UTC'); // fallback to UTC on error
},
complete: () => {
// nothing to do
}
});
}
});
}
/**
* Resolves an address from a string query using the Google Geocoding API.
* Caches responses to optimize repeated lookups.
*
* @param address - The address query string.
* @returns A promise resolving to parsed address data or `false` if an error occurs.
*/
ResolveAddress(address: string): Promise <Address | null> {
return new Promise <Address | null> ((resolve) => {
Iif (this._resolveCache.has(address)) {
setTimeout(() => {
resolve(this._resolveCache.get(address));
}, 10);
}
else {
const _request = this.http.get(this._mapsurl + '&address=' + address, false);
_request.pipe(take(1)).subscribe({
next: (data) => {
const _address = this._parseGoogleResponse(data);
if (_address) {
this._resolveCache.set(address, _address);
}
resolve(_address);
},
error: (error) => {
if (error.status != 0){
this.toast.ShowAlert('danger', this.lang.tr('@http_request_error', [ error.status ]));
}
else E{
console.error("[HTTP] status = 0");
}
resolve(null);
},
complete: () => {
// nothing to do
}
});
}
});
}
/**
* Checks if geolocation services are available on the platform.
*/
get CanGeolocate(){
if (this.platform.is('cordova')){
return true;
}
else {
return navigator.geolocation;
}
}
private _ToGeoposition(position: any): GeocodePosition {
return {
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
altitude: position.coords.altitude !== undefined ? position.coords.altitude : null,
accuracy: position.coords.accuracy,
altitudeAccuracy: position.coords.altitudeAccuracy !== undefined ? position.coords.altitudeAccuracy : null,
heading: position.coords.heading !== undefined ? position.coords.heading : null,
speed: position.coords.speed !== undefined ? position.coords.speed : null
},
timestamp: position.timestamp
};
}
/**
* Retrieves the current geolocation position.
*
* @param resolve - Callback function executed on successful location retrieval.
* @param reject - Callback function executed on failed location retrieval.
*/
GetCurrentPosition(resolve: GeocodePositionCallback, reject: GeocodePositionErrorCallback) {
if (this.platform.is('cordova')){
this.geolocation.getCurrentPosition()
.then((resp) => {
resolve(this._ToGeoposition(resp))
})
.catch((error) => {
reject(error);
});
}
else {
const _options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
navigator.geolocation.getCurrentPosition(
(position) => resolve(this._ToGeoposition(position)),
(error: GeolocationPositionError) => reject(error),
_options
);
}
}
/***************************/
/* WATCH POSITION */
/***************************/
private _positionChanged = new Subject<void> ();
public OnPositionChanged = this._positionChanged.asObservable();
private _watchpositionid: any | null = null;
private _watchposition: WatchPosition = {
granted: false,
coordinates: {
lat: 0,
lng: 0,
},
accuracy: 0
};
/**
* Returns the currently watched position
*/
get CurrentPosition(): WatchPosition{
return this._watchposition;
}
/**
* Calculates the distance in meters between the current position and specified coordinates.
*
* @param coordinates - Target coordinates.
* @returns Distance in meters.
*/
DistanceTo(coordinates: Coordinates): number {
// https://stackoverflow.com/questions/365826/calculate-distance-between-2-gps-coordinates
const _earthRadius = 6371;
function degreesToRadians(degrees: number) {
return degrees * Math.PI / 180;
}
const _dLat = degreesToRadians(this.CurrentPosition.coordinates.lat - coordinates.lat);
const _dLon = degreesToRadians(this.CurrentPosition.coordinates.lng - coordinates.lng);
const _lat1 = degreesToRadians(coordinates.lat);
const _lat2 = degreesToRadians(this.CurrentPosition.coordinates.lat);
const _a = Math.sin(_dLat/2) * Math.sin(_dLat/2) + Math.sin(_dLon/2) * Math.sin(_dLon/2) * Math.cos(_lat1) * Math.cos(_lat2);
const _c = 2 * Math.atan2(Math.sqrt(_a), Math.sqrt(1 - _a));
return Math.abs(Math.round(_earthRadius * _c * 1000));
}
/**
* Starts watching the current geolocation position.
* Updates the `_watchposition` property and notifies observers on position change.
*
* @returns A promise resolving to `true` if watch started successfully, `false` otherwise.
*/
private StartWatch(){
return new Promise <boolean> ((resolve) => {
Iif (this._watchpositionid){
resolve(true);
this._positionChanged.next(); // already started
}
else {
if (this.platform.is('cordova')){
this._watchpositionid = this.geolocation.watchPosition().subscribe(
data => {
if ('coords' in data) {
const _nextposition: WatchPosition = {
granted: true,
coordinates: {
lat: data.coords.latitude,
lng: data.coords.longitude,
},
accuracy: data.coords.accuracy,
};
if (JSON.stringify(this._watchposition) !== JSON.stringify(_nextposition)) {
this._watchposition = _nextposition;
resolve(true);
this._positionChanged.next();
}
}
else E{
console.error("[GEOLOCATION] error in watchPosition: ", data.message);
resolve(false);
}
},
(err) => {
this._watchpositionid = null;
console.error("[GEOLOCATION] error on watchposition: ", err.message);
switch (err.code) {
case 1:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_denied'));
break;
case 2:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_unavailable'));
break;
case 3:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_expired'));
break;
default:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_error', [err.message, err.code.toString()]));
break;
}
resolve(false);
});
}
else {
const _options: PositionOptions = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
this._watchpositionid = navigator.geolocation.watchPosition(
(pos) => {
const _nextposition: WatchPosition = {
granted: true,
coordinates: {
lat: pos.coords.latitude,
lng: pos.coords.longitude,
},
accuracy: pos.coords.accuracy
}
if (JSON.stringify(this._watchposition) != JSON.stringify(_nextposition)){
this._watchposition = _nextposition;
resolve(true);
this._positionChanged.next();
}
}, (err) => {
this._watchpositionid = null;
console.error("[GEOLOCATION] error on watchposition: ", err.message);
switch(err.code){
case 1:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_denied'));
break;
case 2:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_unavailable'));
break;
case 3:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_expired'));
break;
default:
this.toast.ShowAlert('danger', this.lang.tr('@geolocation_error', [ err.message, err.code.toString() ]))
break;
}
resolve(false);
}, _options);
}
}
});
}
/**
* Stops watching the geolocation position.
* Resets the `_watchposition` property and clears the watch ID.
*/
private ClearWatch(){
if (this._watchpositionid){
if (this.platform.is('cordova')){
this._watchpositionid.unsubscribe();
}
else {
navigator.geolocation.clearWatch(this._watchpositionid);
}
this._watchposition = {
granted: this._watchposition.granted,
coordinates: {
lat: 0,
lng: 0
},
accuracy: 0
};
this._watchpositionid = null;
}
}
private _nearby_farawaymodal = false; // keep control of away modal being displayed
private async ShowAway(center: Coordinates){
const modal = await this.modalCtrl.create({
component: modalAwayComponent,
backdropDismiss: false,
componentProps: {
center: center,
}
});
if (this._nearby_farawaymodal){
await modal.present();
const detail = await modal.onDidDismiss();
this._nearby_farawaymodal = false;
return detail?.data || null;
}
return null;
}
private async AskPermission(){
const alert = await this.alertCtrl.alert({
header: this.lang.tr('@require_geolocate_title'),
message: this.lang.tr('@require_geolocate_message'),
buttons: [{
text: this.lang.tr('@ok'),
handler: () => {
alert.dismiss(true);
}
}]
});
await alert.present();
await alert.onDidDismiss();
await new Promise(resolve => setTimeout(resolve, 100));
return await this.StartWatch();
}
private IsNear(center: Coordinates, radius: number){
return (this.DistanceTo(center) <= radius + this.CurrentPosition.accuracy)
}
/**
* Waits until the current position is within a specified radius of the center coordinates.
* Shows a modal if the user is outside the radius, and waits until they are nearby.
*
* @param center - The center coordinates.
* @param radius - Radius in meters (default is 250).
* @returns A promise resolving to `true` if within radius, `false` otherwise.
*/
WaitForNear(center: Coordinates, radius = 250) : Promise <boolean> {
return new Promise <boolean> ((resolve) => {
if (this.CurrentPosition){
if (this.IsNear(center, radius)){
resolve(true);
}
else {
if (!this._nearby_farawaymodal){
this._nearby_farawaymodal = true;
this.ShowAway(center).then(
data => {
this._nearby_farawaymodal = false;
resolve(data ? true : false);
});
}
}
}
else E{
this.OnPositionChanged.pipe(take(1)).subscribe(
() => {
resolve(this.WaitForNear(center, radius));
});
}
});
}
/**
* Enables or disables a proximity-based restriction.
* Starts watching the position if required and checks proximity.
*
* @param center - The center coordinates or `null` to disable the restriction.
* @param radius - Radius in meters (default is 250).
* @returns A promise resolving to `true` if within radius or restriction is disabled, `false` otherwise.
*/
async NearBy(center: Coordinates | null, radius = 250) : Promise <boolean> {
// use center = null to disable requirement
Iif (center == null){
console.info("[GEOLOCATE] disabling near-by restrinction")
this.ClearWatch();
Iif (this._nearby_farawaymodal){
this._nearby_farawaymodal = false;
}
return true; // disabled
}
else {
if (!this._watchpositionid){ // we must start watching
console.info("[GEOLOCATE] near-by restrinction enabled to " + radius + " metres");
let _granted = this._watchposition.granted;
if (!_granted){
_granted = await this.AskPermission();
}
else E{
_granted = await this.StartWatch();
}
Iif (!_granted){ // permission not granted
return false;
}
}
if (this._watchpositionid){
return (await this.WaitForNear(center, radius)) ? true : false;
}
}
return false; // could not start watching
}
}
/************************************/
/* MODAL FAR AWAY */
/************************************/
/**
* A modal component that displays information when the user is far from a specified center location.
* It includes distance monitoring and an option to close the modal when the user is within range.
*/
@Component({
selector: 'upp-modal-away',
templateUrl: './away/modal/modal-away.html',
styleUrls: [
'./away/modal/modal-away.scss'
]
})
export class modalAwayComponent {
/**
* The center coordinates that the distance is measured from.
*/
@Input() center: Coordinates | null = null;
/**
* Initializes the component and retrieves the center coordinates from modal parameters.
*
* @param modalCtrl - Controller for managing modal dismissal.
*/
constructor(private modalCtrl: ModalController) {
// nothing to do
}
private inrange = 250;
/**
* Handles changes to the user's distance from the center.
* Closes the modal if the distance is within the specified range plus the accuracy.
*
* @param data - Object containing `distance` and `accuracy` properties for the user's current position.
*/
OnChange(data: any){
Iif (data.distance < (this.inrange + data.accuracy)){
(document.activeElement as HTMLElement)?.blur();
this.modalCtrl.dismiss(true);
}
}
/**
* Manually closes the modal without confirming proximity.
*/
OnClose(){
(document.activeElement as HTMLElement)?.blur();
this.modalCtrl.dismiss(false);
}
}
/************************************/
/* FAR AWAY INFORMATION */
/************************************/
/**
* A component that displays information when the user is far from a specified center location.
* Includes map display and location information based on Google Maps API.
*/
@Component({
selector: 'upp-away',
templateUrl:'./away/view/ui-away.html',
styleUrls: [
'./away/view/ui-away.scss'
]
})
export class UiAwayComponent extends languageSupport implements OnInit, AfterViewInit, OnDestroy {
/**
* The center coordinates to calculate the distance from.
*/
@Input() _center: Coordinates | null = null;
private _gmapsApiLoaded = new Subject <boolean> ();
public gmapsApiLoaded = this._gmapsApiLoaded.asObservable();
/**
* Map display information, including markers, accuracy, and zoom level.
*/
public _mapinfo = {
zoom: 17,
accuracy: 0,
position: {
lat: 0,
lng: 0
},
markers: [{
position: {
lat: 0,
lng: 0
},
options: {
draggable: false,
icon: '/assets/image/marker-place.png'
}
}, {
position: {
lat: 0,
lng: 0
},
options: {
draggable: false
}
}]
};
private _distance = 0;
/**
* Gets the distance to the center point. Displays in kilometers if the distance is over 1,000 meters.
*/
get Distance(){
if (this._distance > 1000){
return (this._distance / 1000).toFixed(2) + " " + this.lang.tr("@kilometres");
}
else {
return this._distance + " " + this.lang.tr("@metres");
}
}
/**
* Loads the Google Maps API script if not already loaded and initializes language and location services.
*/
constructor(private lang: languageService, private geocode: geocodeService, public view: viewService, private http: HttpClient) {
super(lang, null);
// https://github.com/angular/components/tree/master/src/google-maps
if (!geocode.GMAP_API_LOADED) {
this.geocode.LoadGoogleMaps(this._gmapsApiLoaded);
}
else {
console.warn("[GOOGLE MAPS] API already loaded");
setTimeout(() => {
this._gmapsApiLoaded.next(true);
}, 0);
}
}
// https://stackoverflow.com/questions/6048975/google-maps-v3-how-to-calculate-the-zoom-level-for-a-given-bounds
@ViewChild('googlemap', { static: false }) _googlemap: any;
private BoundsZoomLevel(coords1: Coordinates, coords2: Coordinates) {
const WORLD_DIM = { height: 256, width: 256 };
const ZOOM_MAX = 21, ZOOM_DEFAULT = 17;
function getNorthEast(coords1: Coordinates, coords2: Coordinates){
return {
lat: (coords1.lat > coords2.lat) ? coords1.lat : coords2.lat,
lng: (coords1.lng > coords2.lng) ? coords1.lng : coords2.lng
};
}
function getSouthWest(coords1: Coordinates, coords2: Coordinates){
return {
lat: (coords1.lat < coords2.lat) ? coords1.lat : coords2.lat,
lng: (coords1.lng < coords2.lng) ? coords1.lng : coords2.lng
};
}
function latRad(lat: number) {
const sin = Math.sin(lat * Math.PI / 180);
const radX2 = Math.log((1 + sin) / (1 - sin)) / 2;
return Math.max(Math.min(radX2, Math.PI), -Math.PI) / 2;
}
function zoom(mapPx: number, worldPx: number, fraction: number) {
return Math.floor(Math.log(mapPx / worldPx / fraction) / Math.LN2);
}
let mapDim = { height: 0, width: 0 };
Iif (!this._googlemap){
return ZOOM_DEFAULT;
}
else {
mapDim = {
height: this._googlemap._elementRef.nativeElement.clientHeight,
width: this._googlemap._elementRef.nativeElement.clientHeight
};
Iif ((mapDim.height == 0) || (mapDim.width == 0)){
return ZOOM_DEFAULT;
}
}
const ne = getNorthEast(coords1, coords2);
const sw = getSouthWest(coords1, coords2);
const latFraction = (latRad(ne.lat) - latRad(sw.lat)) / Math.PI;
const lngDiff = ne.lng - sw.lng;
const lngFraction = ((lngDiff < 0) ? (lngDiff + 360) : lngDiff) / 360;
const latZoom = zoom(mapDim.height, WORLD_DIM.height, latFraction);
const lngZoom = zoom(mapDim.width, WORLD_DIM.width, lngFraction);
return Math.min(latZoom, lngZoom, ZOOM_MAX) - 2;
}
private _locate_subscription: Subscription | null = null;
/**
* Subscribes to location changes to update the position on initialization.
*/
ngOnInit(){
this._locate_subscription = this.geocode.OnPositionChanged.subscribe(
() => {
this.UpdatePosition();
});
}
/**
* Updates the map position after the view initializes.
*/
ngAfterViewInit(){
this.UpdatePosition();
}
/**
* Unsubscribes from location updates on component destruction.
*/
ngOnDestroy(){
super.OnDestroy();
if (this._locate_subscription){
this._locate_subscription.unsubscribe();
this._locate_subscription = null;
}
}
/**
* Emits an event when the distance or accuracy changes.
*/
@Output() changeEvent = new EventEmitter<any>();
private UpdatePosition(){
Iif (!this._googlemap){
setTimeout(() => {
this.UpdatePosition()
}, 250);
}
else {
let _center: Coordinates = {
lat: 0,
lng: 0
};
if (this._center){
_center = this._center;
}
this._distance = this.geocode.DistanceTo(_center);
this._mapinfo.markers[0].position = {
lat: this._center?.lat || 0,
lng: this._center?.lng || 0
}
this._mapinfo.markers[1].position = {
lat: this.geocode.CurrentPosition.coordinates.lat,
lng: this.geocode.CurrentPosition.coordinates.lng,
}
this._mapinfo.position = {
lng: (this._mapinfo.markers[0].position.lng + this._mapinfo.markers[1].position.lng) / 2,
lat: (this._mapinfo.markers[0].position.lat + this._mapinfo.markers[1].position.lat) / 2,
}
this._mapinfo.zoom = this.BoundsZoomLevel(
this._mapinfo.markers[0].position,
this._mapinfo.markers[1].position
);
this.changeEvent.emit({
accuracy: this.geocode.CurrentPosition.accuracy,
distance: this._distance
});
}
}
/**
* Event emitted when the component is closed.
*/
@Output() closeEvent = new EventEmitter<any>();
/**
* Emits the `closeEvent` to notify listeners that the component should close.
*/
OnClose(){
this.closeEvent.emit();
}
}
|