HTML5 makes extremely easy getting the position of the user device, e.g. browser. The API itself uses various sources of location information as GPS, IP address, WiFi, GSM, Bluetooth. Let me show you how to detect a device location with few lines javascript.
CHECK BROWSER SUPPORT
Before to proceed with it is a good practice to check if the browser supports HTML5 Geolocation API.
if (navigator.geolocation) { // supported }
which is equivalent to:
if ('geolocation' in navigator) { // supported }
GETTING CURRENT POSITION
To get the current location of a user device, use the
getCurrentPosition()
method. It takes up to three arguments as follow:- successCallback – Callback function that is called asynchronously if the attempt to obtain the current location of the device is successful.
- errorCallback – (optional) A callback function that is invoked asynchronously if the attempt to obtain the current location of the device fails.
- options – (optional) Accepts next three properties: enableHighAccuracy, timeout, maximumAge.
function successCallback (position) { console.log(position.coords.latitude); // 43.2132209 console.log(position.coords.longitude); // 27.9571503 } navigator.geolocation.getCurrentPosition(successCallback);
Calling the
getCurrentPosition()
forces the browser to displays a confirmation dialog, in which asks the visitor for permission as shown below:Giving a permission will display a icon in the address bar as shown below:
Blocking the request will display a icon in the address bar as shown below:
ERROR HANDLING
The error callback function is invoked asyncronously when the attempt of getting the position fails. It takes one argument – an object with the reason for the failure.
function errorCallback (error) { console.log(error.message); } navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
WATCHING THE POSITION
To track position updates use the
watchPosition()
method. It takes up to three arguments (successCallback, errorCallback, options). Returns a unique identifier of a watch operation.var watchId = navigator.geolocation.watchPosition(successCallback);
STOP THE WATCH PROCESS
To stop watching for the device current position use the
clearWatch()
method. It takes one argument – the identifier of a watch operation.navigator.geolocation.clearWatch(watchId);
BROWSER COMPATIBILITY
IE 9+, Edge 12+, Firefox 3.5+, Chrome 5+, Safari 5+, Opera 16+
Recently Google Chrome discontinue the support of getCurrentPosition() and watchPosition() on insecure origins.
CONCLUSION
Various industries could benefit as for example: accommodations, real estate, travel, transportation, tourism, food & beverage, auto, classified ads, retail, security, sport. A lot of applications could use coordinates to show nearby amenities, hotels, restaurants, gas stations. The apps could show user’s daily route and the current position at any time.