English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML5 Geolocation

HTML5 Geolocation is used to locate the user's location.

Locate the user's location

HTML5 The Geolocation API is used to obtain the user's geographical location.

Since this feature may infringe on user privacy, user location information is not available unless the user agrees.

Browser Support

Internet Explorer 9+, Firefox, Chrome, Safari, and Opera support Geolocation (geolocation).

Note: Geolocation is more accurate for devices with GPS, such as iPhone.

HTML5 - Using Geolocation

Please use the getCurrentPosition() method to obtain the user's location.

The following is a simple example of geolocation that can return the longitude and latitude of the user's location:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial Website(oldtoolbag.com)</</title> 
</</head>
<body>
<p id="demo">Click the button to get your current coordinates (it may take a long time to retrieve):<//button>
<button onclick="getLocation()">Click Me</button>
<script>
var x = document.getElementById("demo");
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        x.innerHTML="This browser does not support geolocation retrieval.";
    }
}
function showPosition(position)
{
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;    
}
</script>
</body>
</html>
Test to See ‹/›

Example analysis:

  • Check if geolocation is supported

  • If supported, run the getCurrentPosition() method. If not supported, display a message to the user.

  • If getCurrentPosition() runs successfully, it returns a coordinates object to the function specified in the parameter showPosition

  • The showPosition() function obtains and displays latitude and longitude

The example above is a very basic geolocation script without error handling.

Handling errors and denials

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies the function to be executed when the user's location cannot be obtained:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial(oldtoolbag.com)</</title> 
</</head>
<body>
<p id="demo">Click the button to get your current coordinates (it may take a long time to retrieve):<//button>
<button onclick="getLocation()">Click Me</button>
<script>
var x = document.getElementById("demo");
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else
    {
        x.innerHTML="This browser does not support geolocation.";
    }
}
function showPosition(position)
{
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;    
}
function showError(error)
{
    switch(error.code) 
    {
        case error.PERMISSION_DENIED:
            x.innerHTML="The user denied the request for geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML="Request for user geolocation timed out.";
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="Unknown error.";
            break;
    }
}
</script>
</body>
</html>
Test to See ‹/›

Error code:

  • Permission denied - User does not allow geolocation

  • Position unavailable - Unable to obtain current location

  • Timeout - Operation timeout

Display results on the map

To display the results on the map, you need to access a map service that uses latitude and longitude, such as Google Maps or Baidu Maps:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial(oldtoolbag.com)</</title> 
</</head>
<body>
<p id="demo">Click the button to get your current coordinates (it may take a long time to retrieve):<//button>
<button onclick="getLocation()">Click Me</button>
<div id="mapholder"></div>
<script>
var x = document.getElementById("demo");
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else
    {
        x.innerHTML="This browser does not support geolocation retrieval.";
    }
}
function showPosition(position)
{
    var latlon=position.coords.latitude+","+position.coords.longitude;
    var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&zoom=14&size=400x300&sensor=false";
    document.getElementById("mapholder").innerHTML="<img src='"+img_url+"'>";
}
function showError(error)
{
    switch(error.code) 
    {
        case error.PERMISSION_DENIED:
            x.innerHTML="The user denied the request for geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
            break;
        case error.TIMEOUT:
            x.innerHTML="Request for user geolocation timed out.";
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="Unknown error.";
            break;
    }
}
</script>
</body>
</html>
Test to See ‹/›

In the example above, we used the returned latitude and longitude data to display the location on Google Maps (using static images).

Google Maps Script
The following link shows you how to use scripts to display an interactive map with markers, zoom, and drag options.

Information about a given location

This page demonstrates how to display the user's location on a map. However, geolocation is also very useful for information about a given location.

Example:

  • Update local information

  • Display points of interest around the user

  • Interactive Vehicle Navigation System (GPS)

getCurrentPosition() method - Return data

If successful, the getCurrentPosition() method returns an object. It always returns latitude, longitude, and accuracy properties. If available, it will return other properties listed below.

PropertyDescription
coords.latitudeDecimal degree latitude
coords.longitudeDecimal degree longitude
coords.accuracyLocation accuracy
coords.altitudeAltitude, in meters above sea level
coords.altitudeAccuracyAltitude accuracy of the location
coords.headingDirection, measured in degrees from true north
coords.speedSpeed, in meters/Every second
timestampResponse date/Time

Geolocation Object - Other interesting methods

watchPosition(); - Returns the user's current position and continues to return the user's updated position as they move (like a GPS on a car).

clearWatch(); - Stop the watchPosition() method

The following example demonstrates the watchPosition() method. You will need a GPS device with good accuracy to test this example (such as an iPhone):

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>Basic Tutorial(oldtoolbag.com)</</title> 
</</head>
<body>
<p id="demo">Click the button to get your current coordinates (it may take a long time to retrieve):<//button>
<button onclick="getLocation()">Click Me</button>
<script>
var x = document.getElementById("demo");
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.watchPosition(showPosition);
    }
    else
    {
        x.innerHTML="This browser does not support geolocation retrieval.";
    }
}
function showPosition(position)
{
    x.innerHTML="Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude;    
}
</script>
</body>
</html>
Test to See ‹/›