The Navigator object belongs to Window object and contains information about the browser and the operating system on which the browser is running. It defines a number of properties and methods, the main one being the userAgent property representing the user’s browser:
document.write(navigator.userAgent);//Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36
You can use the geolocation property of the Navigator object to get the geographic location of the user. The getCurrentPosition() method is used to get the position. This method takes two parameters: a function that fires on success, and a function that fires on a geodata request failure:
function success(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; var altitude = position.coords.altitude; var speed = position.coords.speed; document.write("Latitude: " + latitude); document.write("Longitude: " + longitude); document.write("Altitude: " + altitude); document.write("User speed: " + speed); }; function error(obj) { document.write("Error"); }; navigator.geolocation.getCurrentPosition(success, error);
The user’s position is passed to the function, which is executed when the geodata is successfully determined, in the form of the position parameter. The passed object has a coords nested object, which property can be used to get the user’s immediate coordinates.
!be aware that browsers have a security policy that, when calling the geolocation.getCurrentPosition() method, displays a message to the user in which the user can confirm the sending of geographic coordinates. If the user refuses, then the error() function will be triggered.