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) {
    console.log(error.message);
}

navigator.geolocation.getCurrentPosition(successCallback,errorCallback);
  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);
navigator.geolocation.clearWatch(watchId);
date2019-04-15 17:00:32 From:www.jquerypluginhub.com Author:JPH
Related Tags:
Comments

Leave a Reply

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