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

标签 angular typescript

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

最佳答案

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

这将要求用户从浏览器共享位置,然后就完成了。

More Details .

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

关于angular - 如何使用 Angular 2 或 TypeScript 获取访问者位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43088193/

相关文章:

javascript - 当 % 字符出现在 url 中时出现问题

javascript - Typescript:使用 .map 时如何保留长度信息

javascript - Cytoscape.js 警告 : "The style value of ` label` is deprecated for `width` "when trying to have a node with same width of label

angular - 延迟/反跳浏览器重新加载 Angular2

angular - 对于使用 loadChildren 进行的 angular2 路由器延迟加载,服务不是单例的

angular - url angular 2 中的 Http Post 参数

javascript - 如何将ISO8601 json转换为正常日期格式

javascript - SVG 渲染按钮在调整大小 Highcharts 上重新定位

javascript - Angular 2在同一页面中一个接一个地引导两个应用程序

javascript - System.config() 调用 <head> 或 <body>?