Skip to content

Instantly share code, notes, and snippets.

@FelipeBarrosCruz
Last active November 14, 2017 10:36
Show Gist options
  • Save FelipeBarrosCruz/5a69cb77488c7d9139dd7b3ddb78dc5b to your computer and use it in GitHub Desktop.
Save FelipeBarrosCruz/5a69cb77488c7d9139dd7b3ddb78dc5b to your computer and use it in GitHub Desktop.
import { first, find } from 'lodash'
export interface IGeoLocationModel {
lat: string
lng: string
country: string
parseGoogleMapResponse(result: object): void
}
export class GeoLocationModel implements IGeoLocationModel {
public lat: string
public lng: string
public country: string
constructor(position) {
if (position && position.coords) {
this.lat = position.coords.latitude
this.lng = position.coords.longitude
}
}
parseGoogleMapResponse(response): void {
if (response.status !== 'OK' || !Array.isArray(response.results) || !response.results.length) {
return
}
const country = first(response.results).address_components.find((address) => {
return Array.isArray(address.types) && address.types.indexOf('country') !== -1
})
this.country = country && country.long_name && country.long_name.toLowerCase() || undefined
}
}
import { Injectable } from '@angular/core'
import { HttpClient } from '@angular/common/http'
import { merge } from 'lodash'
import { GeoLocationModel } from 'app/models/geolocation.model'
import { environment } from '../../environments/environment'
export interface IGeoLocationService {
getLocation(): Promise<GeoLocationModel>
}
@Injectable()
export class GeoLocationService implements IGeoLocationService {
private navigator: Navigator = navigator;
private baseGoogleUrl = environment.googleMapUrl
constructor(private http: HttpClient) {
if (!this.navigator.geolocation) {
console.error('Geolocation disabled')
}
}
getLocation(): Promise<GeoLocationModel> {
return new Promise((resolve, reject) => {
this.getFullLocation()
.then((location: GeoLocationModel) => resolve(location))
.catch(reject)
})
}
private async getFullLocation() {
try {
const location: GeoLocationModel = await this.getCountry(await this.getCurrentLocation())
return Promise.resolve(location)
} catch (err) {
return Promise.reject(err)
}
}
private getCurrentLocation(): Promise<GeoLocationModel> {
return new Promise((resolve, reject) => {
try {
this.navigator.geolocation.getCurrentPosition((position) => {
resolve(new GeoLocationModel(position))
})
} catch (err) {
return reject(err)
}
})
}
private getCountry(location: GeoLocationModel): Promise<GeoLocationModel> {
return new Promise((resolve, reject) => {
const url = this.baseGoogleUrl.concat(`&latlng=${location.lat},${location.lng}`)
this.http.get(url).subscribe((response) => {
location.parseGoogleMapResponse(response)
return resolve(location)
}, reject)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment