Get current country in angular 5 using geolocation
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
import { Injectable } from '@angular/core'; 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'; } }) } } |