From 859d74056a44bf105d18357ffcf283006d20f7ff Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Wed, 11 Mar 2026 15:29:43 +0700 Subject: [PATCH 01/47] fix track mock location --- src/components/AscGISMap.vue | 275 +++++++++++------------ src/composables/useLocationValidation.ts | 89 ++++++-- 2 files changed, 206 insertions(+), 158 deletions(-) diff --git a/src/components/AscGISMap.vue b/src/components/AscGISMap.vue index 81da108..d78b1bc 100644 --- a/src/components/AscGISMap.vue +++ b/src/components/AscGISMap.vue @@ -32,7 +32,7 @@ const apiKey = ref( ) const zoomMap = ref(18) -async function initializeMap() { +async function initializeMap(position: GeolocationPosition) { try { // Load modules of ArcGIS loadModules([ @@ -43,159 +43,146 @@ async function initializeMap() { 'esri/Graphic', 'esri/layers/TileLayer', ]).then(async ([esriConfig, Map, MapView, Point, Graphic, TileLayer]) => { - // Set apiKey - // esriConfig.apiKey = - // 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP' - - // Create a FeatureLayer using a custom server URL - // const hillshadeLayer = new TileLayer({ - // url: `https://bmagis.bangkok.go.th/arcgis/rest/services/cache/BMA_3D_2D_Cache/MapServer`, - // }) - const map = new Map({ basemap: 'streets', - // basemap: 'arcgis-topographic', - // layers: [hillshadeLayer], }) - navigator.geolocation.getCurrentPosition(async (position) => { - const { latitude, longitude } = position.coords + const { latitude, longitude } = position.coords - const mapView = new MapView({ - container: 'mapViewDisplay', - map: map, - center: { - latitude: latitude, - longitude: longitude, - }, // Set the initial map center current position + const mapView = new MapView({ + container: 'mapViewDisplay', + map: map, + center: { + latitude: latitude, + longitude: longitude, + }, // Set the initial map center current position - zoom: zoomMap.value, - constraints: { - snapToZoom: false, // Disables snapping to the zoom level - minZoom: zoomMap.value, // Set minimum zoom level - maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom) - }, + zoom: zoomMap.value, + constraints: { + snapToZoom: false, // Disables snapping to the zoom level + minZoom: zoomMap.value, // Set minimum zoom level + maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom) + }, - ui: { - components: [], // Empty array to remove all default UI components - }, - }) + ui: { + components: [], // Empty array to remove all default UI components + }, + }) - // ตำแหน่งของผู้ใช้ - const userPoint = new Point({ longitude, latitude }) - const userSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/red.png', - width: '32px', - height: '32px', - } - const userGraphic = new Graphic({ - geometry: userPoint, - symbol: userSymbol, - }) - mapView.graphics.add(userGraphic) - // Get POI place ยิงไปขอที่ server ของกทม.ก่อน - await axios - .get( - 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/', - { - params: { - f: 'json', // Format JSON response - distance: 2000, - category: 'POI', - location: { - spatialReference: { wkid: 4326 }, - x: longitude, - y: latitude, - }, - token: apiKey.value, + // ตำแหน่งของผู้ใช้ + const userPoint = new Point({ longitude, latitude }) + const userSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/red.png', + width: '32px', + height: '32px', + } + const userGraphic = new Graphic({ + geometry: userPoint, + symbol: userSymbol, + }) + mapView.graphics.add(userGraphic) + // Get POI place ยิงไปขอที่ server ของกทม.ก่อน + await axios + .get( + 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/', + { + params: { + f: 'json', // Format JSON response + distance: 2000, + category: 'POI', + location: { + spatialReference: { wkid: 4326 }, + x: longitude, + y: latitude, }, - } - ) - .then((response) => { - // console.log('poi', response.data.location) - poiPlaceName.value = response.data.address - ? response.data.address.PlaceName === '' - ? response.data.address.ShortLabel - : response.data.address.PlaceName - : 'ไม่พบข้อมูล' - const poiPoint = new Point({ - longitude: response.data.location.x, - latitude: response.data.location.y, - }) - const poiSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', - width: '32px', - height: '32px', - } - const poiGraphic = new Graphic({ - geometry: poiPoint, - symbol: poiSymbol, - }) - mapView.graphics.add(poiGraphic) - // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI - mapView.goTo({ - target: [userPoint, poiPoint], - zoom: zoomMap.value, - }) - - updateLocation(latitude, longitude, poiPlaceName.value) + token: apiKey.value, + }, + } + ) + .then((response) => { + // console.log('poi', response.data.location) + poiPlaceName.value = response.data.address + ? response.data.address.PlaceName === '' + ? response.data.address.ShortLabel + : response.data.address.PlaceName + : 'ไม่พบข้อมูล' + const poiPoint = new Point({ + longitude: response.data.location.x, + latitude: response.data.location.y, }) - .catch(async (error) => { - // console.error('Error fetching points of interest:', error) - // Get POI place ยิงไปขอที่ server arcgis ไม่ต้องใช้ token - await axios - .get( - 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', - { - params: { - f: 'json', // Format JSON response - distance: 2000, - category: 'POI', - location: { - spatialReference: { wkid: 4326 }, - x: longitude, - y: latitude, - }, + const poiSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', + width: '32px', + height: '32px', + } + const poiGraphic = new Graphic({ + geometry: poiPoint, + symbol: poiSymbol, + }) + mapView.graphics.add(poiGraphic) + // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI + mapView.goTo({ + target: [userPoint, poiPoint], + zoom: zoomMap.value, + }) + + updateLocation(latitude, longitude, poiPlaceName.value) + }) + .catch(async (error) => { + // console.error('Error fetching points of interest:', error) + // Get POI place ยิงไปขอที่ server arcgis ไม่ต้องใช้ token + await axios + .get( + 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', + { + params: { + f: 'json', // Format JSON response + distance: 2000, + category: 'POI', + location: { + spatialReference: { wkid: 4326 }, + x: longitude, + y: latitude, }, - } - ) - .then((response) => { - // console.log('poi', response.data.location) - poiPlaceName.value = response.data.address - ? response.data.address.PlaceName === '' - ? response.data.address.ShortLabel - : response.data.address.PlaceName - : 'ไม่พบข้อมูล' - const poiPoint = new Point({ - longitude: response.data.location.x, - latitude: response.data.location.y, - }) - const poiSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', - width: '32px', - height: '32px', - } - const poiGraphic = new Graphic({ - geometry: poiPoint, - symbol: poiSymbol, - }) - mapView.graphics.add(poiGraphic) - // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI - mapView.goTo({ - target: [userPoint, poiPoint], - zoom: zoomMap.value, - }) + }, + } + ) + .then((response) => { + // console.log('poi', response.data.location) + poiPlaceName.value = response.data.address + ? response.data.address.PlaceName === '' + ? response.data.address.ShortLabel + : response.data.address.PlaceName + : 'ไม่พบข้อมูล' + const poiPoint = new Point({ + longitude: response.data.location.x, + latitude: response.data.location.y, + }) + const poiSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', + width: '32px', + height: '32px', + } + const poiGraphic = new Graphic({ + geometry: poiPoint, + symbol: poiSymbol, + }) + mapView.graphics.add(poiGraphic) + // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI + mapView.goTo({ + target: [userPoint, poiPoint], + zoom: zoomMap.value, + }) - updateLocation(latitude, longitude, poiPlaceName.value) - }) - .catch((error) => { - // console.error('Error fetching points of interest:', error) - }) - }) - }) + updateLocation(latitude, longitude, poiPlaceName.value) + }) + .catch((error) => { + // console.error('Error fetching points of interest:', error) + }) + }) }) } catch (error) { console.error('Error loading the map', error) @@ -236,7 +223,7 @@ const requestLocationPermission = () => { } // Check for critical errors (invalid coordinates) that prevent showing location - const hasCriticalErrors = validationResult.errors.some(error => + const hasCriticalErrors = validationResult.errors.some((error) => error.includes('พิกัดตำแหน่งไม่ถูกต้อง') ) @@ -261,7 +248,7 @@ const requestLocationPermission = () => { // Center map on user's location if map is initialized if (privacyStore.isAccepted) { - await initializeMap() + await initializeMap(position) } }, (error) => { diff --git a/src/composables/useLocationValidation.ts b/src/composables/useLocationValidation.ts index 27222df..2522d07 100644 --- a/src/composables/useLocationValidation.ts +++ b/src/composables/useLocationValidation.ts @@ -23,6 +23,7 @@ export const VALIDATION_CONFIG = { MAX_SPEED_MS: 100, // 100 m/s (~360 km/h) - maximum plausible movement speed POSITION_HISTORY_SIZE: 5, // number of positions to keep for pattern detection MOCK_INDICATOR_THRESHOLD: 3, // threshold for mock detection (indicators >= 3 = mock) + SUSPICIOUS_ACCURACY_MAX: 5, // accuracy ≤ 5m AND integer = suspicious (real GPS never rounds to whole number) } as const export function useLocationValidation() { @@ -31,17 +32,26 @@ export function useLocationValidation() { // Thai error messages - exported for i18n consistency const errorMessages = { - MOCK_DETECTED: 'ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง กรุณาปิดแอปจำลองตำแหน่งและลองใหม่', + MOCK_DETECTED: + 'ตรวจพบว่าตำแหน่ง GPS อาจไม่ถูกต้อง กรุณาปิดแอปจำลองตำแหน่งและลองใหม่', INVALID_COORDINATES: 'พิกัดตำแหน่งไม่ถูกต้อง กรุณาลองใหม่', STALE_TIMESTAMP: 'ข้อมูลตำแหน่งเก่าเกินไป กรุณารับสัญญาณ GPS ใหม่', POOR_ACCURACY: 'ความแม่นยำตำแหน่งต่ำเกินไป กรุณาตรวจสอบการรับสัญญาณ GPS', - IMPOSSIBLE_SPEED: 'ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง', + IMPOSSIBLE_SPEED: + 'ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง', + SUSPICIOUS_ACCURACY: 'ตรวจพบค่าความแม่นยำที่ผิดปกติ อาจเป็นการจำลองตำแหน่ง', + DUPLICATE_POSITION: 'ตรวจพบพิกัดตำแหน่งซ้ำกัน อาจเป็นการจำลองตำแหน่ง', } const previousPositions = ref([]) // คำนวณระยะห่างระหว่าง 2 จุด (Haversine formula) - const haversineDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => { + const haversineDistance = ( + lat1: number, + lon1: number, + lat2: number, + lon2: number + ): number => { const R = 6371e3 // Earth's radius in meters const φ1 = (lat1 * Math.PI) / 180 const φ2 = (lat2 * Math.PI) / 180 @@ -59,9 +69,12 @@ export function useLocationValidation() { // ตรวจสอบพิกัดถูกต้อง const validateCoordinates = (lat: number, lon: number): boolean => { return ( - lat >= -90 && lat <= 90 && - lon >= -180 && lon <= 180 && - !isNaN(lat) && !isNaN(lon) && + lat >= -90 && + lat <= 90 && + lon >= -180 && + lon <= 180 && + !isNaN(lat) && + !isNaN(lon) && !(lat === 0 && lon === 0) // Mock มักใช้ 0,0 ) } @@ -80,20 +93,49 @@ export function useLocationValidation() { } // คำนวณความเร็ว - const calculateSpeed = (pos1: PositionSnapshot, pos2: PositionSnapshot): number => { - const distance = haversineDistance(pos1.latitude, pos1.longitude, pos2.latitude, pos2.longitude) + const calculateSpeed = ( + pos1: PositionSnapshot, + pos2: PositionSnapshot + ): number => { + const distance = haversineDistance( + pos1.latitude, + pos1.longitude, + pos2.latitude, + pos2.longitude + ) const timeDiff = Math.abs(pos2.timestamp - pos1.timestamp) / 1000 // seconds return timeDiff > 0 ? distance / timeDiff : 0 } // ตรวจสอบความเร็วปกติ - const validateSpeed = (current: PositionSnapshot, previous: PositionSnapshot): boolean => { + const validateSpeed = ( + current: PositionSnapshot, + previous: PositionSnapshot + ): boolean => { const speed = calculateSpeed(previous, current) return speed <= VALIDATION_CONFIG.MAX_SPEED_MS } + // ตรวจสอบค่าความแม่นยำที่ผิดปกติ (mock apps มักรายงานค่าที่เป็นเลขจำนวนเต็มสวยงาม เช่น 5.0, 3.0) + const hasSuspiciousPerfectAccuracy = (accuracy: number | null): boolean => { + if (accuracy === null) return false + return ( + Number.isInteger(accuracy) && + accuracy <= VALIDATION_CONFIG.SUSPICIOUS_ACCURACY_MAX + ) + } + + // ตรวจสอบพิกัดซ้ำกันทุกค่า (real GPS มีการสั่นเล็กน้อย mock app มักคืนพิกัดเดิมซ้ำ) + const hasDuplicateCoordinates = (lat: number, lon: number): boolean => { + return previousPositions.value.some( + (p) => p.latitude === lat && p.longitude === lon + ) + } + // Main validation function - const validateLocation = (position: GeolocationPosition): LocationValidationResult => { + const validateLocation = ( + position: GeolocationPosition + ): LocationValidationResult => { const warnings: string[] = [] const errors: string[] = [] let mockIndicators = 0 @@ -121,7 +163,8 @@ export function useLocationValidation() { // 4. Compare with previous positions if (previousPositions.value.length > 0) { - const previous = previousPositions.value[previousPositions.value.length - 1] + const previous = + previousPositions.value[previousPositions.value.length - 1] if (!validateSpeed({ latitude, longitude, timestamp }, previous)) { errors.push(errorMessages.IMPOSSIBLE_SPEED) @@ -129,14 +172,32 @@ export function useLocationValidation() { } } + // 5. Suspiciously perfect accuracy — real GPS never rounds to a whole-number ≤ 5m + if (hasSuspiciousPerfectAccuracy(accuracy)) { + warnings.push(errorMessages.SUSPICIOUS_ACCURACY) + mockIndicators += 2 + } + + // 6. Exact duplicate coordinates — real GPS always drifts slightly between readings + if ( + previousPositions.value.length > 0 && + hasDuplicateCoordinates(latitude, longitude) + ) { + warnings.push(errorMessages.DUPLICATE_POSITION) + mockIndicators += 2 + } + // Store current position previousPositions.value.push({ latitude, longitude, timestamp }) - if (previousPositions.value.length > VALIDATION_CONFIG.POSITION_HISTORY_SIZE) { + if ( + previousPositions.value.length > VALIDATION_CONFIG.POSITION_HISTORY_SIZE + ) { previousPositions.value.shift() } // Determine result - const isMockDetected = mockIndicators >= VALIDATION_CONFIG.MOCK_INDICATOR_THRESHOLD + const isMockDetected = + mockIndicators >= VALIDATION_CONFIG.MOCK_INDICATOR_THRESHOLD const isValid = errors.length === 0 let confidence: 'low' | 'medium' | 'high' = 'low' @@ -154,7 +215,7 @@ export function useLocationValidation() { const showMockWarning = (result: LocationValidationResult) => { if (!result.isMockDetected) return - messageError($q, null, errorMessages.MOCK_DETECTED) + messageError($q, '', errorMessages.MOCK_DETECTED) } const resetValidation = () => { From 3ae6e6eeaced6f3ab07996c178c0c92dd7a9ad9e Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Wed, 11 Mar 2026 17:44:39 +0700 Subject: [PATCH 02/47] fix fack location complated --- src/components/AscGISMap.vue | 66 ++++++--- src/composables/useLocationValidation.ts | 25 ++++ src/stores/mixin.ts | 178 +++++++++++------------ src/views/HomeView.vue | 133 ++++++++++++++++- 4 files changed, 287 insertions(+), 115 deletions(-) diff --git a/src/components/AscGISMap.vue b/src/components/AscGISMap.vue index d78b1bc..7ed48a7 100644 --- a/src/components/AscGISMap.vue +++ b/src/components/AscGISMap.vue @@ -16,7 +16,32 @@ const mapElement = ref(null) const emit = defineEmits(['update:location', 'locationStatus', 'mockDetected']) const $q = useQuasar() -const { validateLocation, showMockWarning } = useLocationValidation() +const { validateLocation } = useLocationValidation() +const MOCK_CHECK_DELAY_MS = 800 + +function wait(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +function getCurrentPositionAsync(options?: PositionOptions) { + return new Promise((resolve, reject) => { + navigator.geolocation.getCurrentPosition(resolve, reject, options) + }) +} + +async function getPositionForValidation(fallback: GeolocationPosition) { + await wait(MOCK_CHECK_DELAY_MS) + try { + return await getCurrentPositionAsync({ + enableHighAccuracy: true, + timeout: 10000, + maximumAge: 0, + }) + } catch (error) { + // Keep the original reading if the second sampling fails. + return fallback + } +} function updateLocation(latitude: number, longitude: number, namePOI: string) { // ส่ง event ไปยัง parent component เพื่ออัพเดทค่า props @@ -24,6 +49,7 @@ function updateLocation(latitude: number, longitude: number, namePOI: string) { } const poiPlaceName = ref('') // ชื่อพื้นที่ใกล้เคียง +const isMapReady = ref(false) // Replace ArcGIS api key const apiKey = ref( @@ -68,6 +94,7 @@ async function initializeMap(position: GeolocationPosition) { components: [], // Empty array to remove all default UI components }, }) + isMapReady.value = true // ตำแหน่งของผู้ใช้ const userPoint = new Point({ longitude, latitude }) @@ -180,7 +207,9 @@ async function initializeMap(position: GeolocationPosition) { updateLocation(latitude, longitude, poiPlaceName.value) }) .catch((error) => { - // console.error('Error fetching points of interest:', error) + // Keep map visible even when POI lookup fails. + poiPlaceName.value = 'ไม่พบข้อมูล' + updateLocation(latitude, longitude, poiPlaceName.value) }) }) }) @@ -213,13 +242,16 @@ const requestLocationPermission = () => { navigator.geolocation.getCurrentPosition( async (position) => { - // Validate location first - const validationResult = validateLocation(position) + const sampledPosition = await getPositionForValidation(position) - // Always emit mockDetected event (regardless of result) + // Validate location first + const validationResult = validateLocation(sampledPosition) + + // Do not block map preview on initial mock detection. + // The hard-stop warning is enforced at submit time in HomeView. if (validationResult.isMockDetected) { - showMockWarning(validationResult) - emit('mockDetected', validationResult) + locationGranted.value = true + emit('locationStatus', true) } // Check for critical errors (invalid coordinates) that prevent showing location @@ -234,11 +266,11 @@ const requestLocationPermission = () => { return } - // Permission granted based on mock detection - locationGranted.value = !validationResult.isMockDetected - emit('locationStatus', !validationResult.isMockDetected) + // Permission granted for map preview state. + locationGranted.value = true + emit('locationStatus', true) - const { latitude, longitude } = position.coords + const { latitude, longitude } = sampledPosition.coords // console.log('Current position:', latitude, longitude) if (!latitude || !longitude) { @@ -248,7 +280,7 @@ const requestLocationPermission = () => { // Center map on user's location if map is initialized if (privacyStore.isAccepted) { - await initializeMap(position) + await initializeMap(sampledPosition) } }, (error) => { @@ -279,7 +311,7 @@ const requestLocationPermission = () => { break } }, - { enableHighAccuracy: true } + { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } ) } @@ -291,7 +323,7 @@ defineExpose({ diff --git a/src/composables/useLocationValidation.ts b/src/composables/useLocationValidation.ts index 2522d07..689af41 100644 --- a/src/composables/useLocationValidation.ts +++ b/src/composables/useLocationValidation.ts @@ -24,6 +24,13 @@ export const VALIDATION_CONFIG = { POSITION_HISTORY_SIZE: 5, // number of positions to keep for pattern detection MOCK_INDICATOR_THRESHOLD: 3, // threshold for mock detection (indicators >= 3 = mock) SUSPICIOUS_ACCURACY_MAX: 5, // accuracy ≤ 5m AND integer = suspicious (real GPS never rounds to whole number) + // Geographic service area (Thailand) to reduce spoofing risk from remote fake coordinates. + SERVICE_AREA: { + MIN_LAT: 5.0, + MAX_LAT: 21.0, + MIN_LON: 97.0, + MAX_LON: 106.0, + }, } as const export function useLocationValidation() { @@ -41,6 +48,8 @@ export function useLocationValidation() { 'ตรวจพบการเคลื่อนที่ด้วยความเร็วผิดปกติ อาจเป็นการจำลองตำแหน่ง', SUSPICIOUS_ACCURACY: 'ตรวจพบค่าความแม่นยำที่ผิดปกติ อาจเป็นการจำลองตำแหน่ง', DUPLICATE_POSITION: 'ตรวจพบพิกัดตำแหน่งซ้ำกัน อาจเป็นการจำลองตำแหน่ง', + OUT_OF_SERVICE_AREA: + 'ตรวจพบตำแหน่งนอกพื้นที่ใช้งานของระบบ กรุณาปิดแอปจำลองตำแหน่งและลองใหม่', } const previousPositions = ref([]) @@ -132,6 +141,16 @@ export function useLocationValidation() { ) } + const isWithinServiceArea = (lat: number, lon: number): boolean => { + const area = VALIDATION_CONFIG.SERVICE_AREA + return ( + lat >= area.MIN_LAT && + lat <= area.MAX_LAT && + lon >= area.MIN_LON && + lon <= area.MAX_LON + ) + } + // Main validation function const validateLocation = ( position: GeolocationPosition @@ -149,6 +168,12 @@ export function useLocationValidation() { mockIndicators += 3 } + // 1.1 Service-area validation (critical for remote spoofed coordinates) + if (!isWithinServiceArea(latitude, longitude)) { + errors.push(errorMessages.OUT_OF_SERVICE_AREA) + mockIndicators += 3 + } + // 2. Timestamp validation if (!validateTimestamp(timestamp)) { errors.push(errorMessages.STALE_TIMESTAMP) diff --git a/src/stores/mixin.ts b/src/stores/mixin.ts index 3ff5636..fffa00c 100644 --- a/src/stores/mixin.ts +++ b/src/stores/mixin.ts @@ -5,6 +5,56 @@ import { logout } from '@/plugins/auth' import { format, utcToZonedTime } from 'date-fns-tz' export const useCounterMixin = defineStore('mixin', () => { + let activeErrorDialog: any = null + + const clearActiveErrorDialog = () => { + if (!activeErrorDialog) return + try { + if (typeof activeErrorDialog.hide === 'function') { + activeErrorDialog.hide() + } else if (typeof activeErrorDialog.destroy === 'function') { + activeErrorDialog.destroy() + } + } finally { + activeErrorDialog = null + } + } + + const openSingleErrorDialog = ( + q: any, + message: string, + onCancel?: () => void | Promise + ) => { + clearActiveErrorDialog() + + const dialog = q.dialog({ + component: CustomComponent, + componentProps: { + title: `พบข้อผิดพลาด`, + message, + icon: 'warning', + color: 'red', + onlycancel: true, + }, + }) + + activeErrorDialog = dialog + + dialog.onDismiss(() => { + if (activeErrorDialog === dialog) { + activeErrorDialog = null + } + }) + + if (onCancel) { + dialog.onCancel(() => { + void onCancel() + }) + } + + return dialog + } + function date2Thai(srcDate: Date, isFullMonth = false, isTime = false) { if (srcDate == null) { return null @@ -133,53 +183,30 @@ export const useCounterMixin = defineStore('mixin', () => { } const messageError = (q: any, e: any = '', msg: string = '') => { - // q.dialog.hide(); + // Keep only one active warning popup to prevent dialog overlap. if (e.response !== undefined) { if (e.response.data.status !== undefined) { if (e.response.data.status == 401) { //invalid_token - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: `ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง`, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }).onCancel(async () => { - showLoader() - await logout() - setTimeout(() => { - hideLoader() - }, 1000) - }) + openSingleErrorDialog( + q, + 'ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง', + async () => { + showLoader() + await logout() + setTimeout(() => { + hideLoader() + }, 1000) + } + ) } else { const message = e.response.data.result ?? e.response.data.message - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: `${message}`, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }) + openSingleErrorDialog(q, `${message}`) } } else { if (e.response.status == 401) { if (msg !== '') { - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: msg, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }).onCancel(async () => { + openSingleErrorDialog(q, msg, async () => { showLoader() await logout() setTimeout(() => { @@ -188,70 +215,35 @@ export const useCounterMixin = defineStore('mixin', () => { }) } else { //invalid_token - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: `ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง`, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }).onCancel(async () => { - showLoader() - await logout() - setTimeout(() => { - hideLoader() - }, 1000) - }) + openSingleErrorDialog( + q, + 'ล็อกอินหมดอายุ กรุณาล็อกอินใหม่อีกครั้ง', + async () => { + showLoader() + await logout() + setTimeout(() => { + hideLoader() + }, 1000) + } + ) } } else if (e.response.data.successful === false) { - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: e.response.data.message, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }) + openSingleErrorDialog(q, e.response.data.message) } else { - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: `ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์`, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }) + openSingleErrorDialog( + q, + 'ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์' + ) } } } else { if (msg !== '') { - return q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: msg, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }) + return openSingleErrorDialog(q, msg) } - q.dialog({ - component: CustomComponent, - componentProps: { - title: `พบข้อผิดพลาด`, - message: `ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์`, - icon: 'warning', - color: 'red', - onlycancel: true, - }, - }) + openSingleErrorDialog( + q, + 'ข้อมูลผิดพลาดทำให้เกิดการไม่ตอบสนองต่อการเรียกใช้งานดูเว็บไซต์' + ) } } diff --git a/src/views/HomeView.vue b/src/views/HomeView.vue index 379b970..43c14c0 100644 --- a/src/views/HomeView.vue +++ b/src/views/HomeView.vue @@ -8,6 +8,7 @@ import config from '@/app.config' import http from '@/plugins/http' import { useCounterMixin } from '@/stores/mixin' import { usePermissions } from '@/composables/usePermissions' +import { useLocationValidation } from '@/composables/useLocationValidation' import { usePrivacyStore } from '@/stores/privacy' import type { FormRef, OptionReason } from '@/interface/response/checkin' @@ -18,7 +19,10 @@ const mixin = useCounterMixin() const { date2Thai, showLoader, hideLoader, messageError, dialogConfirm } = mixin const $q = useQuasar() const { checkPrivacyAccepted } = usePermissions() +const { validateLocation, showMockWarning, resetValidation } = + useLocationValidation() const privacyStore = usePrivacyStore() +const MOCK_CHECK_DELAY_MS = 800 const modalTime = ref(false) // Dailog ลงเวลาเข้างานของคุณ const checkStatus = ref('') @@ -120,14 +124,110 @@ async function updateLocation( */ function onLocationStatus(status: boolean) { locationGranted.value = status + if (status) { + isMockLocationDetected.value = false + } } /** * รับค่า mock location detection จาก AscGISMap */ function onMockDetected(result: any) { - isMockLocationDetected.value = true - disabledBtn.value = true + isMockLocationDetected.value = !!result?.isMockDetected + disabledBtn.value = false +} + +function resetLocationForRetry() { + locationGranted.value = false + formLocation.lat = 0 + formLocation.lng = 0 + formLocation.POI = '' +} + +function getCurrentPositionAsync(options?: PositionOptions) { + return new Promise((resolve, reject) => { + navigator.geolocation.getCurrentPosition(resolve, reject, options) + }) +} + +function wait(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)) +} + +async function getDelayedFreshPosition() { + const firstPosition = await getCurrentPositionAsync({ + enableHighAccuracy: true, + timeout: 10000, + maximumAge: 0, + }) + + await wait(MOCK_CHECK_DELAY_MS) + + try { + return await getCurrentPositionAsync({ + enableHighAccuracy: true, + timeout: 10000, + maximumAge: 0, + }) + } catch (error) { + return firstPosition + } +} + +async function revalidateLocationBeforeSubmit() { + if (!navigator.geolocation) { + messageError( + $q, + '', + 'ไม่สามารถระบุตำแหน่งปัจจุบันได้ เบราว์เซอร์ของคุณไม่รองรับ Geolocation' + ) + return false + } + + try { + // If previous attempt was mock, clear history so fresh GPS is not compared + // against spoofed coordinates and incorrectly flagged as impossible speed. + if (isMockLocationDetected.value) { + resetValidation() + } + + const position = await getDelayedFreshPosition() + + const validationResult = validateLocation(position) + + if (validationResult.isMockDetected) { + isMockLocationDetected.value = true + disabledBtn.value = false + resetValidation() + resetLocationForRetry() + showMockWarning(validationResult) + mapRef.value?.requestLocationPermission() + return false + } + + if (validationResult.errors.length > 0) { + disabledBtn.value = false + resetValidation() + resetLocationForRetry() + messageError($q, '', validationResult.errors[0]) + mapRef.value?.requestLocationPermission() + return false + } + + locationGranted.value = true + isMockLocationDetected.value = false + return true + } catch (error) { + disabledBtn.value = false + resetLocationForRetry() + messageError( + $q, + '', + 'ไม่สามารถตรวจสอบตำแหน่งล่าสุดก่อนลงเวลาได้ กรุณาลองใหม่อีกครั้ง' + ) + mapRef.value?.requestLocationPermission() + return false + } } const location = ref('') // พื้นที่ใกล้เคียง @@ -348,7 +448,7 @@ const objectRef: FormRef = { } /** function ตรวจสอบค่าว่างของ input*/ -function validateForm() { +async function validateForm() { const hasError = [] for (const key in objectRef) { if (Object.prototype.hasOwnProperty.call(objectRef, key)) { @@ -360,6 +460,11 @@ function validateForm() { } } if (hasError.every((result) => result === true)) { + const isLocationValid = await revalidateLocationBeforeSubmit() + if (!isLocationValid) { + return + } + if (statusCheckin.value == false) { getCheck() } else if (statusCheckin.value) { @@ -397,6 +502,12 @@ async function confirm() { mapRef.value?.requestLocationPermission() return } + + const isLocationValid = await revalidateLocationBeforeSubmit() + if (!isLocationValid) { + return + } + disabledBtn.value = true showLoader() const isLocation = workplace.value === 'in-place' //*true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง @@ -1016,7 +1127,13 @@ watch( push size="18px" :class="$q.screen.gt.xs ? 'q-px-md' : 'full-width q-pa-sm'" - :disable="disabledBtn || !locationGranted || isMockLocationDetected ? true : camera && img ? false : true" + :disable=" + disabledBtn || !locationGranted || isMockLocationDetected + ? true + : camera && img + ? false + : true + " @click="validateForm" :loading="inQueue" /> @@ -1131,7 +1248,13 @@ watch( push size="18px" :class="$q.screen.gt.xs ? 'q-px-md' : 'full-width q-pa-sm'" - :disable="disabledBtn || !locationGranted || isMockLocationDetected ? true : camera && img ? false : true" + :disable=" + disabledBtn || !locationGranted || isMockLocationDetected + ? true + : camera && img + ? false + : true + " @click="validateForm" :loading="inQueue" /> From 33da60ec026ced73776f13b72c5749713efe277a Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Thu, 12 Mar 2026 00:51:22 +0700 Subject: [PATCH 03/47] =?UTF-8?q?fix=20disable=20=E0=B8=9B=E0=B8=B8?= =?UTF-8?q?=E0=B9=88=E0=B8=A1=E0=B8=A5=E0=B8=87=E0=B9=80=E0=B8=A7=E0=B8=A5?= =?UTF-8?q?=E0=B8=B2=E0=B8=81=E0=B8=A3=E0=B8=93=E0=B8=B5=E0=B9=80=E0=B8=84?= =?UTF-8?q?=E0=B8=A3=E0=B8=B7=E0=B9=88=E0=B8=AD=E0=B8=87=E0=B8=8A=E0=B9=89?= =?UTF-8?q?=E0=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/views/HomeView.vue | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/views/HomeView.vue b/src/views/HomeView.vue index 43c14c0..7021e65 100644 --- a/src/views/HomeView.vue +++ b/src/views/HomeView.vue @@ -449,6 +449,8 @@ const objectRef: FormRef = { /** function ตรวจสอบค่าว่างของ input*/ async function validateForm() { + disabledBtn.value = true + const hasError = [] for (const key in objectRef) { if (Object.prototype.hasOwnProperty.call(objectRef, key)) { @@ -480,11 +482,15 @@ async function validateForm() { model.value === 'อื่นๆ' ? useLocation.value : model.value })` } คุณต้องการยืนยันการลงเวลาเข้างาน?`, - () => {}, + () => { + disabledBtn.value = false + }, 'red', 'ยืนยัน' ) } + } else { + disabledBtn.value = false } } @@ -495,10 +501,12 @@ const timeChickin = ref('') //เวลาเข้างาน,เว async function confirm() { // เช็คสิทธิ์ privacy ก่อนใช้งานแผนที่และกล้อง if (!checkPrivacyAccepted()) { + disabledBtn.value = false return } if (!formLocation.POI || !formLocation.lat || !formLocation.lng) { + disabledBtn.value = false mapRef.value?.requestLocationPermission() return } @@ -508,7 +516,6 @@ async function confirm() { return } - disabledBtn.value = true showLoader() const isLocation = workplace.value === 'in-place' //*true คือ ณ สถานที่ตั้ง, false คือ นอกสถานที่ตั้ง const locationName = workplace.value === 'in-place' ? '' : useLocation.value @@ -551,6 +558,7 @@ async function confirm() { async function getCheck() { if (!formLocation.POI || !formLocation.lat || !formLocation.lng) { + disabledBtn.value = false mapRef.value?.requestLocationPermission() return } @@ -583,7 +591,9 @@ async function getCheck() { () => confirm(), 'ยืนยันการลงเวลาออกงาน', `เวลาออกจากงานของคุณคือ ${endTimeAfternoonVal} แต่ขณะนี้เป็นเวลา ${timeVal} น. หากคุณออกจากงานในเวลานี้สถานะการลงเวลาจะเป็น "${res.data.result.statusText}" คุณแน่ใจว่าจะลงเวลาออกงานในตอนนี้ใช่หรือไม่?`, - () => {}, + () => { + disabledBtn.value = false + }, 'red', 'ยืนยัน' ) @@ -592,6 +602,7 @@ async function getCheck() { } }) .catch((e) => { + disabledBtn.value = false messageError($q, e) }) .finally(() => { From e2f22cc9c056c5eacabbdc7427fb0888d9ed4b35 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Wed, 25 Mar 2026 11:06:00 +0700 Subject: [PATCH 04/47] fix --- src/components/DialogDebug.vue | 5 ++++- src/components/FooterContact.vue | 13 +++++++++++++ src/views/MainView.vue | 6 ++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 src/components/FooterContact.vue diff --git a/src/components/DialogDebug.vue b/src/components/DialogDebug.vue index 5fa1f3f..ab55a0e 100644 --- a/src/components/DialogDebug.vue +++ b/src/components/DialogDebug.vue @@ -11,6 +11,7 @@ import http from '@/plugins/http' import config from '@/app.config' import DialogHeader from '@/components/DialogHeader.vue' +import FooterContact from '@/components/FooterContact.vue' const $q = useQuasar() const store = usePositionKeycloakStore() @@ -343,7 +344,9 @@ function onClose() { - + + + +
+ + + พบปัญหาการใช้งานกรุณาติดต่อผู้ดูแลระบบ + 088-264-9800 + +
+ + + + + diff --git a/src/views/MainView.vue b/src/views/MainView.vue index eda5edc..e34ab53 100644 --- a/src/views/MainView.vue +++ b/src/views/MainView.vue @@ -17,6 +17,7 @@ import { usePositionKeycloakStore } from '@/stores/positionKeycloak' import DialogHeader from '@/components/DialogHeader.vue' import PopupPrivacy from '@/components/PopupPrivacy.vue' import DialogDebug from '@/components/DialogDebug.vue' +import FooterContact from '@/components/FooterContact.vue' const mixin = useCounterMixin() const privacyStore = usePrivacyStore() @@ -561,6 +562,11 @@ onMounted(async () => { + + + + + From 66a48f38302946708ea52af51dcd4f2da33dd864 Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Wed, 25 Mar 2026 11:58:46 +0700 Subject: [PATCH 05/47] fix:tel --- src/components/FooterContact.vue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/components/FooterContact.vue b/src/components/FooterContact.vue index fe21234..025aed3 100644 --- a/src/components/FooterContact.vue +++ b/src/components/FooterContact.vue @@ -3,7 +3,9 @@ พบปัญหาการใช้งานกรุณาติดต่อผู้ดูแลระบบ - 088-264-9800 + 088-264-9800 From fa855b30c84b55f797725f8e3861554f1ef8c07f Mon Sep 17 00:00:00 2001 From: "DESKTOP-1R2VSQH\\Lenovo ThinkPad E490" Date: Wed, 25 Mar 2026 12:12:40 +0700 Subject: [PATCH 06/47] fix:style --- src/components/FooterContact.vue | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/components/FooterContact.vue b/src/components/FooterContact.vue index 025aed3..4df5d53 100644 --- a/src/components/FooterContact.vue +++ b/src/components/FooterContact.vue @@ -4,7 +4,9 @@ พบปัญหาการใช้งานกรุณาติดต่อผู้ดูแลระบบ 088-264-9800088-264-9800 From f53327e2d9b8d71373783d4f5844082c81763d4d Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Fri, 27 Mar 2026 20:57:24 +0700 Subject: [PATCH 07/47] fix on mobile hidden contact --- src/views/MainView.vue | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/views/MainView.vue b/src/views/MainView.vue index e34ab53..c8bc1d8 100644 --- a/src/views/MainView.vue +++ b/src/views/MainView.vue @@ -564,7 +564,10 @@ onMounted(async () => { - + @@ -720,4 +723,8 @@ onMounted(async () => { background-color: #016987; color: #fff; } + +.hidden { + display: none !important; +} From 7edfaa4e4fb50dc12428855d7c329e7b6d9053d9 Mon Sep 17 00:00:00 2001 From: waruneeauy Date: Mon, 30 Mar 2026 10:47:36 +0700 Subject: [PATCH 08/47] fix remove code check fake location --- src/components/AscGISMap.vue | 354 ++++++++++------------- src/components/DialogDebug.vue | 2 +- src/composables/useLocationValidation.ts | 255 ---------------- src/views/HomeView.vue | 125 +------- 4 files changed, 157 insertions(+), 579 deletions(-) delete mode 100644 src/composables/useLocationValidation.ts diff --git a/src/components/AscGISMap.vue b/src/components/AscGISMap.vue index 7ed48a7..7651b7c 100644 --- a/src/components/AscGISMap.vue +++ b/src/components/AscGISMap.vue @@ -5,51 +5,20 @@ import axios from 'axios' import { useCounterMixin } from '@/stores/mixin' import { useQuasar } from 'quasar' import { usePrivacyStore } from '@/stores/privacy' -import { useLocationValidation } from '@/composables/useLocationValidation' const mixin = useCounterMixin() const { messageError } = mixin const privacyStore = usePrivacyStore() -// import type { LocationObject } from '@/interface/index/Main' -const mapElement = ref(null) -const emit = defineEmits(['update:location', 'locationStatus', 'mockDetected']) +const emit = defineEmits(['update:location']) const $q = useQuasar() -const { validateLocation } = useLocationValidation() -const MOCK_CHECK_DELAY_MS = 800 - -function wait(ms: number) { - return new Promise((resolve) => setTimeout(resolve, ms)) -} - -function getCurrentPositionAsync(options?: PositionOptions) { - return new Promise((resolve, reject) => { - navigator.geolocation.getCurrentPosition(resolve, reject, options) - }) -} - -async function getPositionForValidation(fallback: GeolocationPosition) { - await wait(MOCK_CHECK_DELAY_MS) - try { - return await getCurrentPositionAsync({ - enableHighAccuracy: true, - timeout: 10000, - maximumAge: 0, - }) - } catch (error) { - // Keep the original reading if the second sampling fails. - return fallback - } -} - function updateLocation(latitude: number, longitude: number, namePOI: string) { // ส่ง event ไปยัง parent component เพื่ออัพเดทค่า props emit('update:location', latitude, longitude, namePOI) } const poiPlaceName = ref('') // ชื่อพื้นที่ใกล้เคียง -const isMapReady = ref(false) // Replace ArcGIS api key const apiKey = ref( @@ -58,7 +27,7 @@ const apiKey = ref( ) const zoomMap = ref(18) -async function initializeMap(position: GeolocationPosition) { +async function initializeMap() { try { // Load modules of ArcGIS loadModules([ @@ -69,149 +38,159 @@ async function initializeMap(position: GeolocationPosition) { 'esri/Graphic', 'esri/layers/TileLayer', ]).then(async ([esriConfig, Map, MapView, Point, Graphic, TileLayer]) => { + // Set apiKey + // esriConfig.apiKey = + // 'AAPK4f700a4324d04e9f8a1a134e0771ac45FXWawdCl-OotFfr52gz9XKxTDJTpDzw_YYcwbmKDDyAJswf14FoPyw0qBkN64DvP' + + // Create a FeatureLayer using a custom server URL + // const hillshadeLayer = new TileLayer({ + // url: `https://bmagis.bangkok.go.th/arcgis/rest/services/cache/BMA_3D_2D_Cache/MapServer`, + // }) + const map = new Map({ basemap: 'streets', + // basemap: 'arcgis-topographic', + // layers: [hillshadeLayer], }) - const { latitude, longitude } = position.coords + navigator.geolocation.getCurrentPosition(async (position) => { + const { latitude, longitude } = position.coords - const mapView = new MapView({ - container: 'mapViewDisplay', - map: map, - center: { - latitude: latitude, - longitude: longitude, - }, // Set the initial map center current position + const mapView = new MapView({ + container: 'mapViewDisplay', + map: map, + center: { + latitude: latitude, + longitude: longitude, + }, // Set the initial map center current position - zoom: zoomMap.value, - constraints: { - snapToZoom: false, // Disables snapping to the zoom level - minZoom: zoomMap.value, // Set minimum zoom level - maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom) - }, + zoom: zoomMap.value, + constraints: { + snapToZoom: false, // Disables snapping to the zoom level + minZoom: zoomMap.value, // Set minimum zoom level + maxZoom: zoomMap.value, // Set maximum zoom level (same as minZoom for fixed zoom) + }, - ui: { - components: [], // Empty array to remove all default UI components - }, - }) - isMapReady.value = true - - // ตำแหน่งของผู้ใช้ - const userPoint = new Point({ longitude, latitude }) - const userSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/red.png', - width: '32px', - height: '32px', - } - const userGraphic = new Graphic({ - geometry: userPoint, - symbol: userSymbol, - }) - mapView.graphics.add(userGraphic) - // Get POI place ยิงไปขอที่ server ของกทม.ก่อน - await axios - .get( - 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/', - { - params: { - f: 'json', // Format JSON response - distance: 2000, - category: 'POI', - location: { - spatialReference: { wkid: 4326 }, - x: longitude, - y: latitude, - }, - token: apiKey.value, - }, - } - ) - .then((response) => { - // console.log('poi', response.data.location) - poiPlaceName.value = response.data.address - ? response.data.address.PlaceName === '' - ? response.data.address.ShortLabel - : response.data.address.PlaceName - : 'ไม่พบข้อมูล' - const poiPoint = new Point({ - longitude: response.data.location.x, - latitude: response.data.location.y, - }) - const poiSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', - width: '32px', - height: '32px', - } - const poiGraphic = new Graphic({ - geometry: poiPoint, - symbol: poiSymbol, - }) - mapView.graphics.add(poiGraphic) - // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI - mapView.goTo({ - target: [userPoint, poiPoint], - zoom: zoomMap.value, - }) - - updateLocation(latitude, longitude, poiPlaceName.value) + ui: { + components: [], // Empty array to remove all default UI components + }, }) - .catch(async (error) => { - // console.error('Error fetching points of interest:', error) - // Get POI place ยิงไปขอที่ server arcgis ไม่ต้องใช้ token - await axios - .get( - 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', - { - params: { - f: 'json', // Format JSON response - distance: 2000, - category: 'POI', - location: { - spatialReference: { wkid: 4326 }, - x: longitude, - y: latitude, - }, + + // ตำแหน่งของผู้ใช้ + const userPoint = new Point({ longitude, latitude }) + const userSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/red.png', + width: '32px', + height: '32px', + } + const userGraphic = new Graphic({ + geometry: userPoint, + symbol: userSymbol, + }) + mapView.graphics.add(userGraphic) + // Get POI place ยิงไปขอที่ server ของกทม.ก่อน + await axios + .get( + 'https://bmagis.bangkok.go.th/portal/sharing/servers/e4732c3a9fe549ab8bc697573b468f68/rest/services/World/GeocodeServer/reverseGeocode/', + { + params: { + f: 'json', // Format JSON response + distance: 2000, + category: 'POI', + location: { + spatialReference: { wkid: 4326 }, + x: longitude, + y: latitude, }, - } - ) - .then((response) => { - // console.log('poi', response.data.location) - poiPlaceName.value = response.data.address - ? response.data.address.PlaceName === '' - ? response.data.address.ShortLabel - : response.data.address.PlaceName - : 'ไม่พบข้อมูล' - const poiPoint = new Point({ - longitude: response.data.location.x, - latitude: response.data.location.y, - }) - const poiSymbol = { - type: 'picture-marker', - url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', - width: '32px', - height: '32px', - } - const poiGraphic = new Graphic({ - geometry: poiPoint, - symbol: poiSymbol, - }) - mapView.graphics.add(poiGraphic) - // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI - mapView.goTo({ - target: [userPoint, poiPoint], - zoom: zoomMap.value, - }) + token: apiKey.value, + }, + } + ) + .then((response) => { + // console.log('poi', response.data.location) + poiPlaceName.value = response.data.address + ? response.data.address.PlaceName === '' + ? response.data.address.ShortLabel + : response.data.address.PlaceName + : 'ไม่พบข้อมูล' + const poiPoint = new Point({ + longitude: response.data.location.x, + latitude: response.data.location.y, + }) + const poiSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', + width: '32px', + height: '32px', + } + const poiGraphic = new Graphic({ + geometry: poiPoint, + symbol: poiSymbol, + }) + mapView.graphics.add(poiGraphic) + // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI + mapView.goTo({ + target: [userPoint, poiPoint], + zoom: zoomMap.value, + }) - updateLocation(latitude, longitude, poiPlaceName.value) - }) - .catch((error) => { - // Keep map visible even when POI lookup fails. - poiPlaceName.value = 'ไม่พบข้อมูล' - updateLocation(latitude, longitude, poiPlaceName.value) - }) - }) + updateLocation(latitude, longitude, poiPlaceName.value) + }) + .catch(async (error) => { + // console.error('Error fetching points of interest:', error) + // Get POI place ยิงไปขอที่ server arcgis ไม่ต้องใช้ token + await axios + .get( + 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode/', + { + params: { + f: 'json', // Format JSON response + distance: 2000, + category: 'POI', + location: { + spatialReference: { wkid: 4326 }, + x: longitude, + y: latitude, + }, + }, + } + ) + .then((response) => { + // console.log('poi', response.data.location) + poiPlaceName.value = response.data.address + ? response.data.address.PlaceName === '' + ? response.data.address.ShortLabel + : response.data.address.PlaceName + : 'ไม่พบข้อมูล' + const poiPoint = new Point({ + longitude: response.data.location.x, + latitude: response.data.location.y, + }) + const poiSymbol = { + type: 'picture-marker', + url: 'http://maps.google.com/mapfiles/ms/icons/blue.png', + width: '32px', + height: '32px', + } + const poiGraphic = new Graphic({ + geometry: poiPoint, + symbol: poiSymbol, + }) + mapView.graphics.add(poiGraphic) + // อัปเดตการแสดงผลให้แสดงทั้งตำแหน่งของผู้ใช้และ POI + mapView.goTo({ + target: [userPoint, poiPoint], + zoom: zoomMap.value, + }) + + updateLocation(latitude, longitude, poiPlaceName.value) + }) + .catch((error) => { + // console.error('Error fetching points of interest:', error) + }) + }) + }) }) } catch (error) { console.error('Error loading the map', error) @@ -242,35 +221,10 @@ const requestLocationPermission = () => { navigator.geolocation.getCurrentPosition( async (position) => { - const sampledPosition = await getPositionForValidation(position) - - // Validate location first - const validationResult = validateLocation(sampledPosition) - - // Do not block map preview on initial mock detection. - // The hard-stop warning is enforced at submit time in HomeView. - if (validationResult.isMockDetected) { - locationGranted.value = true - emit('locationStatus', true) - } - - // Check for critical errors (invalid coordinates) that prevent showing location - const hasCriticalErrors = validationResult.errors.some((error) => - error.includes('พิกัดตำแหน่งไม่ถูกต้อง') - ) - - if (hasCriticalErrors) { - locationGranted.value = false - emit('locationStatus', false) - messageError($q, '', validationResult.errors[0]) - return - } - - // Permission granted for map preview state. + // Permission granted locationGranted.value = true - emit('locationStatus', true) - const { latitude, longitude } = sampledPosition.coords + const { latitude, longitude } = position.coords // console.log('Current position:', latitude, longitude) if (!latitude || !longitude) { @@ -280,13 +234,12 @@ const requestLocationPermission = () => { // Center map on user's location if map is initialized if (privacyStore.isAccepted) { - await initializeMap(sampledPosition) + await initializeMap() } }, (error) => { // Permission denied locationGranted.value = false - emit('locationStatus', false) switch (error.code) { case error.PERMISSION_DENIED: @@ -311,19 +264,18 @@ const requestLocationPermission = () => { break } }, - { enableHighAccuracy: true, timeout: 10000, maximumAge: 0 } + { enableHighAccuracy: true } ) } defineExpose({ requestLocationPermission, - locationGranted, }) diff --git a/src/components/DialogDebug.vue b/src/components/DialogDebug.vue index ab55a0e..fb151e3 100644 --- a/src/components/DialogDebug.vue +++ b/src/components/DialogDebug.vue @@ -176,7 +176,7 @@ function onClose() {