I started use get by ServerVariables["HTTP_CF_IPCOUNTRY"]
by backend server, but it is too slow, I need an Angular or TypeScript solution for this.
Angular 2 Development with Typescript introduces Angular 2 to developers comfortable using AngularJS v1 or other web frameworks. You'll start by exploring how Angular 2 works in an online auction application. Along the way, you'll learn to use TypeScript to write type-aware classes, interfaces, and generics.
It is, however, worth noting that Angular 2 fully supports the use of TypeScript instead of restricting users to plain JavaScript. TypeScript is a programming language that's a superset of JavaScript.
TypeScript is a typed super set of JavaScript which has been built and maintained by Microsoft and chosen by the AngularJS team for development. The presence of types makes the code written in TypeScript less prone to run-time errors.
One of the useful ways of getting your user location is by the use of IP address lookup although it may not be entirely free depending the API. Some very good APIs for this operation are http://ip-api.com/, https://ipinfo.io, geoip-db.com and many others.
If you wanted to take location from front-end side , we can get the location simply via javascript
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
This will ask user from browser to share the location , and its done.
More Details.
In Angular 2 Component implements OnInit , put that code inside ngOnInit
import { Component, OnInit } from '@angular/core';
export class LocationComponent implements OnInit {
ngOnInit(){
if(window.navigator.geolocation){
window.navigator.geolocation.getCurrentPosition(this.setPosition.bind(this));
};
}
}
}
Found solution using Vivek example.
ngOnInit() {
if (window.navigator && window.navigator.geolocation) {
window.navigator.geolocation.getCurrentPosition(
position => {
this.geolocationPosition = position,
console.log(position)
},
error => {
switch (error.code) {
case 1:
console.log('Permission Denied');
break;
case 2:
console.log('Position Unavailable');
break;
case 3:
console.log('Timeout');
break;
}
}
);
};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With