我开始在后端服务器上使用get ServerVariables["HTTP_CF_IPCOUNTRY"]
,但速度太慢,我需要一个Angular或TypeScript解决方案。
答案 0 :(得分:19)
如果您想从前端获取位置,我们只需通过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;
}
这将要求用户从浏览器共享该位置,并完成它。
在Angular 2 Component中实现OnInit,将该代码放在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));
};
}
}
}
答案 1 :(得分:9)
使用Vivek示例找到解决方案。
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;
}
}
);
};
}