fix: add better error handling for initMap

This commit is contained in:
log101 2024-02-06 20:45:14 +03:00
parent e062b4a577
commit 6a90866d56
4 changed files with 115 additions and 61 deletions

View File

@ -6,6 +6,7 @@ import { useEffect, useState } from "react"
import "../styles/locked-content.css" import "../styles/locked-content.css"
import type { Generated } from "kysely" import type { Generated } from "kysely"
import { onLocationError } from "@/lib/error"
const incrementCounter = async (id: string | Generated<string>) => const incrementCounter = async (id: string | Generated<string>) =>
await fetch(`${import.meta.env.PUBLIC_HOME_URL}/api/content/increment?id=${id}`) await fetch(`${import.meta.env.PUBLIC_HOME_URL}/api/content/increment?id=${id}`)
@ -26,6 +27,7 @@ const LocationButton = ({
const [distanceRemain, setDistanceRemain] = useState<string>("") const [distanceRemain, setDistanceRemain] = useState<string>("")
const targetCoordinates = JSON.parse(location).coordinates const targetCoordinates = JSON.parse(location).coordinates
const targetPos = { const targetPos = {
lat: targetCoordinates[0], lat: targetCoordinates[0],
lng: targetCoordinates[1] lng: targetCoordinates[1]
@ -57,7 +59,7 @@ const LocationButton = ({
setAtTarget(true) setAtTarget(true)
} }
}, },
() => null, err => onLocationError(err),
{ enableHighAccuracy: true, timeout: 27000, maximumAge: 10000 } { enableHighAccuracy: true, timeout: 27000, maximumAge: 10000 }
) )
@ -96,8 +98,7 @@ const LocationButton = ({
<Button <Button
size='lg' size='lg'
className='text-lg p-6 animate-pulse bg-indigo-600 hover:bg-indigo-700 hover:animate-none border-2 border-indigo-800' className='text-lg p-6 animate-pulse bg-indigo-600 hover:bg-indigo-700 hover:animate-none border-2 border-indigo-800'
onClick={handleUnlock} onClick={handleUnlock}>
>
<LockOpen1Icon className='mr-2 h-4 w-4' /> <LockOpen1Icon className='mr-2 h-4 w-4' />
İçeriğin Kilidi ıldı İçeriğin Kilidi ıldı
</Button> </Button>
@ -129,8 +130,7 @@ const LocationButton = ({
<Button <Button
size='sm' size='sm'
className='bg-green-700 hover:bg-green-600 text-md' className='bg-green-700 hover:bg-green-600 text-md'
onClick={() => startWatchingLocation()} onClick={() => startWatchingLocation()}>
>
Konum İzni Ver Konum İzni Ver
</Button> </Button>
</div> </div>

31
src/lib/error.ts Normal file
View File

@ -0,0 +1,31 @@
export function onLocationError(err: GeolocationPositionError) {
let errorMessage
switch (err.code) {
case 1:
errorMessage = "Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin."
break
case 2:
errorMessage = "Konumunuz tespit edilemedi, lütfen biraz sonra tekrar deneyiniz."
break
case 3:
errorMessage = "Konum isteği zaman aşımına uğradı, lütfen sayfayı yenileyip tekrar deneyiniz."
break
default:
errorMessage = "Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin."
break
}
// @ts-ignore
Toastify({
text: errorMessage,
duration: 3000,
gravity: "top", // `top` or `bottom`
position: "center", // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: "black",
borderRadius: "6px",
margin: "16px"
},
onClick: function () {} // Callback after click
}).showToast()
}

View File

@ -1,29 +1,11 @@
import { remoteLog } from "@/lib/utils";
const data = JSON.parse(document.getElementById('map').dataset.targetLocation) const data = JSON.parse(document.getElementById('map').dataset.targetLocation)
const TARGET_LOCATION = data.coordinates const TARGET_LOCATION = data.coordinates
let watchId = -1;
function startWatchingLocation() { function startWatchingLocation() {
watchId = navigator.geolocation.watchPosition( map.locate({ watch: true })
(position) => {
console.log('watching')
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
if (currentLocationMarker) {
currentLocationMarker.setLatLng(pos);
} else {
currentLocationMarker = L.marker(pos, { icon: currentLocationIcon });
currentLocationMarker.addTo(map);
}
},
() => null,
{ enableHighAccuracy: true, timeout: 27000, maximumAge: 10000 }
)
console.log('trying', watchId)
} }
var map = L.map('map').setView(TARGET_LOCATION, 13); var map = L.map('map').setView(TARGET_LOCATION, 13);
@ -55,12 +37,60 @@ var currentLocationIcon = L.icon({
let currentLocationMarker; let currentLocationMarker;
function onLocationError(e) { function onLocationError(err) {
alert(e.message); let errorMessage;
switch (err.code) {
case 1:
errorMessage = 'Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.'
break;
case 2:
errorMessage = 'Konumunuz tespit edilemedi, lütfen biraz sonra tekrar deneyiniz.'
break;
case 3:
errorMessage = 'Konum isteği zaman aşımına uğradı, lütfen sayfayı yenileyip tekrar deneyiniz.'
break;
default:
errorMessage = 'Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.'
break;
}
// @ts-ignore
Toastify({
text: errorMessage,
duration: 3000,
gravity: 'top', // `top` or `bottom`
position: 'center', // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: 'black',
borderRadius: '6px',
margin: '16px',
},
onClick: function () { }, // Callback after click
}).showToast();
}
function onLocationSuccess(locationEvent) {
const position = locationEvent.latlng
const currentPos = {
lat: position.lat,
lng: position.lng
}
if (currentLocationMarker) {
currentLocationMarker.setLatLng(currentPos);
} else {
currentLocationMarker = L.marker(currentPos, { icon: currentLocationIcon });
currentLocationMarker.addTo(map);
}
} }
map.on('locationerror', onLocationError); map.on('locationerror', onLocationError);
map.on('locationfound', onLocationSuccess)
L.Control.GoToCurrentLocation = L.Control.extend({ L.Control.GoToCurrentLocation = L.Control.extend({
onAdd: function (map) { onAdd: function (map) {
const locationButton = document.createElement('button'); const locationButton = document.createElement('button');
@ -69,24 +99,38 @@ L.Control.GoToCurrentLocation = L.Control.extend({
locationButton.classList.add('custom-map-control-button'); locationButton.classList.add('custom-map-control-button');
locationButton.name = 'select-location-button' locationButton.type = 'button'
locationButton.addEventListener('click', () => { locationButton.addEventListener('click', (ev) => {
if (watchId === -1) { if (locationButton.textContent != 'Konumuma Git') {
startWatchingLocation() startWatchingLocation()
locationButton.textContent = 'Konumuma Git'; locationButton.textContent = 'Konumuma Git';
} else { } else {
console.log(currentLocationMarker) if (currentLocationMarker) {
map.setView(currentLocationMarker.getLatLng(), 12); map.setView(currentLocationMarker.getLatLng(), 12);
} else {
// @ts-ignore
Toastify({
text: 'Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.',
duration: 3000,
gravity: 'top', // `top` or `bottom`
position: 'center', // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: 'black',
borderRadius: '6px',
margin: '16px',
},
onClick: function () { }, // Callback after click
}).showToast();
}
} }
}); L.DomEvent.stopPropagation(ev)
})
return locationButton; return locationButton;
}, },
onRemove: function (map) {
// Nothing to do here
},
}); });
L.Control.GoToTargetLocation = L.Control.extend({ L.Control.GoToTargetLocation = L.Control.extend({
@ -102,11 +146,7 @@ L.Control.GoToTargetLocation = L.Control.extend({
}); });
return locationButton; return locationButton;
}, }
onRemove: function (map) {
// Nothing to do here
},
}); });
L.control.currentLocation = function (opts) { L.control.currentLocation = function (opts) {

View File

@ -1,3 +1,4 @@
import { onLocationError } from "@/lib/error";
import { remoteLog } from "@/lib/utils"; import { remoteLog } from "@/lib/utils";
var map = L.map('map').setView([41.024857599001905, 28.940787550837882], 10); var map = L.map('map').setView([41.024857599001905, 28.940787550837882], 10);
@ -28,24 +29,6 @@ function startWatchingLocation() {
map.locate({ watch: true }) map.locate({ watch: true })
} }
function onLocationError() {
// @ts-ignore
Toastify({
text: 'Konum izni alınamadı, lütfen tarayıcınızın ve cihazınızın gizlilik ayarlarını kontrol edin.',
duration: 3000,
gravity: 'top', // `top` or `bottom`
position: 'center', // `left`, `center` or `right`
stopOnFocus: true, // Prevents dismissing of toast on hover
style: {
background: 'black',
borderRadius: '6px',
margin: '16px',
},
onClick: function () { }, // Callback after click
}).showToast();
}
function onLocationSuccess(locationEvent) { function onLocationSuccess(locationEvent) {
const position = locationEvent.latlng const position = locationEvent.latlng