HTML5 Geolocation: Finding User Position, Track, and Monitoring Location Changes

Discover how to leverage HTML5's geolocation functionality to determine the user's position in this lesson.


What is Geolocation?

The HTML5 geolocation function allows us to retrieve the geographical information (latitude and longitude) of the user's current location. This feature enhances the browsing experience by providing query results that are geographically relevant to the user.


Finding a Visitor's Coordinates

With the geolocation API in HTML5, obtaining the user's location is a straightforward process using the navigator.geolocation object's three functions: getCurrentPosition(), watchPosition(), and clearWatch().

To demonstrate geolocation, we can present a simple example that displays the user's current location after obtaining their consent to share location information.

<script>
    function showPosition() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
                document.getElementById("result").innerHTML = positionInfo;
            });
        } else {
            alert("your browser does not support HTML5 geolocation.");
        }
    }
</script>

<body>
    <div id="result">
        <!--Position information will be inserted here-->
    </div>
    <button type="button" onclick="showPosition();">Display Position</button>
</body>

In this example, when the Display Position button is clicked, the showPosition() function is called. It checks if the navigator.geolocation object is available, and if so, it calls the getCurrentPosition() method to get the user's location. If successful, displaying the latitude and longitude on the web page.

Note: It is important to note that websites must obtain the user's permission before disclosing their location according to geolocation standards.

Finding a visitor's location in HTML is made possible through the Geolocation API, which provides functionality for obtaining coordinates. With HTML5 geolocation, developers can easily retrieve latitude and longitude information, allowing for precise tracking and positioning of the user.


Dealing with Errors and Rejections

In situations where a user does not want to share their location data, you can handle it gracefully by providing two callback functions when calling the getCurrentPosition() method of the Geolocation API. The first function will be called if the geolocation attempt is successful, while the second function will be called if the attempt ends in failure.

The Geolocation API provides a set of error codes that help identify the reason for failures or rejections when attempting to get the user's location. The error codes are available as properties of the PositionError object. Here is a list of the standard error codes:

  1. PERMISSION_DENIED (numeric value: 1): The user denied the request for geolocation.
  2. POSITION_UNAVAILABLE (numeric value: 2): The device was unable to determine the user's position.
  3. TIMEOUT (numeric value: 3): The geolocation request timed out before obtaining the user's position.
  4. UNKNOWN_ERROR (numeric value: 0): An unknown error occurred while attempting to get the user's location.

Let's see an example:

<script>
// Set up global variable
var result;

function showPosition() {
    // Store the element where the page displays the result
    result = document.getElementById("result");

    // If geolocation is available, try to get the visitor's position
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(successCallback, errorCallback);
        result.innerHTML = "Getting the position information...";
    } else {
        alert("your browser does not support HTML5 geolocation.");
    }
};

// Define callback function for successful attempt
function successCallback(position) {
    result.innerHTML = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
}

// Define callback function for failed attempt
function errorCallback(error) {
    if (error.code == 1) {
        result.innerHTML = "You've decided not to share your position, but it's OK. We won't ask you again.";
    } else if (error.code == 2) {
        result.innerHTML = "The network is down or the positioning service can't be reached.";
    } else if (error.code == 3) {
        result.innerHTML = "The attempt timed out before it could get the location data.";
    } else {
        result.innerHTML = "Geolocation failed due to unknown error.";
    }
}
</script>

In this updated example, the showPosition() function calls getCurrentPosition() with two callback functions, showSuccess() and showFailure(). If the user grants permission and the geolocation attempt is successful, the showSuccess() function will be called to display the latitude and longitude. If the user denies permission or the geolocation attempt fails due to other reasons, the showFailure() function will be called to handle the specific error scenario.

When it comes to handling geolocation errors in HTML, web developers need to be equipped to handle various scenarios, including geolocation rejection, troubleshooting issues, and addressing error codes and error messages that may occur. Additionally, managing user permission rejections and implementing error fallbacks are essential aspects of ensuring a seamless geolocation experience in HTML.


Showing Location on Google Map

Geolocation data offers various possibilities, such as displaying the user's location on a Google map. However, it is also possible to create dynamic Google maps with zooming, dragging, and other interactive features. Creating a location-based service, displaying locations on Google Maps can significantly enhance the user experience.

In the provided example, the user's current location is shown on a static Google map using latitude and longitude data retrieved through HTML5 geolocation.

<script src="https://maps.google.com/maps/api/js?sensor=false"></script>

<script>
function showPosition() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showMap, showError);
    } else {
        alert("your browser does not support HTML5 geolocation.");
    }
}

// Define callback function for successful attempt
function showMap(position) {
    // Get location data
    lat = position.coords.latitude;
    long = position.coords.longitude;
    var latlong = new google.maps.LatLng(lat, long);

    var myOptions = {
        center: latlong,
        zoom: 16,
        mapTypeControl: true,
        navigationControlOptions: {
            style: google.maps.NavigationControlStyle.SMALL
        }
    }

    var map = new google.maps.Map(document.getElementById("embedMap"), myOptions);
    var marker = new google.maps.Marker({ position: latlong, map: map, title: "You are here!" });
}

// Define callback function for failed attempt
function showError(error) {
}
</script>

<body>
    <button type="button" onclick="showPosition();">Display MY Position on Google Map</button>
    <div id="embedMap" style="width: 400px; height: 400px;">
        <!--Google map will be embedded here-->
    </div>
</body>

The JavaScript function showMap(position) is designed to display a Google Map with a marker at a specified location. The function starts by extracting the latitude and longitude values from the position object. Next, the function defines the map's appearance and behavior using an options object called myOptions. This object includes properties like the map's center, initial zoom level, and additional settings such as map type control and navigation control options. After defining the options, the function creates a new Google Map instance and attaches it to an HTML element with the ID embedMap. Finally, the function adds a marker to the map, representing the specified location.

With the integration of HTML geolocation and Google Maps, web applications can seamlessly provide users with an accurate display of their location on interactive maps, resulting in a rich and immersive experience. The integration of HTML geolocation with Google Maps empowers developers to build location-aware applications that offer valuable insights and visual representations of user positions.


Monitoring the Visitor's Movement

In all previous examples, we have primarily used the getCurrentPosition() method of the geolocation object to retrieve the visitor's location. However, there's another method called watchPosition() that offers a unique advantage—it allows continuous tracking of the visitor's movement by providing updated positions whenever there is a change in location.

Similar to getCurrentPosition(), watchPosition() also accepts the same input parameters. However, unlike getCurrentPosition(), watchPosition() can trigger the success function multiple times. The first trigger occurs when it initially obtains the location, and subsequently, it calls the success function again whenever it detects a new position update.

This feature enables real-time tracking and is particularly useful when you need to monitor a user's movement or follow their location changes throughout their session on your web application. Let's explore how this functionality operates in practice.

<script>
// Set global variable
var watchID;

function showPosition() {
    if (navigator.geolocation) {
        watchID = navigator.geolocation.watchPosition(successCallback);
    } else {
        alert("your browser does not support HTML5 geolocation.");
    }
}

function successCallback(position) {
    toggleWatchBtn.innerHTML = "Stop Watching";

    // Check position has been changed or not before doing anything
    if (prevLat != position.coords.latitude || prevLong != position.coords.longitude) {

        // Set previous location
        var prevLat = position.coords.latitude;
        var prevLong = position.coords.longitude;

        // Get current position
        var positionInfo = "Your current position is (" + "Latitude: " + position.coords.latitude + ", " + "Longitude: " + position.coords.longitude + ")";
        document.getElementById("result").innerHTML = positionInfo;
    }
}

function startWatch() {
    var result = document.getElementById("result");
    var toggleWatchBtn = document.getElementById("toggleWatchBtn");

    toggleWatchBtn.onclick = function () {
        if (watchID) {
            toggleWatchBtn.innerHTML = "Start Watch";
            navigator.geolocation.clearWatch(watchID);
            watchID = false;
        } else {
            toggleWatchBtn.innerHTML = "Geo Location...";
            showPosition();
        }
    }
}

// Initialise the whole system (above)
window.onload = startWatch;
</script>

<body>
    <button type="button" id="toggleWatchBtn">Start Watch</button>
    <div id="Div1">
        <!--Position information will be inserted here-->
    </div>   
</body>

The above example code uses the watchPosition() method to track a user's movement continuously. The showPosition() function starts watching for position changes, and the successCallback(position) function is called each time the position updates. It updates the displayed position information whenever a change occurs, showing the user's current latitude and longitude. This real-time tracking feature can be valuable for applications requiring live location updates and user movement monitoring.

HTML geolocation monitoring enables real-time tracking of visitor movement, utilizing features such as tracking user location, monitoring user position changes, and providing real-time geolocation updates. By implementing movement monitoring in HTML, developers can enhance the user experience while ensuring privacy considerations and adhering to best practices for monitoring movement with HTML geolocation.


FAQ

What is geolocation in the context of HTML?

Geolocation in the context of HTML refers to the ability to determine the geographic location of a device or user accessing a web application. It allows websites to request and access the latitude and longitude coordinates, as well as other location-related information, of the device.

How do you retrieve the user's current location using the Geolocation API in HTML?

To retrieve the user's current location, you can use the Geolocation API in HTML. By calling the navigator.geolocation.getCurrentPosition() method, you can prompt the browser to request the user's permission to access their location. If granted, the browser will return the current latitude and longitude coordinates through a callback function.

What are some common use cases for geolocation in web applications?

Some common use cases for geolocation in web applications include providing location-based services, such as finding nearby businesses or attractions, displaying customized content based on the user's location, tracking delivery or transportation services, and enhancing user experience with location-aware features.

What are the steps involved in obtaining the user's geolocation in HTML?

The steps involved in obtaining the user's geolocation in HTML typically include checking if the Geolocation API is available in the browser, requesting the user's permission to access their location, handling success or error responses, and retrieving and utilizing the obtained latitude and longitude coordinates in your web application.

How can you handle scenarios where the user denies or does not provide access to their geolocation?

When the user denies or does not provide access to their geolocation, you can handle these scenarios by displaying alternative content or providing manual input options for the user to specify their location. It's important to gracefully handle such scenarios to ensure a smooth user experience.

Can you track the user's location continuously using the Geolocation API?

Yes, it is possible to track the user's location continuously using the Geolocation API. By using the navigator.geolocation.watchPosition() method instead of getCurrentPosition(), you can continuously monitor the user's location and receive updates whenever there is a change in the user's position.

How do you display the user's location on a map using the geolocation data obtained in HTML?

To display the user's location on a map, you would typically use a mapping library or API such as Google Maps or Leaflet. You can use the obtained latitude and longitude coordinates to set the map's center or place a marker representing the user's location.

Are there any security concerns associated with using geolocation in HTML?

Yes, there are security concerns associated with using geolocation in HTML. As location data is considered sensitive information, browsers typically require user consent to share their location. Additionally, it's important to handle user data securely and responsibly, adhering to privacy policies and ensuring that geolocation data is transmitted securely over HTTPS.

Can you customize the accuracy or granularity of geolocation data obtained in HTML?

The accuracy or granularity of geolocation data obtained in HTML is dependent on various factors, including the user's device, browser implementation, and available location providers. However, you can request a specific level of accuracy when using the Geolocation API by setting options such as enableHighAccuracy to true to request a more precise location, if available.

What browser support is there for geolocation in HTML?

Geolocation support in HTML is widely supported by modern browsers, including Chrome, Firefox, Safari, and Edge. However, it's important to check for browser compatibility and fallback options when implementing geolocation in your web application.


Conclusion

HTML geolocation provides powerful functionality for obtaining and utilizing user location in web development. It enables developers to enhance user experiences by displaying accurate location information, integrating with mapping services like Google Maps, and monitoring user movement in real-time. By leveraging HTML geolocation, developers can create dynamic and personalized applications that offer location-based features and insights. However, it is important to handle errors, respect user privacy, and follow best practices when implementing HTML geolocation. With its versatility and capabilities, HTML geolocation opens up exciting possibilities for creating interactive and location-aware web applications.