import ILocation from '@/models/ILocation' import ILocationQuery from '@/models/ILocationQuery' class MapService { private token: string = import.meta.env.VITE_MAPBOX_KEY || '' public async getPosition(): Promise { const position = await this.getCurrentPosition() if (!position) { return null } const { coords } = position const location = { lat: coords.latitude, lon: coords.longitude } const place = await this.getPlace(location) return { ...location, place } } public async getPlace(location: ILocation): Promise { const result = await fetch(this.url(location.lat, location.lon)) if (!result) { return '' } const json: ILocationQuery = await result.json() return json?.features?.[0]?.text ?? '' } private url(latitude: number, longitude: number) { return `https://api.mapbox.com/geocoding/v5/mapbox.places/${longitude},${latitude}.json?types=place&limit=1&access_token=${this.token}` } private getCurrentPosition(): Promise { return new Promise((resolve, reject) => { if (!('geolocation' in navigator)) { resolve(null) return } navigator.geolocation.getCurrentPosition(resolve, reject) }) } } export default new MapService()