How to Get User Location Information with Javascript

With the advent of HTML5 it is now possible to retrieve the current geographical location of the user. This is achieved by using the Geolocation API.

Demo

Geolocation API Requires HTTPS

Since this API fetches the location of a user, very accurately in devices with built-in GPS, it is important that the privacy and security of the user is not compromised. Hence the Geolocation API will work only over secure networks (HTTPS).

For testing purposes, it will work on HTTP on the localhost environment. Browsers consider localhost as secure.

Geolocation API Requires User Permission

The location data of the user is related to privacy, so the use of Geolocation API requires the user's permission. It is up to the user to provide or deny access to the Geolocation API.

The Geolocation API

The Geolocation API is available through the navigator.geolocation object.

To get the location of the user, the method getCurrentPosition is called.

navigator.geolocation.getCurrentPosition(locationSuccess);

// callback invoked when location data is fetched
function locationSuccess(position) {
	var details = position.coords;
	
	// fetches latitude
	console.log("Latitude: " + details.latitude);
	
	// fetches longitude
	console.log("Longitude: " + details.longitude);
	
	// fetches accuracy of location (in metres)
	console.log("Accuracy: " + details.accuracy);
}

An object is passed to the callback function of getCurrentPosition method that contains the following location data :

  • coords : This contains another object which has the following data in it :

    • latitude : Latitude of the location from the API in decimal format
    • longitude : Longitude of the location from the API in decimal format
    • accuracy : Accuracy of the location from the API in meters
    • alitude : Altitude of the location in meters from the sea level
    • altitudeAccuracy : Accuracy of the altitude in meters
    • heading : Direction of travel of the device in degrees
    • speed : The speed of the device in meters per second
  • timestamp : Timestamp in milliseconds denoting the time when the location of the device was resolved

Error Handling

The second parameter of the getCurrentPosition method is another callback function meant to handle errors that may occur while trying to resolve the location of the user. A Javascript Error object is passed as its parameter.

navigator.geolocation.getCurrentPosition(locationSuccess, locationError);

// location fetched successfully
function locationSuccess(position) {
	console.log(position.coords);
}

// location fetching failed
function locationError(error) {
	console.log("Error Code: " + error.code);
	console.log("Error Message: " + error.message);
}

There can be 3 types of error codes that may be retuned :

  • 1 : User did not give permission
  • 2 : Geolocation could not be fetched
  • 3 : Time taken to get location exceeded the given timeout time

How Geolocation works

In the most basic scenario the location of an user is determined using the IP Address of the said user. Each ISP is allocated a block of IP Addresses depending on it's region of operation. So based on this information the approximate location of an user is determined. The accuracy here is limited to the city of operation of the ISP the said user is using.

Similarly in Wi-Fi based Geolocation, the location of the user is determined on the basis of the Wi-Fi access point the user is connected to. Based on the WiFi signal, fingerprinting and Wi-Fi triangulation the location of the user is determined fairly accurately.

The most accurate location data comes from devices with built-in GPS modules. In this case the Geolocation API queries the hardware, which in turn communicates with the GPS satellites and receives a very accurate information regarding the location of the user. If a website is using Geolocation API and an user is browsing from a mobile device with GPS turned on, the website will get a very accurate location data of the user.

Getting Location with High Accuracy

It is also possible to get a fairly accurate position of the user (if the device is capable of that). Keep in mind that it may take more time to fetch the location of the user, and increases battery usage.

To obtain the location with high accuracy, a third parameter is passed to the getCurrentPosition method. This contains the various options that can be passed. The property enableHighAccuracy in this options object can be set to true to get a high accuracy location.

navigator.geolocation.getCurrentPosition(locationSuccess, locationError, { enableHighAccuracy: true });

Setting a Timeout

In some cases the Geolocation API may take a long time to get the location data. To handle this situation you can set the timeout property in the options parameter. This should be set as milliseconds. After this timeout exceeds, the error callback will be called.

// wait for 10 seconds max
navigator.geolocation.getCurrentPosition(locationSuccess, locationError, { timeout: 10000 });

By default the browser will keep on waiting for an infinite amount of time, till location data comes up. So it is better to set this option.

Caching Results

Once the location data is fetched, you may sometimes like to cache it for future use. This may be beneficial in some cases.

You can set the cache time through the maximumAge property in the options parameter. This is also set in milliseconds.

// cache results for 30 seconds
navigator.geolocation.getCurrentPosition(locationSuccess, locationError, { maximumAge: 300000 });

The default value is 0 — browser will get the current location every time.

Detecting Change in Location

If the device is on the move, then the location needs to be updated regularly. This is achieved by using watchPosition method. This method accepts the same parameters as getCurrentPosition. The only difference is the callback functions are called multiple times, allowing the browser to update the location as the device moves.

The watchPosition method returns an ID. This ID can also be used with clearWatch method to stop updating the user's location.

var posID = navigator.geolocation.watchPosition(locationSuccess, locationError);

// this will be called whenever position changes
function locationSuccess(position) {
	
}

// error callback
function locationError(error) {
	
}

// stop updating the location
navigator.geolocation.clearWatch(posID);
Loading Comments