Reuse the existing Mapbox token instead of maintaining a separate Bing Maps key. Note the coordinate order flips to lon,lat for the Mapbox geocoding endpoint.
50 lines
1.3 KiB
TypeScript
50 lines
1.3 KiB
TypeScript
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<ILocation | null> {
|
|
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<string> {
|
|
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<GeolocationPosition | null> {
|
|
return new Promise((resolve, reject) => {
|
|
if (!('geolocation' in navigator)) {
|
|
resolve(null)
|
|
return
|
|
}
|
|
navigator.geolocation.getCurrentPosition(resolve, reject)
|
|
})
|
|
}
|
|
}
|
|
|
|
export default new MapService()
|