Americo Arvani
Americo Arvani

Reputation: 858

How to get visitors location using Angular 2 or TypeScript

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.

Upvotes: 9

Views: 20866

Answers (2)

Vivek Doshi
Vivek Doshi

Reputation: 58543

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

Upvotes: 24

Americo Arvani
Americo Arvani

Reputation: 858

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

Upvotes: 12

Related Questions