import ILocation from '@/models/ILocation' import ILocationQuery from '@/models/ILocationQuery' class MapService { private key: string = import.meta.env.VITE_MAP_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() if ( !json || !json.resourceSets || !json.resourceSets.length || !json.resourceSets[0].resources.length ) { return '' } const address = json.resourceSets[0].resources[0].address return address ? address.locality : '' } private url(latitude: number, longitude: number) { return `https://dev.virtualearth.net/REST/v1/Locations/${latitude},${longitude}?key=${this.key}` } private getCurrentPosition(): Promise { return new Promise((resolve, reject) => { if (!('geolocation' in navigator)) { resolve(null) return } navigator.geolocation.getCurrentPosition(resolve, reject) }) } } export default new MapService()