With the diversity of client access to your site, there is more than one way to figure out where your user is located. Some of those methods include the visitor’s IP address, the cell tower with which the mobile device is communicating, and/or a dedicated GPS hardware component that calculates latitude and longitude information.

Can it be disabled?

Privacy is an important concern when you are considering the process of sharing your physical location with a remote web server. Fortunately, the geolocation API states: “User Agents must not send location information to Web sites without the express permission of the user.” Therefore the user agent (browser/client app) is required to request permission before obtaining the user’s location.

Geolocation API

Geolocation is not a new HTML element but is an API that allows you to share your location with a website. The information is gathered in the form of latitude and longitude data which are available to JavaScript. The geolocation API is supported by most modern browsers such as Internet Explorer 9, Firefox, Chrome, Safari and Opera. It is not supported by earlier versions of Internet Explorer.

Basic Example

The geolocation API focuses on a new property on the global navigator object navigator.geolocation. Here is a simple example of how to use this API:

getCurrentPosition()

The getCurrentPosition() method returns an object if it is successful. The latitude, longitude, and accuracy properties are always returned. The other properties below are returned if available. Only three of the properties are guaranteed to be available. The three properties are coords.latitude, coords.longitude, and coords.accuracy. The remainder of the properties may or may not have values, depending on the capabilities of the user’s device. The previous example is too simple. As mentioned earlier, not all browsers will support this API, or an error may occur while determining the location. It is suggested that we first test if the browser supports Geolocation services and if it does, let’s make sure that we can also handle possible errors that may occur.

Display the Location in a Map

To display the result in a map, you need access to a map service that can use latitude and longitude. In the following example below we use the returned latitude and longitude data to show the location in a Google map.