Breaking

Thursday, August 29, 2019

[Solved] How to get current location of user using javascript?(Example code)

current location using javascript

How to get the current location of a user using javascript?


You might think to get a user's location is a difficult task, but it's quite easy.

JavaScript offers a simple, yet powerful tool for locating devices in the form of the HTML5 Geolocation API.


It consists of three services:


  • GPS - primarily on mobile devices, very accurate up to 10 meters.
  • WiFi - available on most internet-connected devices, also very accurate.
  • IP geolocation - limited to region and often times unreliable, used as a worst-case scenario when the other two fail.


When geo data is requested the browser will try and use all three of the above options depending on what's available. The results from the WiFi source are usually used as it is quicker than GPS and way more accurate than IP geolocation.

  • the following code will return you longitude and latitude of the user.

(1)

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};

function success(pos) {
  var crd = pos.coords;

  console.log('Your current position is:');
  console.log(`Latitude : ${crd.latitude}`);
  console.log(`Longitude: ${crd.longitude}`);
  console.log(`More or less ${crd.accuracy} meters.`);
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}

navigator.geolocation.getCurrentPosition(success, error, options);


(2) How to get City name and other important parameters using lat and long

var options = {
  enableHighAccuracy: true,
  timeout: 5000,
  maximumAge: 0
};
var response;
var City;

function success(pos) {
var crd = pos.coords;
Lat = (`${crd.latitude}`);
longi = (`${crd.longitude}`);

const Http = new XMLHttpRequest();
const url="https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?location="+longi+"%2C"+Lat+"&langCode=fr&outSR=&forStorage=false&f=pjson";

Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
response = Http.responseText
}
Jresponse = JSON.parse(response)
City = Jresponse.address.City
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);



RESPONSE - 

{
 "address": {
  "Match_addr": "411032",
  "LongLabel": "411032, IND",
  "ShortLabel": "411032",
  "Addr_type": "Postal",
  "Type": "",
  "PlaceName": "411032",
  "AddNum": "",
  "Address": "",
  "Block": "",
  "Sector": "",
  "Neighborhood": "",
  "District": "",
  "City": "Pune",
  "MetroArea": "",
  "Subregion": "Pune",
  "Region": "Maharashtra",
  "Territory": "",
  "Postal": "411032",
  "PostalExt": "",
  "CountryCode": "IND"
 },
 "location": {
  "x": 73.924213699999996,
  "y": 18.570302899999998,
  "spatialReference": {
   "wkid": 4326,
   "latestWkid": 4326
  }
 }

}



This code will only return longitude and latitude if the user allows his/her location. If a user has denied location, you won't be able to get a user's current location.

(3)

<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>
<script>
function geoFindMe() {

  const status = document.querySelector('#status');
  const mapLink = document.querySelector('#map-link');

  mapLink.href = '';
  mapLink.textContent = '';

  function success(position) {
    const latitude  = position.coords.latitude;
    const longitude = position.coords.longitude;

    status.textContent = '';
    mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
    mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
  }

  function error() {
    status.textContent = 'Unable to retrieve your location';
  }

  if (!navigator.geolocation) {
    status.textContent = 'Geolocation is not supported by your browser';
  } else {
    status.textContent = 'Locating…';
    navigator.geolocation.getCurrentPosition(success, error);
  }

}

document.querySelector('#find-me').addEventListener('click', geoFindMe);


</script>

Since the Geolocation API exposes deeply personal information, when an application tries to access it for the first time, a dialog pops up requesting permission. This ensures that users will not have their private data revealed unless they explicitly allow it.

Browser support

The majority of browsers now support the Geolocation API but it's a good practice to always check for support before you do anything.


You can easily check for compatibility by testing for the presence of the geolocation object:

// check for Geolocation support
if (navigator.geolocation) {
  console.log('Geolocation is supported!');
}
else {
  console.log('Geolocation is not supported for this Browser/OS.');
}


  • Another way to get location using ISP is as follows which will give you user location without the need of allowing or deny (How to get Ip of user)


(1)

https://ipapi.co/json/

$.getJSON('https://ipapi.co/json/', function(data) {
  console.log(JSON.stringify(data, null, 2));
});


Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "country": "SG",
  "country_name": "Singapore",
  "postal": null,
  "latitude": 1.2855,
  "longitude": 103.8565,
  "timezone": "Asia/Singapore"
}

Limitations:

1,000 requests per day
Requires SSL (https)

(2)

https://api.ipdata.co

$.getJSON('https://api.ipdata.co', function(data) {
  console.log(JSON.stringify(data, null, 2));
});
Returns:

{
  "ip": "116.12.250.1",
  "city": "Singapore",
  "region": "Central Singapore Community Development Council",
  "region_code": "01",
  "country_name": "Singapore",
  "country_code": "SG",
  "continent_name": "Asia",
  "continent_code": "AS",
  "latitude": 1.2931,
  "longitude": 103.8558,
  "asn": "AS3758",
  "organisation": "SingNet",
  "postal": "",
  "calling_code": "65",
  "flag": "https://ipdata.co/flags/sg.png",
  "emoji_flag": "\ud83c\uddf8\ud83c\uddec",
  "emoji_unicode": "U+1F1F8 U+1F1EC",
  "is_eu": false,
  "languages": [
    {
      "name": "English",
      "native": "English"
    },
    {
      "name": "Malay",
      "native": "Bahasa Melayu"
    },
    {
      "name": "Tamil",
      "native": "\u0ba4\u0bae\u0bbf\u0bb4\u0bcd"
    },
    {
      "name": "Chinese",
      "native": "\u4e2d\u6587"
    }
  ],
  "currency": {
    "name": "Singapore Dollar",
    "code": "SGD",
    "symbol": "S$",
    "native": "$",
    "plural": "Singapore dollars"
  },
  "time_zone": {
    "name": "Asia/Singapore",
    "abbr": "+08",
    "offset": "+0800",
    "is_dst": false,
    "current_time": "2018-05-09T12:28:49.183674+08:00"
  },
  "threat": {
    "is_tor": false,
    "is_proxy": false,
    "is_anonymous": false,
    "is_known_attacker": false,
    "is_known_abuser": false,
    "is_threat": false,
    "is_bogon": false
  }
}

Limitations:

1,500 requests per day
Requires an email address to get your API key

Requires SSL (https)


Getting the actual current location of a user without allowing is quite impossible without hack which is illegal and against privacy and rules of Google.

No comments:

Post a Comment

Featured Post

[Solved] How to get current location of user using javascript?(Example code)

How to get the current location of a user using javascript? You might think to get a user's location is a difficult task, but it&...

Popular Posts