How to detect the device location with js

The HTML API uses various sources of location information as GPS, IP address, WiFi, GSM, Bluetooth to get the position of the device.

All you need to do is just writing a few lines of code.

  1. check if the browser supports HTML5 Geolocation API.

if (navigator.geolocation) {
    // supported
  1. use the method getCurrentPosition to get the device position.

// called asynchronously if the attempt to obtain the current location of the device is successful.
function successCallback (position) {
    console.log(position.coords.latitude); // 43.2132209
    console.log(position.coords.longitude); // 27.9571503
// invoked asyncronously when the attempt of getting the position fails.
function errorCallback (error) {

  1. when the code runs,there will alert a confirm dialog ask for permission.Giving the permission will display a icon in the address bar of browser.

4.You can use watchPosition()method to track the position updates and clearWatch() method to stop the watch process

var watchId = navigator.geolocation.watchPosition(successCallback);
date2019-04-15 17:00:32 Author:JPH
Related Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *