Using the HTML5 Geolocation API

Share this article

Knowing the location of your users can help boost the quality of your website and the speed of your service. In the past, users had to actively input their location and submit it to a site, either by typing it, using a long drop-down list, or clicking a map. Now, with the HTML5 Geolocation API, finding your users (with their permission) is easier than ever. Figure 1 shows a website using geolocation to determine the location of a user, represented in latitude and longitude. The numbers can easily be translated into something more understandable, such as the street name or city. showing user location Figure 1 Showing a User’s Location with the Help of Geolocation Imagine how useful your site could be if it provided online timetables for all public transportation in a particular city. Using geolocation, the site could recommend optimal travel routes to get people where they’re going as quickly as possible. Desktop users could get their start location sorted by proximity to their computer. Mobile users trying to get home after a night out could quickly find the closest bus stop within walking distance. These possibilities and more are just an API away.

Scenarios for Using the Geolocation API

Here are 12 simple scenarios that illustrate how a website can accommodate users and customize their experience by taking their location into account. Some of them might seem obvious, but the small things often make the biggest differences.
  • Public transportation sites can list nearby bus stops and metro locations.
  • Late night out? Taxi or car service websites can find where you are, even if you don’t know.
  • Shopping sites can immediately provide estimates for shipping costs.
  • Travel agencies can provide better vacation tips for current location and season.
  • Content sites can more accurately determine the language and dialect of search queries.
  • Real estate sites can present average house prices in a particular area, a handy tool when you’re driving around to check out a neighborhood or visit open houses.
  • Movie theater sites can promote films playing nearby.
  • Online games can blend reality into the game play by giving users missions to accomplish in the real world.
  • News sites can include customized local headlines and weather on their front page.
  • Online stores can inform whether products are in stock at local retailers.
  • Sports and entertainment ticket sales sites can promote upcoming games and shows nearby.
  • Job postings can automatically include potential commute times.

How Geolocation Works

Technically speaking, a PC or a mobile device has several ways to find out its own location (hopefully, in the same place as the user).
  • GPS is the most accurate way to determine positioning, but it’s less energy efficient than other options and sometimes requires a lengthy startup time.
  • A-GPS (assistive GPS) uses triangulation between mobile phone towers and public masts to determine location. Although not as precise as GPS, A-GPS is sufficient for many scenarios.
  • Mobile devices that support Wi-Fi access points can use hotspots to determine the user’s location.
  • Stationary computers without wireless devices can obtain rough location information using known IP address ranges.
When it comes to sharing the physical location of users, privacy is a serious concern. According to the Geolocation API, “user agents must not send location information to websites without the express permission of the user.” In other words, a user must always opt in to share location information with a website. Figure 2 shows a typical message requesting a user’s permission. For more information about ensuring security with the Geolocation API, see Security and privacy considerations. user permission request Figure 2 Sample User Permission Request

Three Simple Functions

Are you ready to incorporate geolocation into your website? You need to learn only three simple functions to master the entire API, which resides within the geolocation object, an attribute of the Navigator object. Learn more about the geolocation object here. The getCurrentPosition function gets the user location one time. It takes two arguments in the form of callbacks: one for a successful location query and one for a failed location query. The success callback takes a Position object as an argument. It optionally takes a third argument in the form of a PositionOptions object.
navigator.geolocation.getCurrentPosition(locationSuccess, locationFail);
    function locationSuccess(position) {
        latitude = position.coords.latitude;
	longitude = position.coords.longitude;
    }

    function locationFail() {
        alert(‘Oops, could not find you.’);
    }
The Position object contains the properties shown below. Properties of the Position Object
Property Value Unit
coords.latitude double degrees
coords.longitude double degrees
coords.altitude double or null meters
coords.accuracy double meters
coords.altitudeAccuracy double or null meters
coords.heading double or null degrees clockwise
coords.speed double or null meters/second
timestamp DOMTimeStamp like the Date object
The watchPosition function keeps polling for user position and returns an associated ID. The device determines the rate of updates and pushes changes in location to the server. The clearWatch function stops polling for user position. It takes the ID of watchPosition as an argument.

Presenting Location Data: Geodetic or Civic

There are two ways of presenting location data to the user: geodetic and civil. The geodetic way of describing position refers directly to latitude and longitude. The civic representation of location data is a more human readable and understandable format. Each parameter has both a geodetic representation and a civic representation, as illustrated below. Examples of Geodetic and Civic Data
Attribute Geodetic Civic
Position 59.3, 18.6 Stockholm
Elevation 10 meters 4th floor
Heading 234 degrees To the city center
Speed 5 km / h Walking
Orientation 45 degrees North-East
When using the Geolocation API, you get the geodetic data back from the functions. Presenting location data in raw numbers is rarely friendly or useful. Online services, such as Bing Maps and Yahoo GeoPlanet can help you translate between the two presentation modes.

Browser Support

IE FF Chrome Opera
Internet Explorer 9+ Firefox 3.5+ Chrome 5+ Opera 10.6+
Safari iPhone Android Windows Phone
Safari 5+ iPhone 3+ Android 2+ Windows Phone 7.5+

Browsers that support the HTML5 Geolocation API

Even though geolocation works in all the major browsers, you still have to take into account the scenarios in which location can’t be provided. For example, a user might be running an older browser or have hardware that doesn’t include positioning devices, or simply might not want to automatically share location information. The location detected could even be incorrect. In such situations, you should always include an alternative or a fallback method so users can enter or change their location manually.

Geolocation in Action

Copy and paste the example code below and save it as an HTML file. Open it in your favorite browser and follow the two-step instructions on the website to see the Geolocation API draw a blue circle around your current location. Using the Geolocation API
<!doctype html>
<html lang="en">
<head>
    <title>Geolocation demo</title>
    <meta charset="utf-8" />
</head>
<body>
    <h1>Geolocation demo</h1>
    <p>
        Find out approximately where you are.
    </p> 
    <p> 
        Step 1: <button onclick="GetMap()">Show map</button> 
    </p> 
    <p> 
        Step 2: When prompted, allow your location to be shared to see Geolocation in action 
    </p> 
    <div id="mapDiv" style="position: relative; width: 800px; height: 600px;"></div> 
    <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script> 
    <script type="text/javascript"> 
        var map = null; 
        function GetMap() { 
            /* Replace YOUR_BING_MAPS_KEY with your own credentials. 
            Obtain a key by signing up for a developer account at 
            http://www.microsoft.com/maps/developers/ */ 
        var cred = "YOUR_BING_MAPS_KEY"; 
        // Initialize map 
        map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), 
           { credentials: cred }); 
        // Check if browser supports geolocation 
        if (navigator.geolocation) { 
            navigator.geolocation.getCurrentPosition(locateSuccess, locateFail);
        } 
        else { 
            alert('I'm sorry, but Geolocation is not supported in your current browser.'); 
        } 
    } 
    // Successful geolocation 
    function locateSuccess(loc) { 
        // Set the user's location 
        var userLocation = new Microsoft.Maps.Location(loc.coords.latitude, loc.coords.longitude); 
        // Zoom in on user's location on map 
        map.setView({ center: userLocation, zoom: 17 }); 
        // Draw circle of area where user is located 
        var locationArea = drawCircle(userLocation); 
        map.entities.push(locationArea);
    } 
    // Unsuccessful geolocation 
    function locateFail(geoPositionError) { 
        switch (geoPositionError.code) { 
            case 0: // UNKNOWN_ERROR 
                alert('An unknown error occurred, sorry'); 
                break; 
            case 1: // PERMISSION_DENIED 
                alert('Permission to use Geolocation was denied'); 
                break; 
            case 2: // POSITION_UNAVAILABLE 
                alert('Couldn't find you...'); 
                break; 
            case 3: // TIMEOUT 
                alert('The Geolocation request took too long and timed out'); 
                break; 
            default: 
        } 
    }
    // Draw blue circle on top of user's location 
    function drawCircle(loc) { 
        var radius = 100; 
        var R = 6378137; 
        var lat = (loc.latitude * Math.PI) / 180; 
        var lon = (loc.longitude * Math.PI) / 180; 
        var d = parseFloat(radius) / R; 
        var locs = new Array(); 
        for (x = 0; x <= 360; x++) { 
            var p = new Microsoft.Maps.Location(); 
            brng = x * Math.PI / 180; 
            p.latitude = Math.asin(Math.sin(lat) * Math.cos(d) + Math.cos(lat) * Math.sin(d) * Math.cos(brng)); 
            p.longitude = ((lon + Math.atan2(Math.sin(brng) * Math.sin(d) * Math.cos(lat), Math.cos(d) - Math.sin(lat) * Math.sin(p.latitude))) * 180) / Math.PI; 
            p.latitude = (p.latitude * 180) / Math.PI; 
            locs.push(p); 
        } 
        return new Microsoft.Maps.Polygon(locs, { fillColor: new Microsoft.Maps.Color(125, 0, 0, 255), strokeColor: new Microsoft.Maps.Color(0, 0, 0, 255) }); 
    } 
  </script> 
</body> 
</html>
If you run the code as is, your location will be shown along with a message about invalid credentials, as shown in Figure 3
. To get a result without the warning text (Figure 4), you need to replace YOUR_BING_MAPS_KEY with your own key, which is generated when you sign up for a Bing Maps Developer account. mapping without a valid key Figure 3 Geolocation Demo Mapping a Location without a Valid Key mapping a location with a valid key Figure 4 Geolocation Demo Mapping a Location after Inserting a Valid Key To see other examples of geolocation, which map your location using a push pin, visit IE Test Drive or attend an HTML5 Web Camp. Learn more about geolocation here:

Frequently Asked Questions about HTML5 Geolocation API

What is the HTML5 Geolocation API and how does it work?

The HTML5 Geolocation API is a powerful tool that allows developers to retrieve the geographical location information of a user. It works by accessing the latitude and longitude coordinates of the user’s device. This information can be used to provide location-specific data or services to the user. The API works across different devices such as desktops, laptops, smartphones, and tablets. It’s important to note that for privacy reasons, the user’s permission is required before accessing their location information.

How can I use the HTML5 Geolocation API in my web application?

To use the HTML5 Geolocation API in your web application, you need to call the navigator.geolocation.getCurrentPosition() method. This method retrieves the current geographical location of the user’s device. It takes two callback functions as parameters: one for success and one for error. The success callback function is called with a Position object if the location retrieval is successful. The error callback function is called with a PositionError object if there is an error.

What are some practical applications of the HTML5 Geolocation API?

The HTML5 Geolocation API has a wide range of practical applications. It can be used to provide location-specific services such as weather updates, local news, or personalized recommendations. It can also be used in mapping applications to provide directions or show the user’s current location. Other applications include tracking user location for analytics, enhancing e-commerce experiences by suggesting local stores, or providing location-based game experiences.

What are the privacy considerations when using the HTML5 Geolocation API?

Privacy is a major concern when dealing with location data. The HTML5 Geolocation API requires user permission before it can access location data. The user can choose to grant or deny permission, and they can also revoke permission at any time. It’s important for developers to respect user privacy and use location data responsibly. This includes informing users why their location data is needed and how it will be used.

How accurate is the location data provided by the HTML5 Geolocation API?

The accuracy of the location data provided by the HTML5 Geolocation API can vary depending on several factors. These include the device being used, the method used to determine the location, and the environmental conditions. For example, GPS can provide very accurate location data, but it may not work well indoors or in urban areas with tall buildings. Network-based methods such as IP address lookup or cell tower triangulation may be less accurate, but they can work in a wider range of conditions.

Can I use the HTML5 Geolocation API in all browsers?

Most modern web browsers support the HTML5 Geolocation API, including Chrome, Firefox, Safari, and Edge. However, it’s always a good idea to check the browser compatibility before using the API. You can do this by using the navigator.geolocation property. If this property exists, then the browser supports the Geolocation API.

What are the error handling mechanisms in the HTML5 Geolocation API?

The HTML5 Geolocation API provides several error handling mechanisms. The navigator.geolocation.getCurrentPosition() method takes an error callback function as a parameter. This function is called with a PositionError object if there is an error in retrieving the location data. The PositionError object has two properties: code and message. The code property is a numerical value representing the error code, and the message property is a human-readable string describing the error.

Can I track a user’s movement with the HTML5 Geolocation API?

Yes, the HTML5 Geolocation API provides a method called navigator.geolocation.watchPosition() that allows you to track a user’s movement. This method works similarly to the getCurrentPosition() method, but it keeps watching the user’s location and calls the success callback function every time the location changes.

How can I improve the accuracy of the location data?

The accuracy of the location data can be improved by using a combination of different methods to determine the location. For example, you can use GPS, network-based methods, and device sensors together to get a more accurate location. The PositionOptions object passed to the getCurrentPosition() or watchPosition() methods allows you to specify the desired accuracy.

How can I stop tracking a user’s location?

If you are using the navigator.geolocation.watchPosition() method to track a user’s location, you can stop tracking by calling the navigator.geolocation.clearWatch() method. This method takes the ID returned by the watchPosition() method and stops the watch operation.

Danwei Tran LucianiDanwei Tran Luciani
View Author

Danwei Tran Luciani is a developer evangelist at Microsoft. Her current focus is HTML5 and the next version of Windows. When she isn’t putting her M.Sc. degrees in Software Engineering and Interaction Design to use, she enjoys playing on the XBOX and geocaching. She tweets regularly and blogs sporadically.

geolocationHTML5 Dev Center
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week