如何使用 Angular 2 或 TypeScript 获取访问者位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43088193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:23:42  来源:igfitidea点击:

How to get visitors location using Angular 2 or TypeScript

angulartypescript

提问by Americo Arvani

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.

我开始ServerVariables["HTTP_CF_IPCOUNTRY"]通过后端服务器使用 get by ,但它太慢了,为此我需要一个 Angular 或 TypeScript 解决方案。

回答by Vivek Doshi

If you wanted to take location from front-end side , we can get the location simply via javascript

如果你想从前端获取位置,我们可以简单地通过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

在 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));
            };
        }
    }
}

回答by Americo Arvani

Found solution using Vivek example.

使用 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;
                }
            }
        );
    };
}