kunal-chowdhury.com

Showing Geolocation in Browser using HTML5 and JavaScript


Few days ago, we learned about “Easy Form Validation using HTML5”. Hope, you liked that post. Today we will explore another new great feature of HTML5 with complete code analysis and simple but easy to understandable demo.

 

HTML5 exposes geolocation API to get the geographical location of user. Today we will focus our discussion on this topic. So, continue reading.

 

HTML5 geolocation API is used to get the geographical location of a user. Using the navigator, user can retrieve the current location and you can pass that location to show that location in a Map.

 

The API supports the following browsers: IE9+, Firefox, Chrome and Opera.

 

To implement this in your web page, you need to follow the below mentioned steps:

    • Check whether the geolocation API is supported by the underlying browser.
    • If supported, call the navigator.geolocation.getCurrentPosition() method and if not supported, display a proper message to the user.
    • If the navigator.geolocation.getCurrentPosition() successfully retrieves the user’s current position, it returns a coordinate object to the function “showPosition” specified as first parameter passed to this method.
    • The showPosition() function displays the latitude and longitude of the current location.
    • Further enhance it to show the position in a map by using a map service like Google Map.

Here is the code snippet of the implementation:

 
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition, showError);
    }
    else { message.innerHTML = "Geolocation is not supported by this browser."; }
}
 
function showPosition(position) {
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;
    var imageURL = "http://maps.googleapis.com/maps/api/staticmap?center="
    + latitude + "," + longitude + "&zoom=14&size=400x300&sensor=false";
 
    document.getElementById("locationHolder").innerHTML = 
                    "Your current location is: (" + latitude + ", " + longitude + ")";
    document.getElementById("mapHolder").innerHTML = "<img src='" + imageURL + "'>";
}

 

 

Don’t forget to handle the user interaction and error status properly. Based on the error code, show a proper message to the user. Here is the code snippet of the same, for your reference:

 
function showError(error) {
    switch (error.code) {
        case error.PERMISSION_DENIED:
            message.innerHTML = "User denied the request for Geolocation."
            break;
        case error.POSITION_UNAVAILABLE:
            message.innerHTML = "Location information is unavailable at this time."
            break;
        case error.TIMEOUT:
            message.innerHTML = "The request to get user location timed out."
            break;
        case error.UNKNOWN_ERROR:
            message.innerHTML = "An unknown error occurred. Try again later."
            break;
    }
}

 

Hope, this code snippet is clear to you and you will now be able to retrieve the user location and show it using a map service. In our case, we used Google Map to pass the latitude and longitude to the API as shown above.

 

HTML5 Geolocation Demo

Let’s see a demo of the same. Click the button below to call the getCurrentPosition() method. Once it retrieves the location coordinate, it will show you the coordinate (latitude and longitude) in the page. Also, it will show you that position in Google map. Check it out here:

 

Click the button below to show your current position in map:

 

 

The complete code of the above implementation is mentioned here, for your reference:

 
<!DOCTYPE html>
<html>
<head>
    <title>HTML5 Geolocation Demo</title>
</head>
<body>
    <p id="message">Click the button below to show your current position in map:</p>
    <button onclick="getLocation()">Show Geolocation</button>
    <div id="locationHolder"></div>
    <div id="mapHolder"></div>
 
    <script language="JavaScript">
        var message = document.getElementById("message");
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition, showError);
            }
            else { message.innerHTML = "Geolocation is not supported by this browser."; }
        }
 
        function showPosition(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;
            var imageURL = "http://maps.googleapis.com/maps/api/staticmap?center="
            + latitude + "," + longitude + "&zoom=14&size=400x300&sensor=false";
 
            document.getElementById("locationHolder").innerHTML = 
                        "Your current location is: (" + latitude + ", " + longitude + ")";
            document.getElementById("mapHolder").innerHTML = "<img src='" + imageURL + "'>";
        }
 
        function showError(error) {
            switch (error.code) {
                case error.PERMISSION_DENIED:
                    message.innerHTML = "User denied the request for Geolocation."
                    break;
                case error.POSITION_UNAVAILABLE:
                    message.innerHTML = "Location information is unavailable at this time."
                    break;
                case error.TIMEOUT:
                    message.innerHTML = "The request to get user location timed out."
                    break;
                case error.UNKNOWN_ERROR:
                    message.innerHTML = "An unknown error occurred. Try again later."
                    break;
            }
        }
    </script>
</body>
</html>

 

 

I hope, this post will be helpful for you to understand the API and showing position in Google map. Let me know, if you have further queries on it. Don’t forget to share it to your network and help your friends to learn about it.

 

I am available in Twitter, Facebook and Google+. Don’t forget to connect with me for updates and technical discussions. Also, subscribe to my blog’s RSS feed and Email Newsletter to get the blog updates directly in your inbox. Cheers. Happy Coding.


Kunal Chowdhury
If you have come this far, it means that you liked what you are reading (Showing Geolocation in Browser using HTML5 and JavaScript).

Why not reach little more and connect with me directly on Twitter, Facebook, Google+ and LinkedIn. I would love to hear your thoughts and opinions.

Authored Books: