Categories

Detecting device location with JavaScript

Posted on: July 16, 2016 by Dimitar Ivanov

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.

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.

If you have any questions about the HTML5 Geolocation,
leave a comment below. And do not be shy to share this article. Thanks so much
for reading.

Dimitar Ivanov

Dimitar Ivanov is a senior LAMP developer, javascript engineer, web performance-obsessed.
He is programming since 2003 and loves to build web applications.
You can find him on Twitter,
LinkedIn and
GitHub.

Subscribe to our newsletter

Join our mailing list and stay tuned! Never miss out news about Zino UI, new releases, or even blog post.