In typescript working with angular 6,
i needed to make a async function which respond with current countryCode based on users geoLocation.
So here I am using nevigator get the current lat lng.
Its not possible to get the country code directly from nevigator. SO i needed googleMapsApi
By using import { MapsAPILoader } from ‘@agm/core’;
I am able to get the address_components from google responce and filtering it to get the current country Short name.
This is a am going to use in
ng2TelInput => https://www.npmjs.com/package/ng2-tel-input
which is used to add dial code in phone number but requires country code to auto populate.
See the GITHUB:
https://github.com/shakalya195/geolocationService
Make an service with async method.
import { MapsAPILoader } from ‘@agm/core’;
// import {} from ‘googlemaps’;
declare const google: any;
@Injectable({
providedIn: ‘root’
})
export class GeolocationService {
constructor(
private mapsAPILoader: MapsAPILoader,
) { }
async getCurrentCountry(){
return await new Promise((resolve,reject)=>{
if (‘geolocation’ in navigator) {
navigator.geolocation.getCurrentPosition( async (position) => {
// console.log(position);
this.mapsAPILoader.load().then(() => {
const geocoder = new google.maps.Geocoder();
const latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
const request = { latLng: latlng };
geocoder.geocode(request, (results, status) => {
if (status === google.maps.GeocoderStatus.OK) {
// console.log(results);
let address_components = results[0].address_components;
let address = address_components.filter(r=>{
if(r.types[0] == ‘country’){
return r;
}
}).map(r=>{
return r.short_name;
})
// console.log(address);
resolve(address[0]);
}
});
});
});
}else{
/* default return */
return ‘SA’;
}
})
}
}